##// END OF EJS Templates
tests: get run-tests to reliably hand shellquote a string and not a bytes...
Augie Fackler -
r35841:4be99133 default
parent child Browse files
Show More
@@ -1,3032 +1,3036 b''
1 #!/usr/bin/env python
1 #!/usr/bin/env python
2 #
2 #
3 # run-tests.py - Run a set of tests on Mercurial
3 # run-tests.py - Run a set of tests on Mercurial
4 #
4 #
5 # Copyright 2006 Matt Mackall <mpm@selenic.com>
5 # Copyright 2006 Matt Mackall <mpm@selenic.com>
6 #
6 #
7 # This software may be used and distributed according to the terms of the
7 # This software may be used and distributed according to the terms of the
8 # GNU General Public License version 2 or any later version.
8 # GNU General Public License version 2 or any later version.
9
9
10 # Modifying this script is tricky because it has many modes:
10 # Modifying this script is tricky because it has many modes:
11 # - serial (default) vs parallel (-jN, N > 1)
11 # - serial (default) vs parallel (-jN, N > 1)
12 # - no coverage (default) vs coverage (-c, -C, -s)
12 # - no coverage (default) vs coverage (-c, -C, -s)
13 # - temp install (default) vs specific hg script (--with-hg, --local)
13 # - temp install (default) vs specific hg script (--with-hg, --local)
14 # - tests are a mix of shell scripts and Python scripts
14 # - tests are a mix of shell scripts and Python scripts
15 #
15 #
16 # If you change this script, it is recommended that you ensure you
16 # If you change this script, it is recommended that you ensure you
17 # haven't broken it by running it in various modes with a representative
17 # haven't broken it by running it in various modes with a representative
18 # sample of test scripts. For example:
18 # sample of test scripts. For example:
19 #
19 #
20 # 1) serial, no coverage, temp install:
20 # 1) serial, no coverage, temp install:
21 # ./run-tests.py test-s*
21 # ./run-tests.py test-s*
22 # 2) serial, no coverage, local hg:
22 # 2) serial, no coverage, local hg:
23 # ./run-tests.py --local test-s*
23 # ./run-tests.py --local test-s*
24 # 3) serial, coverage, temp install:
24 # 3) serial, coverage, temp install:
25 # ./run-tests.py -c test-s*
25 # ./run-tests.py -c test-s*
26 # 4) serial, coverage, local hg:
26 # 4) serial, coverage, local hg:
27 # ./run-tests.py -c --local test-s* # unsupported
27 # ./run-tests.py -c --local test-s* # unsupported
28 # 5) parallel, no coverage, temp install:
28 # 5) parallel, no coverage, temp install:
29 # ./run-tests.py -j2 test-s*
29 # ./run-tests.py -j2 test-s*
30 # 6) parallel, no coverage, local hg:
30 # 6) parallel, no coverage, local hg:
31 # ./run-tests.py -j2 --local test-s*
31 # ./run-tests.py -j2 --local test-s*
32 # 7) parallel, coverage, temp install:
32 # 7) parallel, coverage, temp install:
33 # ./run-tests.py -j2 -c test-s* # currently broken
33 # ./run-tests.py -j2 -c test-s* # currently broken
34 # 8) parallel, coverage, local install:
34 # 8) parallel, coverage, local install:
35 # ./run-tests.py -j2 -c --local test-s* # unsupported (and broken)
35 # ./run-tests.py -j2 -c --local test-s* # unsupported (and broken)
36 # 9) parallel, custom tmp dir:
36 # 9) parallel, custom tmp dir:
37 # ./run-tests.py -j2 --tmpdir /tmp/myhgtests
37 # ./run-tests.py -j2 --tmpdir /tmp/myhgtests
38 # 10) parallel, pure, tests that call run-tests:
38 # 10) parallel, pure, tests that call run-tests:
39 # ./run-tests.py --pure `grep -l run-tests.py *.t`
39 # ./run-tests.py --pure `grep -l run-tests.py *.t`
40 #
40 #
41 # (You could use any subset of the tests: test-s* happens to match
41 # (You could use any subset of the tests: test-s* happens to match
42 # enough that it's worth doing parallel runs, few enough that it
42 # enough that it's worth doing parallel runs, few enough that it
43 # completes fairly quickly, includes both shell and Python scripts, and
43 # completes fairly quickly, includes both shell and Python scripts, and
44 # includes some scripts that run daemon processes.)
44 # includes some scripts that run daemon processes.)
45
45
46 from __future__ import absolute_import, print_function
46 from __future__ import absolute_import, print_function
47
47
48 import argparse
48 import argparse
49 import collections
49 import collections
50 import difflib
50 import difflib
51 import distutils.version as version
51 import distutils.version as version
52 import errno
52 import errno
53 import json
53 import json
54 import os
54 import os
55 import random
55 import random
56 import re
56 import re
57 import shutil
57 import shutil
58 import signal
58 import signal
59 import socket
59 import socket
60 import subprocess
60 import subprocess
61 import sys
61 import sys
62 import sysconfig
62 import sysconfig
63 import tempfile
63 import tempfile
64 import threading
64 import threading
65 import time
65 import time
66 import unittest
66 import unittest
67 import xml.dom.minidom as minidom
67 import xml.dom.minidom as minidom
68
68
69 try:
69 try:
70 import Queue as queue
70 import Queue as queue
71 except ImportError:
71 except ImportError:
72 import queue
72 import queue
73
73
74 try:
74 try:
75 import shlex
75 import shlex
76 shellquote = shlex.quote
76 shellquote = shlex.quote
77 except (ImportError, AttributeError):
77 except (ImportError, AttributeError):
78 import pipes
78 import pipes
79 shellquote = pipes.quote
79 shellquote = pipes.quote
80
80
81 if os.environ.get('RTUNICODEPEDANTRY', False):
81 if os.environ.get('RTUNICODEPEDANTRY', False):
82 try:
82 try:
83 reload(sys)
83 reload(sys)
84 sys.setdefaultencoding("undefined")
84 sys.setdefaultencoding("undefined")
85 except NameError:
85 except NameError:
86 pass
86 pass
87
87
88 origenviron = os.environ.copy()
88 origenviron = os.environ.copy()
89 osenvironb = getattr(os, 'environb', os.environ)
89 osenvironb = getattr(os, 'environb', os.environ)
90 processlock = threading.Lock()
90 processlock = threading.Lock()
91
91
92 pygmentspresent = False
92 pygmentspresent = False
93 # ANSI color is unsupported prior to Windows 10
93 # ANSI color is unsupported prior to Windows 10
94 if os.name != 'nt':
94 if os.name != 'nt':
95 try: # is pygments installed
95 try: # is pygments installed
96 import pygments
96 import pygments
97 import pygments.lexers as lexers
97 import pygments.lexers as lexers
98 import pygments.lexer as lexer
98 import pygments.lexer as lexer
99 import pygments.formatters as formatters
99 import pygments.formatters as formatters
100 import pygments.token as token
100 import pygments.token as token
101 import pygments.style as style
101 import pygments.style as style
102 pygmentspresent = True
102 pygmentspresent = True
103 difflexer = lexers.DiffLexer()
103 difflexer = lexers.DiffLexer()
104 terminal256formatter = formatters.Terminal256Formatter()
104 terminal256formatter = formatters.Terminal256Formatter()
105 except ImportError:
105 except ImportError:
106 pass
106 pass
107
107
108 if pygmentspresent:
108 if pygmentspresent:
109 class TestRunnerStyle(style.Style):
109 class TestRunnerStyle(style.Style):
110 default_style = ""
110 default_style = ""
111 skipped = token.string_to_tokentype("Token.Generic.Skipped")
111 skipped = token.string_to_tokentype("Token.Generic.Skipped")
112 failed = token.string_to_tokentype("Token.Generic.Failed")
112 failed = token.string_to_tokentype("Token.Generic.Failed")
113 skippedname = token.string_to_tokentype("Token.Generic.SName")
113 skippedname = token.string_to_tokentype("Token.Generic.SName")
114 failedname = token.string_to_tokentype("Token.Generic.FName")
114 failedname = token.string_to_tokentype("Token.Generic.FName")
115 styles = {
115 styles = {
116 skipped: '#e5e5e5',
116 skipped: '#e5e5e5',
117 skippedname: '#00ffff',
117 skippedname: '#00ffff',
118 failed: '#7f0000',
118 failed: '#7f0000',
119 failedname: '#ff0000',
119 failedname: '#ff0000',
120 }
120 }
121
121
122 class TestRunnerLexer(lexer.RegexLexer):
122 class TestRunnerLexer(lexer.RegexLexer):
123 tokens = {
123 tokens = {
124 'root': [
124 'root': [
125 (r'^Skipped', token.Generic.Skipped, 'skipped'),
125 (r'^Skipped', token.Generic.Skipped, 'skipped'),
126 (r'^Failed ', token.Generic.Failed, 'failed'),
126 (r'^Failed ', token.Generic.Failed, 'failed'),
127 (r'^ERROR: ', token.Generic.Failed, 'failed'),
127 (r'^ERROR: ', token.Generic.Failed, 'failed'),
128 ],
128 ],
129 'skipped': [
129 'skipped': [
130 (r'[\w-]+\.(t|py)', token.Generic.SName),
130 (r'[\w-]+\.(t|py)', token.Generic.SName),
131 (r':.*', token.Generic.Skipped),
131 (r':.*', token.Generic.Skipped),
132 ],
132 ],
133 'failed': [
133 'failed': [
134 (r'[\w-]+\.(t|py)', token.Generic.FName),
134 (r'[\w-]+\.(t|py)', token.Generic.FName),
135 (r'(:| ).*', token.Generic.Failed),
135 (r'(:| ).*', token.Generic.Failed),
136 ]
136 ]
137 }
137 }
138
138
139 runnerformatter = formatters.Terminal256Formatter(style=TestRunnerStyle)
139 runnerformatter = formatters.Terminal256Formatter(style=TestRunnerStyle)
140 runnerlexer = TestRunnerLexer()
140 runnerlexer = TestRunnerLexer()
141
141
142 if sys.version_info > (3, 5, 0):
142 if sys.version_info > (3, 5, 0):
143 PYTHON3 = True
143 PYTHON3 = True
144 xrange = range # we use xrange in one place, and we'd rather not use range
144 xrange = range # we use xrange in one place, and we'd rather not use range
145 def _bytespath(p):
145 def _bytespath(p):
146 if p is None:
146 if p is None:
147 return p
147 return p
148 return p.encode('utf-8')
148 return p.encode('utf-8')
149
149
150 def _strpath(p):
150 def _strpath(p):
151 if p is None:
151 if p is None:
152 return p
152 return p
153 return p.decode('utf-8')
153 return p.decode('utf-8')
154
154
155 elif sys.version_info >= (3, 0, 0):
155 elif sys.version_info >= (3, 0, 0):
156 print('%s is only supported on Python 3.5+ and 2.7, not %s' %
156 print('%s is only supported on Python 3.5+ and 2.7, not %s' %
157 (sys.argv[0], '.'.join(str(v) for v in sys.version_info[:3])))
157 (sys.argv[0], '.'.join(str(v) for v in sys.version_info[:3])))
158 sys.exit(70) # EX_SOFTWARE from `man 3 sysexit`
158 sys.exit(70) # EX_SOFTWARE from `man 3 sysexit`
159 else:
159 else:
160 PYTHON3 = False
160 PYTHON3 = False
161
161
162 # In python 2.x, path operations are generally done using
162 # In python 2.x, path operations are generally done using
163 # bytestrings by default, so we don't have to do any extra
163 # bytestrings by default, so we don't have to do any extra
164 # fiddling there. We define the wrapper functions anyway just to
164 # fiddling there. We define the wrapper functions anyway just to
165 # help keep code consistent between platforms.
165 # help keep code consistent between platforms.
166 def _bytespath(p):
166 def _bytespath(p):
167 return p
167 return p
168
168
169 _strpath = _bytespath
169 _strpath = _bytespath
170
170
171 # For Windows support
171 # For Windows support
172 wifexited = getattr(os, "WIFEXITED", lambda x: False)
172 wifexited = getattr(os, "WIFEXITED", lambda x: False)
173
173
174 # Whether to use IPv6
174 # Whether to use IPv6
175 def checksocketfamily(name, port=20058):
175 def checksocketfamily(name, port=20058):
176 """return true if we can listen on localhost using family=name
176 """return true if we can listen on localhost using family=name
177
177
178 name should be either 'AF_INET', or 'AF_INET6'.
178 name should be either 'AF_INET', or 'AF_INET6'.
179 port being used is okay - EADDRINUSE is considered as successful.
179 port being used is okay - EADDRINUSE is considered as successful.
180 """
180 """
181 family = getattr(socket, name, None)
181 family = getattr(socket, name, None)
182 if family is None:
182 if family is None:
183 return False
183 return False
184 try:
184 try:
185 s = socket.socket(family, socket.SOCK_STREAM)
185 s = socket.socket(family, socket.SOCK_STREAM)
186 s.bind(('localhost', port))
186 s.bind(('localhost', port))
187 s.close()
187 s.close()
188 return True
188 return True
189 except socket.error as exc:
189 except socket.error as exc:
190 if exc.errno == errno.EADDRINUSE:
190 if exc.errno == errno.EADDRINUSE:
191 return True
191 return True
192 elif exc.errno in (errno.EADDRNOTAVAIL, errno.EPROTONOSUPPORT):
192 elif exc.errno in (errno.EADDRNOTAVAIL, errno.EPROTONOSUPPORT):
193 return False
193 return False
194 else:
194 else:
195 raise
195 raise
196 else:
196 else:
197 return False
197 return False
198
198
199 # useipv6 will be set by parseargs
199 # useipv6 will be set by parseargs
200 useipv6 = None
200 useipv6 = None
201
201
202 def checkportisavailable(port):
202 def checkportisavailable(port):
203 """return true if a port seems free to bind on localhost"""
203 """return true if a port seems free to bind on localhost"""
204 if useipv6:
204 if useipv6:
205 family = socket.AF_INET6
205 family = socket.AF_INET6
206 else:
206 else:
207 family = socket.AF_INET
207 family = socket.AF_INET
208 try:
208 try:
209 s = socket.socket(family, socket.SOCK_STREAM)
209 s = socket.socket(family, socket.SOCK_STREAM)
210 s.bind(('localhost', port))
210 s.bind(('localhost', port))
211 s.close()
211 s.close()
212 return True
212 return True
213 except socket.error as exc:
213 except socket.error as exc:
214 if exc.errno not in (errno.EADDRINUSE, errno.EADDRNOTAVAIL,
214 if exc.errno not in (errno.EADDRINUSE, errno.EADDRNOTAVAIL,
215 errno.EPROTONOSUPPORT):
215 errno.EPROTONOSUPPORT):
216 raise
216 raise
217 return False
217 return False
218
218
219 closefds = os.name == 'posix'
219 closefds = os.name == 'posix'
220 def Popen4(cmd, wd, timeout, env=None):
220 def Popen4(cmd, wd, timeout, env=None):
221 processlock.acquire()
221 processlock.acquire()
222 p = subprocess.Popen(cmd, shell=True, bufsize=-1, cwd=wd, env=env,
222 p = subprocess.Popen(cmd, shell=True, bufsize=-1, cwd=wd, env=env,
223 close_fds=closefds,
223 close_fds=closefds,
224 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
224 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
225 stderr=subprocess.STDOUT)
225 stderr=subprocess.STDOUT)
226 processlock.release()
226 processlock.release()
227
227
228 p.fromchild = p.stdout
228 p.fromchild = p.stdout
229 p.tochild = p.stdin
229 p.tochild = p.stdin
230 p.childerr = p.stderr
230 p.childerr = p.stderr
231
231
232 p.timeout = False
232 p.timeout = False
233 if timeout:
233 if timeout:
234 def t():
234 def t():
235 start = time.time()
235 start = time.time()
236 while time.time() - start < timeout and p.returncode is None:
236 while time.time() - start < timeout and p.returncode is None:
237 time.sleep(.1)
237 time.sleep(.1)
238 p.timeout = True
238 p.timeout = True
239 if p.returncode is None:
239 if p.returncode is None:
240 terminate(p)
240 terminate(p)
241 threading.Thread(target=t).start()
241 threading.Thread(target=t).start()
242
242
243 return p
243 return p
244
244
245 PYTHON = _bytespath(sys.executable.replace('\\', '/'))
245 PYTHON = _bytespath(sys.executable.replace('\\', '/'))
246 IMPL_PATH = b'PYTHONPATH'
246 IMPL_PATH = b'PYTHONPATH'
247 if 'java' in sys.platform:
247 if 'java' in sys.platform:
248 IMPL_PATH = b'JYTHONPATH'
248 IMPL_PATH = b'JYTHONPATH'
249
249
250 defaults = {
250 defaults = {
251 'jobs': ('HGTEST_JOBS', 1),
251 'jobs': ('HGTEST_JOBS', 1),
252 'timeout': ('HGTEST_TIMEOUT', 180),
252 'timeout': ('HGTEST_TIMEOUT', 180),
253 'slowtimeout': ('HGTEST_SLOWTIMEOUT', 500),
253 'slowtimeout': ('HGTEST_SLOWTIMEOUT', 500),
254 'port': ('HGTEST_PORT', 20059),
254 'port': ('HGTEST_PORT', 20059),
255 'shell': ('HGTEST_SHELL', 'sh'),
255 'shell': ('HGTEST_SHELL', 'sh'),
256 }
256 }
257
257
258 def canonpath(path):
258 def canonpath(path):
259 return os.path.realpath(os.path.expanduser(path))
259 return os.path.realpath(os.path.expanduser(path))
260
260
261 def parselistfiles(files, listtype, warn=True):
261 def parselistfiles(files, listtype, warn=True):
262 entries = dict()
262 entries = dict()
263 for filename in files:
263 for filename in files:
264 try:
264 try:
265 path = os.path.expanduser(os.path.expandvars(filename))
265 path = os.path.expanduser(os.path.expandvars(filename))
266 f = open(path, "rb")
266 f = open(path, "rb")
267 except IOError as err:
267 except IOError as err:
268 if err.errno != errno.ENOENT:
268 if err.errno != errno.ENOENT:
269 raise
269 raise
270 if warn:
270 if warn:
271 print("warning: no such %s file: %s" % (listtype, filename))
271 print("warning: no such %s file: %s" % (listtype, filename))
272 continue
272 continue
273
273
274 for line in f.readlines():
274 for line in f.readlines():
275 line = line.split(b'#', 1)[0].strip()
275 line = line.split(b'#', 1)[0].strip()
276 if line:
276 if line:
277 entries[line] = filename
277 entries[line] = filename
278
278
279 f.close()
279 f.close()
280 return entries
280 return entries
281
281
282 def parsettestcases(path):
282 def parsettestcases(path):
283 """read a .t test file, return a set of test case names
283 """read a .t test file, return a set of test case names
284
284
285 If path does not exist, return an empty set.
285 If path does not exist, return an empty set.
286 """
286 """
287 cases = set()
287 cases = set()
288 try:
288 try:
289 with open(path, 'rb') as f:
289 with open(path, 'rb') as f:
290 for l in f:
290 for l in f:
291 if l.startswith(b'#testcases '):
291 if l.startswith(b'#testcases '):
292 cases.update(l[11:].split())
292 cases.update(l[11:].split())
293 except IOError as ex:
293 except IOError as ex:
294 if ex.errno != errno.ENOENT:
294 if ex.errno != errno.ENOENT:
295 raise
295 raise
296 return cases
296 return cases
297
297
298 def getparser():
298 def getparser():
299 """Obtain the OptionParser used by the CLI."""
299 """Obtain the OptionParser used by the CLI."""
300 parser = argparse.ArgumentParser(usage='%(prog)s [options] [tests]')
300 parser = argparse.ArgumentParser(usage='%(prog)s [options] [tests]')
301
301
302 selection = parser.add_argument_group('Test Selection')
302 selection = parser.add_argument_group('Test Selection')
303 selection.add_argument('--allow-slow-tests', action='store_true',
303 selection.add_argument('--allow-slow-tests', action='store_true',
304 help='allow extremely slow tests')
304 help='allow extremely slow tests')
305 selection.add_argument("--blacklist", action="append",
305 selection.add_argument("--blacklist", action="append",
306 help="skip tests listed in the specified blacklist file")
306 help="skip tests listed in the specified blacklist file")
307 selection.add_argument("--changed",
307 selection.add_argument("--changed",
308 help="run tests that are changed in parent rev or working directory")
308 help="run tests that are changed in parent rev or working directory")
309 selection.add_argument("-k", "--keywords",
309 selection.add_argument("-k", "--keywords",
310 help="run tests matching keywords")
310 help="run tests matching keywords")
311 selection.add_argument("-r", "--retest", action="store_true",
311 selection.add_argument("-r", "--retest", action="store_true",
312 help = "retest failed tests")
312 help = "retest failed tests")
313 selection.add_argument("--test-list", action="append",
313 selection.add_argument("--test-list", action="append",
314 help="read tests to run from the specified file")
314 help="read tests to run from the specified file")
315 selection.add_argument("--whitelist", action="append",
315 selection.add_argument("--whitelist", action="append",
316 help="always run tests listed in the specified whitelist file")
316 help="always run tests listed in the specified whitelist file")
317 selection.add_argument('tests', metavar='TESTS', nargs='*',
317 selection.add_argument('tests', metavar='TESTS', nargs='*',
318 help='Tests to run')
318 help='Tests to run')
319
319
320 harness = parser.add_argument_group('Test Harness Behavior')
320 harness = parser.add_argument_group('Test Harness Behavior')
321 harness.add_argument('--bisect-repo',
321 harness.add_argument('--bisect-repo',
322 metavar='bisect_repo',
322 metavar='bisect_repo',
323 help=("Path of a repo to bisect. Use together with "
323 help=("Path of a repo to bisect. Use together with "
324 "--known-good-rev"))
324 "--known-good-rev"))
325 harness.add_argument("-d", "--debug", action="store_true",
325 harness.add_argument("-d", "--debug", action="store_true",
326 help="debug mode: write output of test scripts to console"
326 help="debug mode: write output of test scripts to console"
327 " rather than capturing and diffing it (disables timeout)")
327 " rather than capturing and diffing it (disables timeout)")
328 harness.add_argument("-f", "--first", action="store_true",
328 harness.add_argument("-f", "--first", action="store_true",
329 help="exit on the first test failure")
329 help="exit on the first test failure")
330 harness.add_argument("-i", "--interactive", action="store_true",
330 harness.add_argument("-i", "--interactive", action="store_true",
331 help="prompt to accept changed output")
331 help="prompt to accept changed output")
332 harness.add_argument("-j", "--jobs", type=int,
332 harness.add_argument("-j", "--jobs", type=int,
333 help="number of jobs to run in parallel"
333 help="number of jobs to run in parallel"
334 " (default: $%s or %d)" % defaults['jobs'])
334 " (default: $%s or %d)" % defaults['jobs'])
335 harness.add_argument("--keep-tmpdir", action="store_true",
335 harness.add_argument("--keep-tmpdir", action="store_true",
336 help="keep temporary directory after running tests")
336 help="keep temporary directory after running tests")
337 harness.add_argument('--known-good-rev',
337 harness.add_argument('--known-good-rev',
338 metavar="known_good_rev",
338 metavar="known_good_rev",
339 help=("Automatically bisect any failures using this "
339 help=("Automatically bisect any failures using this "
340 "revision as a known-good revision."))
340 "revision as a known-good revision."))
341 harness.add_argument("--list-tests", action="store_true",
341 harness.add_argument("--list-tests", action="store_true",
342 help="list tests instead of running them")
342 help="list tests instead of running them")
343 harness.add_argument("--loop", action="store_true",
343 harness.add_argument("--loop", action="store_true",
344 help="loop tests repeatedly")
344 help="loop tests repeatedly")
345 harness.add_argument('--random', action="store_true",
345 harness.add_argument('--random', action="store_true",
346 help='run tests in random order')
346 help='run tests in random order')
347 harness.add_argument("-p", "--port", type=int,
347 harness.add_argument("-p", "--port", type=int,
348 help="port on which servers should listen"
348 help="port on which servers should listen"
349 " (default: $%s or %d)" % defaults['port'])
349 " (default: $%s or %d)" % defaults['port'])
350 harness.add_argument('--profile-runner', action='store_true',
350 harness.add_argument('--profile-runner', action='store_true',
351 help='run statprof on run-tests')
351 help='run statprof on run-tests')
352 harness.add_argument("-R", "--restart", action="store_true",
352 harness.add_argument("-R", "--restart", action="store_true",
353 help="restart at last error")
353 help="restart at last error")
354 harness.add_argument("--runs-per-test", type=int, dest="runs_per_test",
354 harness.add_argument("--runs-per-test", type=int, dest="runs_per_test",
355 help="run each test N times (default=1)", default=1)
355 help="run each test N times (default=1)", default=1)
356 harness.add_argument("--shell",
356 harness.add_argument("--shell",
357 help="shell to use (default: $%s or %s)" % defaults['shell'])
357 help="shell to use (default: $%s or %s)" % defaults['shell'])
358 harness.add_argument('--showchannels', action='store_true',
358 harness.add_argument('--showchannels', action='store_true',
359 help='show scheduling channels')
359 help='show scheduling channels')
360 harness.add_argument("--slowtimeout", type=int,
360 harness.add_argument("--slowtimeout", type=int,
361 help="kill errant slow tests after SLOWTIMEOUT seconds"
361 help="kill errant slow tests after SLOWTIMEOUT seconds"
362 " (default: $%s or %d)" % defaults['slowtimeout'])
362 " (default: $%s or %d)" % defaults['slowtimeout'])
363 harness.add_argument("-t", "--timeout", type=int,
363 harness.add_argument("-t", "--timeout", type=int,
364 help="kill errant tests after TIMEOUT seconds"
364 help="kill errant tests after TIMEOUT seconds"
365 " (default: $%s or %d)" % defaults['timeout'])
365 " (default: $%s or %d)" % defaults['timeout'])
366 harness.add_argument("--tmpdir",
366 harness.add_argument("--tmpdir",
367 help="run tests in the given temporary directory"
367 help="run tests in the given temporary directory"
368 " (implies --keep-tmpdir)")
368 " (implies --keep-tmpdir)")
369 harness.add_argument("-v", "--verbose", action="store_true",
369 harness.add_argument("-v", "--verbose", action="store_true",
370 help="output verbose messages")
370 help="output verbose messages")
371
371
372 hgconf = parser.add_argument_group('Mercurial Configuration')
372 hgconf = parser.add_argument_group('Mercurial Configuration')
373 hgconf.add_argument("--chg", action="store_true",
373 hgconf.add_argument("--chg", action="store_true",
374 help="install and use chg wrapper in place of hg")
374 help="install and use chg wrapper in place of hg")
375 hgconf.add_argument("--compiler",
375 hgconf.add_argument("--compiler",
376 help="compiler to build with")
376 help="compiler to build with")
377 hgconf.add_argument('--extra-config-opt', action="append", default=[],
377 hgconf.add_argument('--extra-config-opt', action="append", default=[],
378 help='set the given config opt in the test hgrc')
378 help='set the given config opt in the test hgrc')
379 hgconf.add_argument("-l", "--local", action="store_true",
379 hgconf.add_argument("-l", "--local", action="store_true",
380 help="shortcut for --with-hg=<testdir>/../hg, "
380 help="shortcut for --with-hg=<testdir>/../hg, "
381 "and --with-chg=<testdir>/../contrib/chg/chg if --chg is set")
381 "and --with-chg=<testdir>/../contrib/chg/chg if --chg is set")
382 hgconf.add_argument("--ipv6", action="store_true",
382 hgconf.add_argument("--ipv6", action="store_true",
383 help="prefer IPv6 to IPv4 for network related tests")
383 help="prefer IPv6 to IPv4 for network related tests")
384 hgconf.add_argument("--pure", action="store_true",
384 hgconf.add_argument("--pure", action="store_true",
385 help="use pure Python code instead of C extensions")
385 help="use pure Python code instead of C extensions")
386 hgconf.add_argument("-3", "--py3k-warnings", action="store_true",
386 hgconf.add_argument("-3", "--py3k-warnings", action="store_true",
387 help="enable Py3k warnings on Python 2.7+")
387 help="enable Py3k warnings on Python 2.7+")
388 hgconf.add_argument("--with-chg", metavar="CHG",
388 hgconf.add_argument("--with-chg", metavar="CHG",
389 help="use specified chg wrapper in place of hg")
389 help="use specified chg wrapper in place of hg")
390 hgconf.add_argument("--with-hg",
390 hgconf.add_argument("--with-hg",
391 metavar="HG",
391 metavar="HG",
392 help="test using specified hg script rather than a "
392 help="test using specified hg script rather than a "
393 "temporary installation")
393 "temporary installation")
394 # This option should be deleted once test-check-py3-compat.t and other
394 # This option should be deleted once test-check-py3-compat.t and other
395 # Python 3 tests run with Python 3.
395 # Python 3 tests run with Python 3.
396 hgconf.add_argument("--with-python3", metavar="PYTHON3",
396 hgconf.add_argument("--with-python3", metavar="PYTHON3",
397 help="Python 3 interpreter (if running under Python 2)"
397 help="Python 3 interpreter (if running under Python 2)"
398 " (TEMPORARY)")
398 " (TEMPORARY)")
399
399
400 reporting = parser.add_argument_group('Results Reporting')
400 reporting = parser.add_argument_group('Results Reporting')
401 reporting.add_argument("-C", "--annotate", action="store_true",
401 reporting.add_argument("-C", "--annotate", action="store_true",
402 help="output files annotated with coverage")
402 help="output files annotated with coverage")
403 reporting.add_argument("--color", choices=["always", "auto", "never"],
403 reporting.add_argument("--color", choices=["always", "auto", "never"],
404 default=os.environ.get('HGRUNTESTSCOLOR', 'auto'),
404 default=os.environ.get('HGRUNTESTSCOLOR', 'auto'),
405 help="colorisation: always|auto|never (default: auto)")
405 help="colorisation: always|auto|never (default: auto)")
406 reporting.add_argument("-c", "--cover", action="store_true",
406 reporting.add_argument("-c", "--cover", action="store_true",
407 help="print a test coverage report")
407 help="print a test coverage report")
408 reporting.add_argument('--exceptions', action='store_true',
408 reporting.add_argument('--exceptions', action='store_true',
409 help='log all exceptions and generate an exception report')
409 help='log all exceptions and generate an exception report')
410 reporting.add_argument("-H", "--htmlcov", action="store_true",
410 reporting.add_argument("-H", "--htmlcov", action="store_true",
411 help="create an HTML report of the coverage of the files")
411 help="create an HTML report of the coverage of the files")
412 reporting.add_argument("--json", action="store_true",
412 reporting.add_argument("--json", action="store_true",
413 help="store test result data in 'report.json' file")
413 help="store test result data in 'report.json' file")
414 reporting.add_argument("--outputdir",
414 reporting.add_argument("--outputdir",
415 help="directory to write error logs to (default=test directory)")
415 help="directory to write error logs to (default=test directory)")
416 reporting.add_argument("-n", "--nodiff", action="store_true",
416 reporting.add_argument("-n", "--nodiff", action="store_true",
417 help="skip showing test changes")
417 help="skip showing test changes")
418 reporting.add_argument("-S", "--noskips", action="store_true",
418 reporting.add_argument("-S", "--noskips", action="store_true",
419 help="don't report skip tests verbosely")
419 help="don't report skip tests verbosely")
420 reporting.add_argument("--time", action="store_true",
420 reporting.add_argument("--time", action="store_true",
421 help="time how long each test takes")
421 help="time how long each test takes")
422 reporting.add_argument("--view",
422 reporting.add_argument("--view",
423 help="external diff viewer")
423 help="external diff viewer")
424 reporting.add_argument("--xunit",
424 reporting.add_argument("--xunit",
425 help="record xunit results at specified path")
425 help="record xunit results at specified path")
426
426
427 for option, (envvar, default) in defaults.items():
427 for option, (envvar, default) in defaults.items():
428 defaults[option] = type(default)(os.environ.get(envvar, default))
428 defaults[option] = type(default)(os.environ.get(envvar, default))
429 parser.set_defaults(**defaults)
429 parser.set_defaults(**defaults)
430
430
431 return parser
431 return parser
432
432
433 def parseargs(args, parser):
433 def parseargs(args, parser):
434 """Parse arguments with our OptionParser and validate results."""
434 """Parse arguments with our OptionParser and validate results."""
435 options = parser.parse_args(args)
435 options = parser.parse_args(args)
436
436
437 # jython is always pure
437 # jython is always pure
438 if 'java' in sys.platform or '__pypy__' in sys.modules:
438 if 'java' in sys.platform or '__pypy__' in sys.modules:
439 options.pure = True
439 options.pure = True
440
440
441 if options.with_hg:
441 if options.with_hg:
442 options.with_hg = canonpath(_bytespath(options.with_hg))
442 options.with_hg = canonpath(_bytespath(options.with_hg))
443 if not (os.path.isfile(options.with_hg) and
443 if not (os.path.isfile(options.with_hg) and
444 os.access(options.with_hg, os.X_OK)):
444 os.access(options.with_hg, os.X_OK)):
445 parser.error('--with-hg must specify an executable hg script')
445 parser.error('--with-hg must specify an executable hg script')
446 if os.path.basename(options.with_hg) not in [b'hg', b'hg.exe']:
446 if os.path.basename(options.with_hg) not in [b'hg', b'hg.exe']:
447 sys.stderr.write('warning: --with-hg should specify an hg script\n')
447 sys.stderr.write('warning: --with-hg should specify an hg script\n')
448 if options.local:
448 if options.local:
449 testdir = os.path.dirname(_bytespath(canonpath(sys.argv[0])))
449 testdir = os.path.dirname(_bytespath(canonpath(sys.argv[0])))
450 reporootdir = os.path.dirname(testdir)
450 reporootdir = os.path.dirname(testdir)
451 pathandattrs = [(b'hg', 'with_hg')]
451 pathandattrs = [(b'hg', 'with_hg')]
452 if options.chg:
452 if options.chg:
453 pathandattrs.append((b'contrib/chg/chg', 'with_chg'))
453 pathandattrs.append((b'contrib/chg/chg', 'with_chg'))
454 for relpath, attr in pathandattrs:
454 for relpath, attr in pathandattrs:
455 binpath = os.path.join(reporootdir, relpath)
455 binpath = os.path.join(reporootdir, relpath)
456 if os.name != 'nt' and not os.access(binpath, os.X_OK):
456 if os.name != 'nt' and not os.access(binpath, os.X_OK):
457 parser.error('--local specified, but %r not found or '
457 parser.error('--local specified, but %r not found or '
458 'not executable' % binpath)
458 'not executable' % binpath)
459 setattr(options, attr, binpath)
459 setattr(options, attr, binpath)
460
460
461 if (options.chg or options.with_chg) and os.name == 'nt':
461 if (options.chg or options.with_chg) and os.name == 'nt':
462 parser.error('chg does not work on %s' % os.name)
462 parser.error('chg does not work on %s' % os.name)
463 if options.with_chg:
463 if options.with_chg:
464 options.chg = False # no installation to temporary location
464 options.chg = False # no installation to temporary location
465 options.with_chg = canonpath(_bytespath(options.with_chg))
465 options.with_chg = canonpath(_bytespath(options.with_chg))
466 if not (os.path.isfile(options.with_chg) and
466 if not (os.path.isfile(options.with_chg) and
467 os.access(options.with_chg, os.X_OK)):
467 os.access(options.with_chg, os.X_OK)):
468 parser.error('--with-chg must specify a chg executable')
468 parser.error('--with-chg must specify a chg executable')
469 if options.chg and options.with_hg:
469 if options.chg and options.with_hg:
470 # chg shares installation location with hg
470 # chg shares installation location with hg
471 parser.error('--chg does not work when --with-hg is specified '
471 parser.error('--chg does not work when --with-hg is specified '
472 '(use --with-chg instead)')
472 '(use --with-chg instead)')
473
473
474 if options.color == 'always' and not pygmentspresent:
474 if options.color == 'always' and not pygmentspresent:
475 sys.stderr.write('warning: --color=always ignored because '
475 sys.stderr.write('warning: --color=always ignored because '
476 'pygments is not installed\n')
476 'pygments is not installed\n')
477
477
478 if options.bisect_repo and not options.known_good_rev:
478 if options.bisect_repo and not options.known_good_rev:
479 parser.error("--bisect-repo cannot be used without --known-good-rev")
479 parser.error("--bisect-repo cannot be used without --known-good-rev")
480
480
481 global useipv6
481 global useipv6
482 if options.ipv6:
482 if options.ipv6:
483 useipv6 = checksocketfamily('AF_INET6')
483 useipv6 = checksocketfamily('AF_INET6')
484 else:
484 else:
485 # only use IPv6 if IPv4 is unavailable and IPv6 is available
485 # only use IPv6 if IPv4 is unavailable and IPv6 is available
486 useipv6 = ((not checksocketfamily('AF_INET'))
486 useipv6 = ((not checksocketfamily('AF_INET'))
487 and checksocketfamily('AF_INET6'))
487 and checksocketfamily('AF_INET6'))
488
488
489 options.anycoverage = options.cover or options.annotate or options.htmlcov
489 options.anycoverage = options.cover or options.annotate or options.htmlcov
490 if options.anycoverage:
490 if options.anycoverage:
491 try:
491 try:
492 import coverage
492 import coverage
493 covver = version.StrictVersion(coverage.__version__).version
493 covver = version.StrictVersion(coverage.__version__).version
494 if covver < (3, 3):
494 if covver < (3, 3):
495 parser.error('coverage options require coverage 3.3 or later')
495 parser.error('coverage options require coverage 3.3 or later')
496 except ImportError:
496 except ImportError:
497 parser.error('coverage options now require the coverage package')
497 parser.error('coverage options now require the coverage package')
498
498
499 if options.anycoverage and options.local:
499 if options.anycoverage and options.local:
500 # this needs some path mangling somewhere, I guess
500 # this needs some path mangling somewhere, I guess
501 parser.error("sorry, coverage options do not work when --local "
501 parser.error("sorry, coverage options do not work when --local "
502 "is specified")
502 "is specified")
503
503
504 if options.anycoverage and options.with_hg:
504 if options.anycoverage and options.with_hg:
505 parser.error("sorry, coverage options do not work when --with-hg "
505 parser.error("sorry, coverage options do not work when --with-hg "
506 "is specified")
506 "is specified")
507
507
508 global verbose
508 global verbose
509 if options.verbose:
509 if options.verbose:
510 verbose = ''
510 verbose = ''
511
511
512 if options.tmpdir:
512 if options.tmpdir:
513 options.tmpdir = canonpath(options.tmpdir)
513 options.tmpdir = canonpath(options.tmpdir)
514
514
515 if options.jobs < 1:
515 if options.jobs < 1:
516 parser.error('--jobs must be positive')
516 parser.error('--jobs must be positive')
517 if options.interactive and options.debug:
517 if options.interactive and options.debug:
518 parser.error("-i/--interactive and -d/--debug are incompatible")
518 parser.error("-i/--interactive and -d/--debug are incompatible")
519 if options.debug:
519 if options.debug:
520 if options.timeout != defaults['timeout']:
520 if options.timeout != defaults['timeout']:
521 sys.stderr.write(
521 sys.stderr.write(
522 'warning: --timeout option ignored with --debug\n')
522 'warning: --timeout option ignored with --debug\n')
523 if options.slowtimeout != defaults['slowtimeout']:
523 if options.slowtimeout != defaults['slowtimeout']:
524 sys.stderr.write(
524 sys.stderr.write(
525 'warning: --slowtimeout option ignored with --debug\n')
525 'warning: --slowtimeout option ignored with --debug\n')
526 options.timeout = 0
526 options.timeout = 0
527 options.slowtimeout = 0
527 options.slowtimeout = 0
528 if options.py3k_warnings:
528 if options.py3k_warnings:
529 if PYTHON3:
529 if PYTHON3:
530 parser.error(
530 parser.error(
531 '--py3k-warnings can only be used on Python 2.7')
531 '--py3k-warnings can only be used on Python 2.7')
532 if options.with_python3:
532 if options.with_python3:
533 if PYTHON3:
533 if PYTHON3:
534 parser.error('--with-python3 cannot be used when executing with '
534 parser.error('--with-python3 cannot be used when executing with '
535 'Python 3')
535 'Python 3')
536
536
537 options.with_python3 = canonpath(options.with_python3)
537 options.with_python3 = canonpath(options.with_python3)
538 # Verify Python3 executable is acceptable.
538 # Verify Python3 executable is acceptable.
539 proc = subprocess.Popen([options.with_python3, b'--version'],
539 proc = subprocess.Popen([options.with_python3, b'--version'],
540 stdout=subprocess.PIPE,
540 stdout=subprocess.PIPE,
541 stderr=subprocess.STDOUT)
541 stderr=subprocess.STDOUT)
542 out, _err = proc.communicate()
542 out, _err = proc.communicate()
543 ret = proc.wait()
543 ret = proc.wait()
544 if ret != 0:
544 if ret != 0:
545 parser.error('could not determine version of python 3')
545 parser.error('could not determine version of python 3')
546 if not out.startswith('Python '):
546 if not out.startswith('Python '):
547 parser.error('unexpected output from python3 --version: %s' %
547 parser.error('unexpected output from python3 --version: %s' %
548 out)
548 out)
549 vers = version.LooseVersion(out[len('Python '):])
549 vers = version.LooseVersion(out[len('Python '):])
550 if vers < version.LooseVersion('3.5.0'):
550 if vers < version.LooseVersion('3.5.0'):
551 parser.error('--with-python3 version must be 3.5.0 or greater; '
551 parser.error('--with-python3 version must be 3.5.0 or greater; '
552 'got %s' % out)
552 'got %s' % out)
553
553
554 if options.blacklist:
554 if options.blacklist:
555 options.blacklist = parselistfiles(options.blacklist, 'blacklist')
555 options.blacklist = parselistfiles(options.blacklist, 'blacklist')
556 if options.whitelist:
556 if options.whitelist:
557 options.whitelisted = parselistfiles(options.whitelist, 'whitelist')
557 options.whitelisted = parselistfiles(options.whitelist, 'whitelist')
558 else:
558 else:
559 options.whitelisted = {}
559 options.whitelisted = {}
560
560
561 if options.showchannels:
561 if options.showchannels:
562 options.nodiff = True
562 options.nodiff = True
563
563
564 return options
564 return options
565
565
566 def rename(src, dst):
566 def rename(src, dst):
567 """Like os.rename(), trade atomicity and opened files friendliness
567 """Like os.rename(), trade atomicity and opened files friendliness
568 for existing destination support.
568 for existing destination support.
569 """
569 """
570 shutil.copy(src, dst)
570 shutil.copy(src, dst)
571 os.remove(src)
571 os.remove(src)
572
572
573 _unified_diff = difflib.unified_diff
573 _unified_diff = difflib.unified_diff
574 if PYTHON3:
574 if PYTHON3:
575 import functools
575 import functools
576 _unified_diff = functools.partial(difflib.diff_bytes, difflib.unified_diff)
576 _unified_diff = functools.partial(difflib.diff_bytes, difflib.unified_diff)
577
577
578 def getdiff(expected, output, ref, err):
578 def getdiff(expected, output, ref, err):
579 servefail = False
579 servefail = False
580 lines = []
580 lines = []
581 for line in _unified_diff(expected, output, ref, err):
581 for line in _unified_diff(expected, output, ref, err):
582 if line.startswith(b'+++') or line.startswith(b'---'):
582 if line.startswith(b'+++') or line.startswith(b'---'):
583 line = line.replace(b'\\', b'/')
583 line = line.replace(b'\\', b'/')
584 if line.endswith(b' \n'):
584 if line.endswith(b' \n'):
585 line = line[:-2] + b'\n'
585 line = line[:-2] + b'\n'
586 lines.append(line)
586 lines.append(line)
587 if not servefail and line.startswith(
587 if not servefail and line.startswith(
588 b'+ abort: child process failed to start'):
588 b'+ abort: child process failed to start'):
589 servefail = True
589 servefail = True
590
590
591 return servefail, lines
591 return servefail, lines
592
592
593 verbose = False
593 verbose = False
594 def vlog(*msg):
594 def vlog(*msg):
595 """Log only when in verbose mode."""
595 """Log only when in verbose mode."""
596 if verbose is False:
596 if verbose is False:
597 return
597 return
598
598
599 return log(*msg)
599 return log(*msg)
600
600
601 # Bytes that break XML even in a CDATA block: control characters 0-31
601 # Bytes that break XML even in a CDATA block: control characters 0-31
602 # sans \t, \n and \r
602 # sans \t, \n and \r
603 CDATA_EVIL = re.compile(br"[\000-\010\013\014\016-\037]")
603 CDATA_EVIL = re.compile(br"[\000-\010\013\014\016-\037]")
604
604
605 # Match feature conditionalized output lines in the form, capturing the feature
605 # Match feature conditionalized output lines in the form, capturing the feature
606 # list in group 2, and the preceeding line output in group 1:
606 # list in group 2, and the preceeding line output in group 1:
607 #
607 #
608 # output..output (feature !)\n
608 # output..output (feature !)\n
609 optline = re.compile(b'(.*) \((.+?) !\)\n$')
609 optline = re.compile(b'(.*) \((.+?) !\)\n$')
610
610
611 def cdatasafe(data):
611 def cdatasafe(data):
612 """Make a string safe to include in a CDATA block.
612 """Make a string safe to include in a CDATA block.
613
613
614 Certain control characters are illegal in a CDATA block, and
614 Certain control characters are illegal in a CDATA block, and
615 there's no way to include a ]]> in a CDATA either. This function
615 there's no way to include a ]]> in a CDATA either. This function
616 replaces illegal bytes with ? and adds a space between the ]] so
616 replaces illegal bytes with ? and adds a space between the ]] so
617 that it won't break the CDATA block.
617 that it won't break the CDATA block.
618 """
618 """
619 return CDATA_EVIL.sub(b'?', data).replace(b']]>', b'] ]>')
619 return CDATA_EVIL.sub(b'?', data).replace(b']]>', b'] ]>')
620
620
621 def log(*msg):
621 def log(*msg):
622 """Log something to stdout.
622 """Log something to stdout.
623
623
624 Arguments are strings to print.
624 Arguments are strings to print.
625 """
625 """
626 with iolock:
626 with iolock:
627 if verbose:
627 if verbose:
628 print(verbose, end=' ')
628 print(verbose, end=' ')
629 for m in msg:
629 for m in msg:
630 print(m, end=' ')
630 print(m, end=' ')
631 print()
631 print()
632 sys.stdout.flush()
632 sys.stdout.flush()
633
633
634 def highlightdiff(line, color):
634 def highlightdiff(line, color):
635 if not color:
635 if not color:
636 return line
636 return line
637 assert pygmentspresent
637 assert pygmentspresent
638 return pygments.highlight(line.decode('latin1'), difflexer,
638 return pygments.highlight(line.decode('latin1'), difflexer,
639 terminal256formatter).encode('latin1')
639 terminal256formatter).encode('latin1')
640
640
641 def highlightmsg(msg, color):
641 def highlightmsg(msg, color):
642 if not color:
642 if not color:
643 return msg
643 return msg
644 assert pygmentspresent
644 assert pygmentspresent
645 return pygments.highlight(msg, runnerlexer, runnerformatter)
645 return pygments.highlight(msg, runnerlexer, runnerformatter)
646
646
647 def terminate(proc):
647 def terminate(proc):
648 """Terminate subprocess"""
648 """Terminate subprocess"""
649 vlog('# Terminating process %d' % proc.pid)
649 vlog('# Terminating process %d' % proc.pid)
650 try:
650 try:
651 proc.terminate()
651 proc.terminate()
652 except OSError:
652 except OSError:
653 pass
653 pass
654
654
655 def killdaemons(pidfile):
655 def killdaemons(pidfile):
656 import killdaemons as killmod
656 import killdaemons as killmod
657 return killmod.killdaemons(pidfile, tryhard=False, remove=True,
657 return killmod.killdaemons(pidfile, tryhard=False, remove=True,
658 logfn=vlog)
658 logfn=vlog)
659
659
660 class Test(unittest.TestCase):
660 class Test(unittest.TestCase):
661 """Encapsulates a single, runnable test.
661 """Encapsulates a single, runnable test.
662
662
663 While this class conforms to the unittest.TestCase API, it differs in that
663 While this class conforms to the unittest.TestCase API, it differs in that
664 instances need to be instantiated manually. (Typically, unittest.TestCase
664 instances need to be instantiated manually. (Typically, unittest.TestCase
665 classes are instantiated automatically by scanning modules.)
665 classes are instantiated automatically by scanning modules.)
666 """
666 """
667
667
668 # Status code reserved for skipped tests (used by hghave).
668 # Status code reserved for skipped tests (used by hghave).
669 SKIPPED_STATUS = 80
669 SKIPPED_STATUS = 80
670
670
671 def __init__(self, path, outputdir, tmpdir, keeptmpdir=False,
671 def __init__(self, path, outputdir, tmpdir, keeptmpdir=False,
672 debug=False,
672 debug=False,
673 first=False,
673 first=False,
674 timeout=None,
674 timeout=None,
675 startport=None, extraconfigopts=None,
675 startport=None, extraconfigopts=None,
676 py3kwarnings=False, shell=None, hgcommand=None,
676 py3kwarnings=False, shell=None, hgcommand=None,
677 slowtimeout=None, usechg=False,
677 slowtimeout=None, usechg=False,
678 useipv6=False):
678 useipv6=False):
679 """Create a test from parameters.
679 """Create a test from parameters.
680
680
681 path is the full path to the file defining the test.
681 path is the full path to the file defining the test.
682
682
683 tmpdir is the main temporary directory to use for this test.
683 tmpdir is the main temporary directory to use for this test.
684
684
685 keeptmpdir determines whether to keep the test's temporary directory
685 keeptmpdir determines whether to keep the test's temporary directory
686 after execution. It defaults to removal (False).
686 after execution. It defaults to removal (False).
687
687
688 debug mode will make the test execute verbosely, with unfiltered
688 debug mode will make the test execute verbosely, with unfiltered
689 output.
689 output.
690
690
691 timeout controls the maximum run time of the test. It is ignored when
691 timeout controls the maximum run time of the test. It is ignored when
692 debug is True. See slowtimeout for tests with #require slow.
692 debug is True. See slowtimeout for tests with #require slow.
693
693
694 slowtimeout overrides timeout if the test has #require slow.
694 slowtimeout overrides timeout if the test has #require slow.
695
695
696 startport controls the starting port number to use for this test. Each
696 startport controls the starting port number to use for this test. Each
697 test will reserve 3 port numbers for execution. It is the caller's
697 test will reserve 3 port numbers for execution. It is the caller's
698 responsibility to allocate a non-overlapping port range to Test
698 responsibility to allocate a non-overlapping port range to Test
699 instances.
699 instances.
700
700
701 extraconfigopts is an iterable of extra hgrc config options. Values
701 extraconfigopts is an iterable of extra hgrc config options. Values
702 must have the form "key=value" (something understood by hgrc). Values
702 must have the form "key=value" (something understood by hgrc). Values
703 of the form "foo.key=value" will result in "[foo] key=value".
703 of the form "foo.key=value" will result in "[foo] key=value".
704
704
705 py3kwarnings enables Py3k warnings.
705 py3kwarnings enables Py3k warnings.
706
706
707 shell is the shell to execute tests in.
707 shell is the shell to execute tests in.
708 """
708 """
709 if timeout is None:
709 if timeout is None:
710 timeout = defaults['timeout']
710 timeout = defaults['timeout']
711 if startport is None:
711 if startport is None:
712 startport = defaults['port']
712 startport = defaults['port']
713 if slowtimeout is None:
713 if slowtimeout is None:
714 slowtimeout = defaults['slowtimeout']
714 slowtimeout = defaults['slowtimeout']
715 self.path = path
715 self.path = path
716 self.bname = os.path.basename(path)
716 self.bname = os.path.basename(path)
717 self.name = _strpath(self.bname)
717 self.name = _strpath(self.bname)
718 self._testdir = os.path.dirname(path)
718 self._testdir = os.path.dirname(path)
719 self._outputdir = outputdir
719 self._outputdir = outputdir
720 self._tmpname = os.path.basename(path)
720 self._tmpname = os.path.basename(path)
721 self.errpath = os.path.join(self._outputdir, b'%s.err' % self.bname)
721 self.errpath = os.path.join(self._outputdir, b'%s.err' % self.bname)
722
722
723 self._threadtmp = tmpdir
723 self._threadtmp = tmpdir
724 self._keeptmpdir = keeptmpdir
724 self._keeptmpdir = keeptmpdir
725 self._debug = debug
725 self._debug = debug
726 self._first = first
726 self._first = first
727 self._timeout = timeout
727 self._timeout = timeout
728 self._slowtimeout = slowtimeout
728 self._slowtimeout = slowtimeout
729 self._startport = startport
729 self._startport = startport
730 self._extraconfigopts = extraconfigopts or []
730 self._extraconfigopts = extraconfigopts or []
731 self._py3kwarnings = py3kwarnings
731 self._py3kwarnings = py3kwarnings
732 self._shell = _bytespath(shell)
732 self._shell = _bytespath(shell)
733 self._hgcommand = hgcommand or b'hg'
733 self._hgcommand = hgcommand or b'hg'
734 self._usechg = usechg
734 self._usechg = usechg
735 self._useipv6 = useipv6
735 self._useipv6 = useipv6
736
736
737 self._aborted = False
737 self._aborted = False
738 self._daemonpids = []
738 self._daemonpids = []
739 self._finished = None
739 self._finished = None
740 self._ret = None
740 self._ret = None
741 self._out = None
741 self._out = None
742 self._skipped = None
742 self._skipped = None
743 self._testtmp = None
743 self._testtmp = None
744 self._chgsockdir = None
744 self._chgsockdir = None
745
745
746 self._refout = self.readrefout()
746 self._refout = self.readrefout()
747
747
748 def readrefout(self):
748 def readrefout(self):
749 """read reference output"""
749 """read reference output"""
750 # If we're not in --debug mode and reference output file exists,
750 # If we're not in --debug mode and reference output file exists,
751 # check test output against it.
751 # check test output against it.
752 if self._debug:
752 if self._debug:
753 return None # to match "out is None"
753 return None # to match "out is None"
754 elif os.path.exists(self.refpath):
754 elif os.path.exists(self.refpath):
755 with open(self.refpath, 'rb') as f:
755 with open(self.refpath, 'rb') as f:
756 return f.read().splitlines(True)
756 return f.read().splitlines(True)
757 else:
757 else:
758 return []
758 return []
759
759
760 # needed to get base class __repr__ running
760 # needed to get base class __repr__ running
761 @property
761 @property
762 def _testMethodName(self):
762 def _testMethodName(self):
763 return self.name
763 return self.name
764
764
765 def __str__(self):
765 def __str__(self):
766 return self.name
766 return self.name
767
767
768 def shortDescription(self):
768 def shortDescription(self):
769 return self.name
769 return self.name
770
770
771 def setUp(self):
771 def setUp(self):
772 """Tasks to perform before run()."""
772 """Tasks to perform before run()."""
773 self._finished = False
773 self._finished = False
774 self._ret = None
774 self._ret = None
775 self._out = None
775 self._out = None
776 self._skipped = None
776 self._skipped = None
777
777
778 try:
778 try:
779 os.mkdir(self._threadtmp)
779 os.mkdir(self._threadtmp)
780 except OSError as e:
780 except OSError as e:
781 if e.errno != errno.EEXIST:
781 if e.errno != errno.EEXIST:
782 raise
782 raise
783
783
784 name = self._tmpname
784 name = self._tmpname
785 self._testtmp = os.path.join(self._threadtmp, name)
785 self._testtmp = os.path.join(self._threadtmp, name)
786 os.mkdir(self._testtmp)
786 os.mkdir(self._testtmp)
787
787
788 # Remove any previous output files.
788 # Remove any previous output files.
789 if os.path.exists(self.errpath):
789 if os.path.exists(self.errpath):
790 try:
790 try:
791 os.remove(self.errpath)
791 os.remove(self.errpath)
792 except OSError as e:
792 except OSError as e:
793 # We might have raced another test to clean up a .err
793 # We might have raced another test to clean up a .err
794 # file, so ignore ENOENT when removing a previous .err
794 # file, so ignore ENOENT when removing a previous .err
795 # file.
795 # file.
796 if e.errno != errno.ENOENT:
796 if e.errno != errno.ENOENT:
797 raise
797 raise
798
798
799 if self._usechg:
799 if self._usechg:
800 self._chgsockdir = os.path.join(self._threadtmp,
800 self._chgsockdir = os.path.join(self._threadtmp,
801 b'%s.chgsock' % name)
801 b'%s.chgsock' % name)
802 os.mkdir(self._chgsockdir)
802 os.mkdir(self._chgsockdir)
803
803
804 def run(self, result):
804 def run(self, result):
805 """Run this test and report results against a TestResult instance."""
805 """Run this test and report results against a TestResult instance."""
806 # This function is extremely similar to unittest.TestCase.run(). Once
806 # This function is extremely similar to unittest.TestCase.run(). Once
807 # we require Python 2.7 (or at least its version of unittest), this
807 # we require Python 2.7 (or at least its version of unittest), this
808 # function can largely go away.
808 # function can largely go away.
809 self._result = result
809 self._result = result
810 result.startTest(self)
810 result.startTest(self)
811 try:
811 try:
812 try:
812 try:
813 self.setUp()
813 self.setUp()
814 except (KeyboardInterrupt, SystemExit):
814 except (KeyboardInterrupt, SystemExit):
815 self._aborted = True
815 self._aborted = True
816 raise
816 raise
817 except Exception:
817 except Exception:
818 result.addError(self, sys.exc_info())
818 result.addError(self, sys.exc_info())
819 return
819 return
820
820
821 success = False
821 success = False
822 try:
822 try:
823 self.runTest()
823 self.runTest()
824 except KeyboardInterrupt:
824 except KeyboardInterrupt:
825 self._aborted = True
825 self._aborted = True
826 raise
826 raise
827 except unittest.SkipTest as e:
827 except unittest.SkipTest as e:
828 result.addSkip(self, str(e))
828 result.addSkip(self, str(e))
829 # The base class will have already counted this as a
829 # The base class will have already counted this as a
830 # test we "ran", but we want to exclude skipped tests
830 # test we "ran", but we want to exclude skipped tests
831 # from those we count towards those run.
831 # from those we count towards those run.
832 result.testsRun -= 1
832 result.testsRun -= 1
833 except self.failureException as e:
833 except self.failureException as e:
834 # This differs from unittest in that we don't capture
834 # This differs from unittest in that we don't capture
835 # the stack trace. This is for historical reasons and
835 # the stack trace. This is for historical reasons and
836 # this decision could be revisited in the future,
836 # this decision could be revisited in the future,
837 # especially for PythonTest instances.
837 # especially for PythonTest instances.
838 if result.addFailure(self, str(e)):
838 if result.addFailure(self, str(e)):
839 success = True
839 success = True
840 except Exception:
840 except Exception:
841 result.addError(self, sys.exc_info())
841 result.addError(self, sys.exc_info())
842 else:
842 else:
843 success = True
843 success = True
844
844
845 try:
845 try:
846 self.tearDown()
846 self.tearDown()
847 except (KeyboardInterrupt, SystemExit):
847 except (KeyboardInterrupt, SystemExit):
848 self._aborted = True
848 self._aborted = True
849 raise
849 raise
850 except Exception:
850 except Exception:
851 result.addError(self, sys.exc_info())
851 result.addError(self, sys.exc_info())
852 success = False
852 success = False
853
853
854 if success:
854 if success:
855 result.addSuccess(self)
855 result.addSuccess(self)
856 finally:
856 finally:
857 result.stopTest(self, interrupted=self._aborted)
857 result.stopTest(self, interrupted=self._aborted)
858
858
859 def runTest(self):
859 def runTest(self):
860 """Run this test instance.
860 """Run this test instance.
861
861
862 This will return a tuple describing the result of the test.
862 This will return a tuple describing the result of the test.
863 """
863 """
864 env = self._getenv()
864 env = self._getenv()
865 self._genrestoreenv(env)
865 self._genrestoreenv(env)
866 self._daemonpids.append(env['DAEMON_PIDS'])
866 self._daemonpids.append(env['DAEMON_PIDS'])
867 self._createhgrc(env['HGRCPATH'])
867 self._createhgrc(env['HGRCPATH'])
868
868
869 vlog('# Test', self.name)
869 vlog('# Test', self.name)
870
870
871 ret, out = self._run(env)
871 ret, out = self._run(env)
872 self._finished = True
872 self._finished = True
873 self._ret = ret
873 self._ret = ret
874 self._out = out
874 self._out = out
875
875
876 def describe(ret):
876 def describe(ret):
877 if ret < 0:
877 if ret < 0:
878 return 'killed by signal: %d' % -ret
878 return 'killed by signal: %d' % -ret
879 return 'returned error code %d' % ret
879 return 'returned error code %d' % ret
880
880
881 self._skipped = False
881 self._skipped = False
882
882
883 if ret == self.SKIPPED_STATUS:
883 if ret == self.SKIPPED_STATUS:
884 if out is None: # Debug mode, nothing to parse.
884 if out is None: # Debug mode, nothing to parse.
885 missing = ['unknown']
885 missing = ['unknown']
886 failed = None
886 failed = None
887 else:
887 else:
888 missing, failed = TTest.parsehghaveoutput(out)
888 missing, failed = TTest.parsehghaveoutput(out)
889
889
890 if not missing:
890 if not missing:
891 missing = ['skipped']
891 missing = ['skipped']
892
892
893 if failed:
893 if failed:
894 self.fail('hg have failed checking for %s' % failed[-1])
894 self.fail('hg have failed checking for %s' % failed[-1])
895 else:
895 else:
896 self._skipped = True
896 self._skipped = True
897 raise unittest.SkipTest(missing[-1])
897 raise unittest.SkipTest(missing[-1])
898 elif ret == 'timeout':
898 elif ret == 'timeout':
899 self.fail('timed out')
899 self.fail('timed out')
900 elif ret is False:
900 elif ret is False:
901 self.fail('no result code from test')
901 self.fail('no result code from test')
902 elif out != self._refout:
902 elif out != self._refout:
903 # Diff generation may rely on written .err file.
903 # Diff generation may rely on written .err file.
904 if (ret != 0 or out != self._refout) and not self._skipped \
904 if (ret != 0 or out != self._refout) and not self._skipped \
905 and not self._debug:
905 and not self._debug:
906 with open(self.errpath, 'wb') as f:
906 with open(self.errpath, 'wb') as f:
907 for line in out:
907 for line in out:
908 f.write(line)
908 f.write(line)
909
909
910 # The result object handles diff calculation for us.
910 # The result object handles diff calculation for us.
911 with firstlock:
911 with firstlock:
912 if self._result.addOutputMismatch(self, ret, out, self._refout):
912 if self._result.addOutputMismatch(self, ret, out, self._refout):
913 # change was accepted, skip failing
913 # change was accepted, skip failing
914 return
914 return
915 if self._first:
915 if self._first:
916 global firsterror
916 global firsterror
917 firsterror = True
917 firsterror = True
918
918
919 if ret:
919 if ret:
920 msg = 'output changed and ' + describe(ret)
920 msg = 'output changed and ' + describe(ret)
921 else:
921 else:
922 msg = 'output changed'
922 msg = 'output changed'
923
923
924 self.fail(msg)
924 self.fail(msg)
925 elif ret:
925 elif ret:
926 self.fail(describe(ret))
926 self.fail(describe(ret))
927
927
928 def tearDown(self):
928 def tearDown(self):
929 """Tasks to perform after run()."""
929 """Tasks to perform after run()."""
930 for entry in self._daemonpids:
930 for entry in self._daemonpids:
931 killdaemons(entry)
931 killdaemons(entry)
932 self._daemonpids = []
932 self._daemonpids = []
933
933
934 if self._keeptmpdir:
934 if self._keeptmpdir:
935 log('\nKeeping testtmp dir: %s\nKeeping threadtmp dir: %s' %
935 log('\nKeeping testtmp dir: %s\nKeeping threadtmp dir: %s' %
936 (self._testtmp.decode('utf-8'),
936 (self._testtmp.decode('utf-8'),
937 self._threadtmp.decode('utf-8')))
937 self._threadtmp.decode('utf-8')))
938 else:
938 else:
939 shutil.rmtree(self._testtmp, True)
939 shutil.rmtree(self._testtmp, True)
940 shutil.rmtree(self._threadtmp, True)
940 shutil.rmtree(self._threadtmp, True)
941
941
942 if self._usechg:
942 if self._usechg:
943 # chgservers will stop automatically after they find the socket
943 # chgservers will stop automatically after they find the socket
944 # files are deleted
944 # files are deleted
945 shutil.rmtree(self._chgsockdir, True)
945 shutil.rmtree(self._chgsockdir, True)
946
946
947 if (self._ret != 0 or self._out != self._refout) and not self._skipped \
947 if (self._ret != 0 or self._out != self._refout) and not self._skipped \
948 and not self._debug and self._out:
948 and not self._debug and self._out:
949 with open(self.errpath, 'wb') as f:
949 with open(self.errpath, 'wb') as f:
950 for line in self._out:
950 for line in self._out:
951 f.write(line)
951 f.write(line)
952
952
953 vlog("# Ret was:", self._ret, '(%s)' % self.name)
953 vlog("# Ret was:", self._ret, '(%s)' % self.name)
954
954
955 def _run(self, env):
955 def _run(self, env):
956 # This should be implemented in child classes to run tests.
956 # This should be implemented in child classes to run tests.
957 raise unittest.SkipTest('unknown test type')
957 raise unittest.SkipTest('unknown test type')
958
958
959 def abort(self):
959 def abort(self):
960 """Terminate execution of this test."""
960 """Terminate execution of this test."""
961 self._aborted = True
961 self._aborted = True
962
962
963 def _portmap(self, i):
963 def _portmap(self, i):
964 offset = b'' if i == 0 else b'%d' % i
964 offset = b'' if i == 0 else b'%d' % i
965 return (br':%d\b' % (self._startport + i), b':$HGPORT%s' % offset)
965 return (br':%d\b' % (self._startport + i), b':$HGPORT%s' % offset)
966
966
967 def _getreplacements(self):
967 def _getreplacements(self):
968 """Obtain a mapping of text replacements to apply to test output.
968 """Obtain a mapping of text replacements to apply to test output.
969
969
970 Test output needs to be normalized so it can be compared to expected
970 Test output needs to be normalized so it can be compared to expected
971 output. This function defines how some of that normalization will
971 output. This function defines how some of that normalization will
972 occur.
972 occur.
973 """
973 """
974 r = [
974 r = [
975 # This list should be parallel to defineport in _getenv
975 # This list should be parallel to defineport in _getenv
976 self._portmap(0),
976 self._portmap(0),
977 self._portmap(1),
977 self._portmap(1),
978 self._portmap(2),
978 self._portmap(2),
979 (br'([^0-9])%s' % re.escape(self._localip()), br'\1$LOCALIP'),
979 (br'([^0-9])%s' % re.escape(self._localip()), br'\1$LOCALIP'),
980 (br'\bHG_TXNID=TXN:[a-f0-9]{40}\b', br'HG_TXNID=TXN:$ID$'),
980 (br'\bHG_TXNID=TXN:[a-f0-9]{40}\b', br'HG_TXNID=TXN:$ID$'),
981 ]
981 ]
982 r.append((self._escapepath(self._testtmp), b'$TESTTMP'))
982 r.append((self._escapepath(self._testtmp), b'$TESTTMP'))
983
983
984 replacementfile = os.path.join(self._testdir, b'common-pattern.py')
984 replacementfile = os.path.join(self._testdir, b'common-pattern.py')
985
985
986 if os.path.exists(replacementfile):
986 if os.path.exists(replacementfile):
987 data = {}
987 data = {}
988 with open(replacementfile, mode='rb') as source:
988 with open(replacementfile, mode='rb') as source:
989 # the intermediate 'compile' step help with debugging
989 # the intermediate 'compile' step help with debugging
990 code = compile(source.read(), replacementfile, 'exec')
990 code = compile(source.read(), replacementfile, 'exec')
991 exec(code, data)
991 exec(code, data)
992 r.extend(data.get('substitutions', ()))
992 r.extend(data.get('substitutions', ()))
993 return r
993 return r
994
994
995 def _escapepath(self, p):
995 def _escapepath(self, p):
996 if os.name == 'nt':
996 if os.name == 'nt':
997 return (
997 return (
998 (b''.join(c.isalpha() and b'[%s%s]' % (c.lower(), c.upper()) or
998 (b''.join(c.isalpha() and b'[%s%s]' % (c.lower(), c.upper()) or
999 c in b'/\\' and br'[/\\]' or c.isdigit() and c or b'\\' + c
999 c in b'/\\' and br'[/\\]' or c.isdigit() and c or b'\\' + c
1000 for c in p))
1000 for c in p))
1001 )
1001 )
1002 else:
1002 else:
1003 return re.escape(p)
1003 return re.escape(p)
1004
1004
1005 def _localip(self):
1005 def _localip(self):
1006 if self._useipv6:
1006 if self._useipv6:
1007 return b'::1'
1007 return b'::1'
1008 else:
1008 else:
1009 return b'127.0.0.1'
1009 return b'127.0.0.1'
1010
1010
1011 def _genrestoreenv(self, testenv):
1011 def _genrestoreenv(self, testenv):
1012 """Generate a script that can be used by tests to restore the original
1012 """Generate a script that can be used by tests to restore the original
1013 environment."""
1013 environment."""
1014 # Put the restoreenv script inside self._threadtmp
1014 # Put the restoreenv script inside self._threadtmp
1015 scriptpath = os.path.join(self._threadtmp, b'restoreenv.sh')
1015 scriptpath = os.path.join(self._threadtmp, b'restoreenv.sh')
1016 testenv['HGTEST_RESTOREENV'] = scriptpath
1016 testenv['HGTEST_RESTOREENV'] = scriptpath
1017
1017
1018 # Only restore environment variable names that the shell allows
1018 # Only restore environment variable names that the shell allows
1019 # us to export.
1019 # us to export.
1020 name_regex = re.compile('^[a-zA-Z][a-zA-Z0-9_]*$')
1020 name_regex = re.compile('^[a-zA-Z][a-zA-Z0-9_]*$')
1021
1021
1022 # Do not restore these variables; otherwise tests would fail.
1022 # Do not restore these variables; otherwise tests would fail.
1023 reqnames = {'PYTHON', 'TESTDIR', 'TESTTMP'}
1023 reqnames = {'PYTHON', 'TESTDIR', 'TESTTMP'}
1024
1024
1025 with open(scriptpath, 'w') as envf:
1025 with open(scriptpath, 'w') as envf:
1026 for name, value in origenviron.items():
1026 for name, value in origenviron.items():
1027 if not name_regex.match(name):
1027 if not name_regex.match(name):
1028 # Skip environment variables with unusual names not
1028 # Skip environment variables with unusual names not
1029 # allowed by most shells.
1029 # allowed by most shells.
1030 continue
1030 continue
1031 if name in reqnames:
1031 if name in reqnames:
1032 continue
1032 continue
1033 envf.write('%s=%s\n' % (name, shellquote(value)))
1033 envf.write('%s=%s\n' % (name, shellquote(value)))
1034
1034
1035 for name in testenv:
1035 for name in testenv:
1036 if name in origenviron or name in reqnames:
1036 if name in origenviron or name in reqnames:
1037 continue
1037 continue
1038 envf.write('unset %s\n' % (name,))
1038 envf.write('unset %s\n' % (name,))
1039
1039
1040 def _getenv(self):
1040 def _getenv(self):
1041 """Obtain environment variables to use during test execution."""
1041 """Obtain environment variables to use during test execution."""
1042 def defineport(i):
1042 def defineport(i):
1043 offset = '' if i == 0 else '%s' % i
1043 offset = '' if i == 0 else '%s' % i
1044 env["HGPORT%s" % offset] = '%s' % (self._startport + i)
1044 env["HGPORT%s" % offset] = '%s' % (self._startport + i)
1045 env = os.environ.copy()
1045 env = os.environ.copy()
1046 env['PYTHONUSERBASE'] = sysconfig.get_config_var('userbase') or ''
1046 env['PYTHONUSERBASE'] = sysconfig.get_config_var('userbase') or ''
1047 env['HGEMITWARNINGS'] = '1'
1047 env['HGEMITWARNINGS'] = '1'
1048 env['TESTTMP'] = self._testtmp
1048 env['TESTTMP'] = self._testtmp
1049 env['HOME'] = self._testtmp
1049 env['HOME'] = self._testtmp
1050 # This number should match portneeded in _getport
1050 # This number should match portneeded in _getport
1051 for port in xrange(3):
1051 for port in xrange(3):
1052 # This list should be parallel to _portmap in _getreplacements
1052 # This list should be parallel to _portmap in _getreplacements
1053 defineport(port)
1053 defineport(port)
1054 env["HGRCPATH"] = os.path.join(self._threadtmp, b'.hgrc')
1054 env["HGRCPATH"] = os.path.join(self._threadtmp, b'.hgrc')
1055 env["DAEMON_PIDS"] = os.path.join(self._threadtmp, b'daemon.pids')
1055 env["DAEMON_PIDS"] = os.path.join(self._threadtmp, b'daemon.pids')
1056 env["HGEDITOR"] = ('"' + sys.executable + '"'
1056 env["HGEDITOR"] = ('"' + sys.executable + '"'
1057 + ' -c "import sys; sys.exit(0)"')
1057 + ' -c "import sys; sys.exit(0)"')
1058 env["HGMERGE"] = "internal:merge"
1058 env["HGMERGE"] = "internal:merge"
1059 env["HGUSER"] = "test"
1059 env["HGUSER"] = "test"
1060 env["HGENCODING"] = "ascii"
1060 env["HGENCODING"] = "ascii"
1061 env["HGENCODINGMODE"] = "strict"
1061 env["HGENCODINGMODE"] = "strict"
1062 env['HGIPV6'] = str(int(self._useipv6))
1062 env['HGIPV6'] = str(int(self._useipv6))
1063
1063
1064 # LOCALIP could be ::1 or 127.0.0.1. Useful for tests that require raw
1064 # LOCALIP could be ::1 or 127.0.0.1. Useful for tests that require raw
1065 # IP addresses.
1065 # IP addresses.
1066 env['LOCALIP'] = self._localip()
1066 env['LOCALIP'] = self._localip()
1067
1067
1068 # Reset some environment variables to well-known values so that
1068 # Reset some environment variables to well-known values so that
1069 # the tests produce repeatable output.
1069 # the tests produce repeatable output.
1070 env['LANG'] = env['LC_ALL'] = env['LANGUAGE'] = 'C'
1070 env['LANG'] = env['LC_ALL'] = env['LANGUAGE'] = 'C'
1071 env['TZ'] = 'GMT'
1071 env['TZ'] = 'GMT'
1072 env["EMAIL"] = "Foo Bar <foo.bar@example.com>"
1072 env["EMAIL"] = "Foo Bar <foo.bar@example.com>"
1073 env['COLUMNS'] = '80'
1073 env['COLUMNS'] = '80'
1074 env['TERM'] = 'xterm'
1074 env['TERM'] = 'xterm'
1075
1075
1076 for k in ('HG HGPROF CDPATH GREP_OPTIONS http_proxy no_proxy ' +
1076 for k in ('HG HGPROF CDPATH GREP_OPTIONS http_proxy no_proxy ' +
1077 'HGPLAIN HGPLAINEXCEPT EDITOR VISUAL PAGER ' +
1077 'HGPLAIN HGPLAINEXCEPT EDITOR VISUAL PAGER ' +
1078 'NO_PROXY CHGDEBUG').split():
1078 'NO_PROXY CHGDEBUG').split():
1079 if k in env:
1079 if k in env:
1080 del env[k]
1080 del env[k]
1081
1081
1082 # unset env related to hooks
1082 # unset env related to hooks
1083 for k in env.keys():
1083 for k in env.keys():
1084 if k.startswith('HG_'):
1084 if k.startswith('HG_'):
1085 del env[k]
1085 del env[k]
1086
1086
1087 if self._usechg:
1087 if self._usechg:
1088 env['CHGSOCKNAME'] = os.path.join(self._chgsockdir, b'server')
1088 env['CHGSOCKNAME'] = os.path.join(self._chgsockdir, b'server')
1089
1089
1090 return env
1090 return env
1091
1091
1092 def _createhgrc(self, path):
1092 def _createhgrc(self, path):
1093 """Create an hgrc file for this test."""
1093 """Create an hgrc file for this test."""
1094 with open(path, 'wb') as hgrc:
1094 with open(path, 'wb') as hgrc:
1095 hgrc.write(b'[ui]\n')
1095 hgrc.write(b'[ui]\n')
1096 hgrc.write(b'slash = True\n')
1096 hgrc.write(b'slash = True\n')
1097 hgrc.write(b'interactive = False\n')
1097 hgrc.write(b'interactive = False\n')
1098 hgrc.write(b'mergemarkers = detailed\n')
1098 hgrc.write(b'mergemarkers = detailed\n')
1099 hgrc.write(b'promptecho = True\n')
1099 hgrc.write(b'promptecho = True\n')
1100 hgrc.write(b'[defaults]\n')
1100 hgrc.write(b'[defaults]\n')
1101 hgrc.write(b'[devel]\n')
1101 hgrc.write(b'[devel]\n')
1102 hgrc.write(b'all-warnings = true\n')
1102 hgrc.write(b'all-warnings = true\n')
1103 hgrc.write(b'default-date = 0 0\n')
1103 hgrc.write(b'default-date = 0 0\n')
1104 hgrc.write(b'[largefiles]\n')
1104 hgrc.write(b'[largefiles]\n')
1105 hgrc.write(b'usercache = %s\n' %
1105 hgrc.write(b'usercache = %s\n' %
1106 (os.path.join(self._testtmp, b'.cache/largefiles')))
1106 (os.path.join(self._testtmp, b'.cache/largefiles')))
1107 hgrc.write(b'[lfs]\n')
1107 hgrc.write(b'[lfs]\n')
1108 hgrc.write(b'usercache = %s\n' %
1108 hgrc.write(b'usercache = %s\n' %
1109 (os.path.join(self._testtmp, b'.cache/lfs')))
1109 (os.path.join(self._testtmp, b'.cache/lfs')))
1110 hgrc.write(b'[web]\n')
1110 hgrc.write(b'[web]\n')
1111 hgrc.write(b'address = localhost\n')
1111 hgrc.write(b'address = localhost\n')
1112 hgrc.write(b'ipv6 = %s\n' % str(self._useipv6).encode('ascii'))
1112 hgrc.write(b'ipv6 = %s\n' % str(self._useipv6).encode('ascii'))
1113
1113
1114 for opt in self._extraconfigopts:
1114 for opt in self._extraconfigopts:
1115 section, key = opt.encode('utf-8').split(b'.', 1)
1115 section, key = opt.encode('utf-8').split(b'.', 1)
1116 assert b'=' in key, ('extra config opt %s must '
1116 assert b'=' in key, ('extra config opt %s must '
1117 'have an = for assignment' % opt)
1117 'have an = for assignment' % opt)
1118 hgrc.write(b'[%s]\n%s\n' % (section, key))
1118 hgrc.write(b'[%s]\n%s\n' % (section, key))
1119
1119
1120 def fail(self, msg):
1120 def fail(self, msg):
1121 # unittest differentiates between errored and failed.
1121 # unittest differentiates between errored and failed.
1122 # Failed is denoted by AssertionError (by default at least).
1122 # Failed is denoted by AssertionError (by default at least).
1123 raise AssertionError(msg)
1123 raise AssertionError(msg)
1124
1124
1125 def _runcommand(self, cmd, env, normalizenewlines=False):
1125 def _runcommand(self, cmd, env, normalizenewlines=False):
1126 """Run command in a sub-process, capturing the output (stdout and
1126 """Run command in a sub-process, capturing the output (stdout and
1127 stderr).
1127 stderr).
1128
1128
1129 Return a tuple (exitcode, output). output is None in debug mode.
1129 Return a tuple (exitcode, output). output is None in debug mode.
1130 """
1130 """
1131 if self._debug:
1131 if self._debug:
1132 proc = subprocess.Popen(cmd, shell=True, cwd=self._testtmp,
1132 proc = subprocess.Popen(cmd, shell=True, cwd=self._testtmp,
1133 env=env)
1133 env=env)
1134 ret = proc.wait()
1134 ret = proc.wait()
1135 return (ret, None)
1135 return (ret, None)
1136
1136
1137 proc = Popen4(cmd, self._testtmp, self._timeout, env)
1137 proc = Popen4(cmd, self._testtmp, self._timeout, env)
1138 def cleanup():
1138 def cleanup():
1139 terminate(proc)
1139 terminate(proc)
1140 ret = proc.wait()
1140 ret = proc.wait()
1141 if ret == 0:
1141 if ret == 0:
1142 ret = signal.SIGTERM << 8
1142 ret = signal.SIGTERM << 8
1143 killdaemons(env['DAEMON_PIDS'])
1143 killdaemons(env['DAEMON_PIDS'])
1144 return ret
1144 return ret
1145
1145
1146 output = ''
1146 output = ''
1147 proc.tochild.close()
1147 proc.tochild.close()
1148
1148
1149 try:
1149 try:
1150 output = proc.fromchild.read()
1150 output = proc.fromchild.read()
1151 except KeyboardInterrupt:
1151 except KeyboardInterrupt:
1152 vlog('# Handling keyboard interrupt')
1152 vlog('# Handling keyboard interrupt')
1153 cleanup()
1153 cleanup()
1154 raise
1154 raise
1155
1155
1156 ret = proc.wait()
1156 ret = proc.wait()
1157 if wifexited(ret):
1157 if wifexited(ret):
1158 ret = os.WEXITSTATUS(ret)
1158 ret = os.WEXITSTATUS(ret)
1159
1159
1160 if proc.timeout:
1160 if proc.timeout:
1161 ret = 'timeout'
1161 ret = 'timeout'
1162
1162
1163 if ret:
1163 if ret:
1164 killdaemons(env['DAEMON_PIDS'])
1164 killdaemons(env['DAEMON_PIDS'])
1165
1165
1166 for s, r in self._getreplacements():
1166 for s, r in self._getreplacements():
1167 output = re.sub(s, r, output)
1167 output = re.sub(s, r, output)
1168
1168
1169 if normalizenewlines:
1169 if normalizenewlines:
1170 output = output.replace('\r\n', '\n')
1170 output = output.replace('\r\n', '\n')
1171
1171
1172 return ret, output.splitlines(True)
1172 return ret, output.splitlines(True)
1173
1173
1174 class PythonTest(Test):
1174 class PythonTest(Test):
1175 """A Python-based test."""
1175 """A Python-based test."""
1176
1176
1177 @property
1177 @property
1178 def refpath(self):
1178 def refpath(self):
1179 return os.path.join(self._testdir, b'%s.out' % self.bname)
1179 return os.path.join(self._testdir, b'%s.out' % self.bname)
1180
1180
1181 def _run(self, env):
1181 def _run(self, env):
1182 py3kswitch = self._py3kwarnings and b' -3' or b''
1182 py3kswitch = self._py3kwarnings and b' -3' or b''
1183 cmd = b'%s%s "%s"' % (PYTHON, py3kswitch, self.path)
1183 cmd = b'%s%s "%s"' % (PYTHON, py3kswitch, self.path)
1184 vlog("# Running", cmd)
1184 vlog("# Running", cmd)
1185 normalizenewlines = os.name == 'nt'
1185 normalizenewlines = os.name == 'nt'
1186 result = self._runcommand(cmd, env,
1186 result = self._runcommand(cmd, env,
1187 normalizenewlines=normalizenewlines)
1187 normalizenewlines=normalizenewlines)
1188 if self._aborted:
1188 if self._aborted:
1189 raise KeyboardInterrupt()
1189 raise KeyboardInterrupt()
1190
1190
1191 return result
1191 return result
1192
1192
1193 # Some glob patterns apply only in some circumstances, so the script
1193 # Some glob patterns apply only in some circumstances, so the script
1194 # might want to remove (glob) annotations that otherwise should be
1194 # might want to remove (glob) annotations that otherwise should be
1195 # retained.
1195 # retained.
1196 checkcodeglobpats = [
1196 checkcodeglobpats = [
1197 # On Windows it looks like \ doesn't require a (glob), but we know
1197 # On Windows it looks like \ doesn't require a (glob), but we know
1198 # better.
1198 # better.
1199 re.compile(br'^pushing to \$TESTTMP/.*[^)]$'),
1199 re.compile(br'^pushing to \$TESTTMP/.*[^)]$'),
1200 re.compile(br'^moving \S+/.*[^)]$'),
1200 re.compile(br'^moving \S+/.*[^)]$'),
1201 re.compile(br'^pulling from \$TESTTMP/.*[^)]$'),
1201 re.compile(br'^pulling from \$TESTTMP/.*[^)]$'),
1202 # Not all platforms have 127.0.0.1 as loopback (though most do),
1202 # Not all platforms have 127.0.0.1 as loopback (though most do),
1203 # so we always glob that too.
1203 # so we always glob that too.
1204 re.compile(br'.*\$LOCALIP.*$'),
1204 re.compile(br'.*\$LOCALIP.*$'),
1205 ]
1205 ]
1206
1206
1207 bchr = chr
1207 bchr = chr
1208 if PYTHON3:
1208 if PYTHON3:
1209 bchr = lambda x: bytes([x])
1209 bchr = lambda x: bytes([x])
1210
1210
1211 class TTest(Test):
1211 class TTest(Test):
1212 """A "t test" is a test backed by a .t file."""
1212 """A "t test" is a test backed by a .t file."""
1213
1213
1214 SKIPPED_PREFIX = b'skipped: '
1214 SKIPPED_PREFIX = b'skipped: '
1215 FAILED_PREFIX = b'hghave check failed: '
1215 FAILED_PREFIX = b'hghave check failed: '
1216 NEEDESCAPE = re.compile(br'[\x00-\x08\x0b-\x1f\x7f-\xff]').search
1216 NEEDESCAPE = re.compile(br'[\x00-\x08\x0b-\x1f\x7f-\xff]').search
1217
1217
1218 ESCAPESUB = re.compile(br'[\x00-\x08\x0b-\x1f\\\x7f-\xff]').sub
1218 ESCAPESUB = re.compile(br'[\x00-\x08\x0b-\x1f\\\x7f-\xff]').sub
1219 ESCAPEMAP = dict((bchr(i), br'\x%02x' % i) for i in range(256))
1219 ESCAPEMAP = dict((bchr(i), br'\x%02x' % i) for i in range(256))
1220 ESCAPEMAP.update({b'\\': b'\\\\', b'\r': br'\r'})
1220 ESCAPEMAP.update({b'\\': b'\\\\', b'\r': br'\r'})
1221
1221
1222 def __init__(self, path, *args, **kwds):
1222 def __init__(self, path, *args, **kwds):
1223 # accept an extra "case" parameter
1223 # accept an extra "case" parameter
1224 case = kwds.pop('case', None)
1224 case = kwds.pop('case', None)
1225 self._case = case
1225 self._case = case
1226 self._allcases = parsettestcases(path)
1226 self._allcases = parsettestcases(path)
1227 super(TTest, self).__init__(path, *args, **kwds)
1227 super(TTest, self).__init__(path, *args, **kwds)
1228 if case:
1228 if case:
1229 self.name = '%s (case %s)' % (self.name, _strpath(case))
1229 self.name = '%s (case %s)' % (self.name, _strpath(case))
1230 self.errpath = b'%s.%s.err' % (self.errpath[:-4], case)
1230 self.errpath = b'%s.%s.err' % (self.errpath[:-4], case)
1231 self._tmpname += b'-%s' % case
1231 self._tmpname += b'-%s' % case
1232
1232
1233 @property
1233 @property
1234 def refpath(self):
1234 def refpath(self):
1235 return os.path.join(self._testdir, self.bname)
1235 return os.path.join(self._testdir, self.bname)
1236
1236
1237 def _run(self, env):
1237 def _run(self, env):
1238 with open(self.path, 'rb') as f:
1238 with open(self.path, 'rb') as f:
1239 lines = f.readlines()
1239 lines = f.readlines()
1240
1240
1241 # .t file is both reference output and the test input, keep reference
1241 # .t file is both reference output and the test input, keep reference
1242 # output updated with the the test input. This avoids some race
1242 # output updated with the the test input. This avoids some race
1243 # conditions where the reference output does not match the actual test.
1243 # conditions where the reference output does not match the actual test.
1244 if self._refout is not None:
1244 if self._refout is not None:
1245 self._refout = lines
1245 self._refout = lines
1246
1246
1247 salt, script, after, expected = self._parsetest(lines)
1247 salt, script, after, expected = self._parsetest(lines)
1248
1248
1249 # Write out the generated script.
1249 # Write out the generated script.
1250 fname = b'%s.sh' % self._testtmp
1250 fname = b'%s.sh' % self._testtmp
1251 with open(fname, 'wb') as f:
1251 with open(fname, 'wb') as f:
1252 for l in script:
1252 for l in script:
1253 f.write(l)
1253 f.write(l)
1254
1254
1255 cmd = b'%s "%s"' % (self._shell, fname)
1255 cmd = b'%s "%s"' % (self._shell, fname)
1256 vlog("# Running", cmd)
1256 vlog("# Running", cmd)
1257
1257
1258 exitcode, output = self._runcommand(cmd, env)
1258 exitcode, output = self._runcommand(cmd, env)
1259
1259
1260 if self._aborted:
1260 if self._aborted:
1261 raise KeyboardInterrupt()
1261 raise KeyboardInterrupt()
1262
1262
1263 # Do not merge output if skipped. Return hghave message instead.
1263 # Do not merge output if skipped. Return hghave message instead.
1264 # Similarly, with --debug, output is None.
1264 # Similarly, with --debug, output is None.
1265 if exitcode == self.SKIPPED_STATUS or output is None:
1265 if exitcode == self.SKIPPED_STATUS or output is None:
1266 return exitcode, output
1266 return exitcode, output
1267
1267
1268 return self._processoutput(exitcode, output, salt, after, expected)
1268 return self._processoutput(exitcode, output, salt, after, expected)
1269
1269
1270 def _hghave(self, reqs):
1270 def _hghave(self, reqs):
1271 # TODO do something smarter when all other uses of hghave are gone.
1271 # TODO do something smarter when all other uses of hghave are gone.
1272 runtestdir = os.path.abspath(os.path.dirname(_bytespath(__file__)))
1272 runtestdir = os.path.abspath(os.path.dirname(_bytespath(__file__)))
1273 tdir = runtestdir.replace(b'\\', b'/')
1273 tdir = runtestdir.replace(b'\\', b'/')
1274 proc = Popen4(b'%s -c "%s/hghave %s"' %
1274 proc = Popen4(b'%s -c "%s/hghave %s"' %
1275 (self._shell, tdir, b' '.join(reqs)),
1275 (self._shell, tdir, b' '.join(reqs)),
1276 self._testtmp, 0, self._getenv())
1276 self._testtmp, 0, self._getenv())
1277 stdout, stderr = proc.communicate()
1277 stdout, stderr = proc.communicate()
1278 ret = proc.wait()
1278 ret = proc.wait()
1279 if wifexited(ret):
1279 if wifexited(ret):
1280 ret = os.WEXITSTATUS(ret)
1280 ret = os.WEXITSTATUS(ret)
1281 if ret == 2:
1281 if ret == 2:
1282 print(stdout.decode('utf-8'))
1282 print(stdout.decode('utf-8'))
1283 sys.exit(1)
1283 sys.exit(1)
1284
1284
1285 if ret != 0:
1285 if ret != 0:
1286 return False, stdout
1286 return False, stdout
1287
1287
1288 if b'slow' in reqs:
1288 if b'slow' in reqs:
1289 self._timeout = self._slowtimeout
1289 self._timeout = self._slowtimeout
1290 return True, None
1290 return True, None
1291
1291
1292 def _iftest(self, args):
1292 def _iftest(self, args):
1293 # implements "#if"
1293 # implements "#if"
1294 reqs = []
1294 reqs = []
1295 for arg in args:
1295 for arg in args:
1296 if arg.startswith(b'no-') and arg[3:] in self._allcases:
1296 if arg.startswith(b'no-') and arg[3:] in self._allcases:
1297 if arg[3:] == self._case:
1297 if arg[3:] == self._case:
1298 return False
1298 return False
1299 elif arg in self._allcases:
1299 elif arg in self._allcases:
1300 if arg != self._case:
1300 if arg != self._case:
1301 return False
1301 return False
1302 else:
1302 else:
1303 reqs.append(arg)
1303 reqs.append(arg)
1304 return self._hghave(reqs)[0]
1304 return self._hghave(reqs)[0]
1305
1305
1306 def _parsetest(self, lines):
1306 def _parsetest(self, lines):
1307 # We generate a shell script which outputs unique markers to line
1307 # We generate a shell script which outputs unique markers to line
1308 # up script results with our source. These markers include input
1308 # up script results with our source. These markers include input
1309 # line number and the last return code.
1309 # line number and the last return code.
1310 salt = b"SALT%d" % time.time()
1310 salt = b"SALT%d" % time.time()
1311 def addsalt(line, inpython):
1311 def addsalt(line, inpython):
1312 if inpython:
1312 if inpython:
1313 script.append(b'%s %d 0\n' % (salt, line))
1313 script.append(b'%s %d 0\n' % (salt, line))
1314 else:
1314 else:
1315 script.append(b'echo %s %d $?\n' % (salt, line))
1315 script.append(b'echo %s %d $?\n' % (salt, line))
1316
1316
1317 script = []
1317 script = []
1318
1318
1319 # After we run the shell script, we re-unify the script output
1319 # After we run the shell script, we re-unify the script output
1320 # with non-active parts of the source, with synchronization by our
1320 # with non-active parts of the source, with synchronization by our
1321 # SALT line number markers. The after table contains the non-active
1321 # SALT line number markers. The after table contains the non-active
1322 # components, ordered by line number.
1322 # components, ordered by line number.
1323 after = {}
1323 after = {}
1324
1324
1325 # Expected shell script output.
1325 # Expected shell script output.
1326 expected = {}
1326 expected = {}
1327
1327
1328 pos = prepos = -1
1328 pos = prepos = -1
1329
1329
1330 # True or False when in a true or false conditional section
1330 # True or False when in a true or false conditional section
1331 skipping = None
1331 skipping = None
1332
1332
1333 # We keep track of whether or not we're in a Python block so we
1333 # We keep track of whether or not we're in a Python block so we
1334 # can generate the surrounding doctest magic.
1334 # can generate the surrounding doctest magic.
1335 inpython = False
1335 inpython = False
1336
1336
1337 if self._debug:
1337 if self._debug:
1338 script.append(b'set -x\n')
1338 script.append(b'set -x\n')
1339 if self._hgcommand != b'hg':
1339 if self._hgcommand != b'hg':
1340 script.append(b'alias hg="%s"\n' % self._hgcommand)
1340 script.append(b'alias hg="%s"\n' % self._hgcommand)
1341 if os.getenv('MSYSTEM'):
1341 if os.getenv('MSYSTEM'):
1342 script.append(b'alias pwd="pwd -W"\n')
1342 script.append(b'alias pwd="pwd -W"\n')
1343 if self._case:
1343 if self._case:
1344 script.append(b'TESTCASE=%s\n' % shellquote(self._case))
1344 if isinstance(self._case, str):
1345 quoted = shellquote(self._case)
1346 else:
1347 quoted = shellquote(self._case.decode('utf8')).encode('utf8')
1348 script.append(b'TESTCASE=%s\n' % quoted)
1345 script.append(b'export TESTCASE\n')
1349 script.append(b'export TESTCASE\n')
1346
1350
1347 n = 0
1351 n = 0
1348 for n, l in enumerate(lines):
1352 for n, l in enumerate(lines):
1349 if not l.endswith(b'\n'):
1353 if not l.endswith(b'\n'):
1350 l += b'\n'
1354 l += b'\n'
1351 if l.startswith(b'#require'):
1355 if l.startswith(b'#require'):
1352 lsplit = l.split()
1356 lsplit = l.split()
1353 if len(lsplit) < 2 or lsplit[0] != b'#require':
1357 if len(lsplit) < 2 or lsplit[0] != b'#require':
1354 after.setdefault(pos, []).append(' !!! invalid #require\n')
1358 after.setdefault(pos, []).append(' !!! invalid #require\n')
1355 haveresult, message = self._hghave(lsplit[1:])
1359 haveresult, message = self._hghave(lsplit[1:])
1356 if not haveresult:
1360 if not haveresult:
1357 script = [b'echo "%s"\nexit 80\n' % message]
1361 script = [b'echo "%s"\nexit 80\n' % message]
1358 break
1362 break
1359 after.setdefault(pos, []).append(l)
1363 after.setdefault(pos, []).append(l)
1360 elif l.startswith(b'#if'):
1364 elif l.startswith(b'#if'):
1361 lsplit = l.split()
1365 lsplit = l.split()
1362 if len(lsplit) < 2 or lsplit[0] != b'#if':
1366 if len(lsplit) < 2 or lsplit[0] != b'#if':
1363 after.setdefault(pos, []).append(' !!! invalid #if\n')
1367 after.setdefault(pos, []).append(' !!! invalid #if\n')
1364 if skipping is not None:
1368 if skipping is not None:
1365 after.setdefault(pos, []).append(' !!! nested #if\n')
1369 after.setdefault(pos, []).append(' !!! nested #if\n')
1366 skipping = not self._iftest(lsplit[1:])
1370 skipping = not self._iftest(lsplit[1:])
1367 after.setdefault(pos, []).append(l)
1371 after.setdefault(pos, []).append(l)
1368 elif l.startswith(b'#else'):
1372 elif l.startswith(b'#else'):
1369 if skipping is None:
1373 if skipping is None:
1370 after.setdefault(pos, []).append(' !!! missing #if\n')
1374 after.setdefault(pos, []).append(' !!! missing #if\n')
1371 skipping = not skipping
1375 skipping = not skipping
1372 after.setdefault(pos, []).append(l)
1376 after.setdefault(pos, []).append(l)
1373 elif l.startswith(b'#endif'):
1377 elif l.startswith(b'#endif'):
1374 if skipping is None:
1378 if skipping is None:
1375 after.setdefault(pos, []).append(' !!! missing #if\n')
1379 after.setdefault(pos, []).append(' !!! missing #if\n')
1376 skipping = None
1380 skipping = None
1377 after.setdefault(pos, []).append(l)
1381 after.setdefault(pos, []).append(l)
1378 elif skipping:
1382 elif skipping:
1379 after.setdefault(pos, []).append(l)
1383 after.setdefault(pos, []).append(l)
1380 elif l.startswith(b' >>> '): # python inlines
1384 elif l.startswith(b' >>> '): # python inlines
1381 after.setdefault(pos, []).append(l)
1385 after.setdefault(pos, []).append(l)
1382 prepos = pos
1386 prepos = pos
1383 pos = n
1387 pos = n
1384 if not inpython:
1388 if not inpython:
1385 # We've just entered a Python block. Add the header.
1389 # We've just entered a Python block. Add the header.
1386 inpython = True
1390 inpython = True
1387 addsalt(prepos, False) # Make sure we report the exit code.
1391 addsalt(prepos, False) # Make sure we report the exit code.
1388 script.append(b'%s -m heredoctest <<EOF\n' % PYTHON)
1392 script.append(b'%s -m heredoctest <<EOF\n' % PYTHON)
1389 addsalt(n, True)
1393 addsalt(n, True)
1390 script.append(l[2:])
1394 script.append(l[2:])
1391 elif l.startswith(b' ... '): # python inlines
1395 elif l.startswith(b' ... '): # python inlines
1392 after.setdefault(prepos, []).append(l)
1396 after.setdefault(prepos, []).append(l)
1393 script.append(l[2:])
1397 script.append(l[2:])
1394 elif l.startswith(b' $ '): # commands
1398 elif l.startswith(b' $ '): # commands
1395 if inpython:
1399 if inpython:
1396 script.append(b'EOF\n')
1400 script.append(b'EOF\n')
1397 inpython = False
1401 inpython = False
1398 after.setdefault(pos, []).append(l)
1402 after.setdefault(pos, []).append(l)
1399 prepos = pos
1403 prepos = pos
1400 pos = n
1404 pos = n
1401 addsalt(n, False)
1405 addsalt(n, False)
1402 cmd = l[4:].split()
1406 cmd = l[4:].split()
1403 if len(cmd) == 2 and cmd[0] == b'cd':
1407 if len(cmd) == 2 and cmd[0] == b'cd':
1404 l = b' $ cd %s || exit 1\n' % cmd[1]
1408 l = b' $ cd %s || exit 1\n' % cmd[1]
1405 script.append(l[4:])
1409 script.append(l[4:])
1406 elif l.startswith(b' > '): # continuations
1410 elif l.startswith(b' > '): # continuations
1407 after.setdefault(prepos, []).append(l)
1411 after.setdefault(prepos, []).append(l)
1408 script.append(l[4:])
1412 script.append(l[4:])
1409 elif l.startswith(b' '): # results
1413 elif l.startswith(b' '): # results
1410 # Queue up a list of expected results.
1414 # Queue up a list of expected results.
1411 expected.setdefault(pos, []).append(l[2:])
1415 expected.setdefault(pos, []).append(l[2:])
1412 else:
1416 else:
1413 if inpython:
1417 if inpython:
1414 script.append(b'EOF\n')
1418 script.append(b'EOF\n')
1415 inpython = False
1419 inpython = False
1416 # Non-command/result. Queue up for merged output.
1420 # Non-command/result. Queue up for merged output.
1417 after.setdefault(pos, []).append(l)
1421 after.setdefault(pos, []).append(l)
1418
1422
1419 if inpython:
1423 if inpython:
1420 script.append(b'EOF\n')
1424 script.append(b'EOF\n')
1421 if skipping is not None:
1425 if skipping is not None:
1422 after.setdefault(pos, []).append(' !!! missing #endif\n')
1426 after.setdefault(pos, []).append(' !!! missing #endif\n')
1423 addsalt(n + 1, False)
1427 addsalt(n + 1, False)
1424
1428
1425 return salt, script, after, expected
1429 return salt, script, after, expected
1426
1430
1427 def _processoutput(self, exitcode, output, salt, after, expected):
1431 def _processoutput(self, exitcode, output, salt, after, expected):
1428 # Merge the script output back into a unified test.
1432 # Merge the script output back into a unified test.
1429 warnonly = 1 # 1: not yet; 2: yes; 3: for sure not
1433 warnonly = 1 # 1: not yet; 2: yes; 3: for sure not
1430 if exitcode != 0:
1434 if exitcode != 0:
1431 warnonly = 3
1435 warnonly = 3
1432
1436
1433 pos = -1
1437 pos = -1
1434 postout = []
1438 postout = []
1435 for l in output:
1439 for l in output:
1436 lout, lcmd = l, None
1440 lout, lcmd = l, None
1437 if salt in l:
1441 if salt in l:
1438 lout, lcmd = l.split(salt, 1)
1442 lout, lcmd = l.split(salt, 1)
1439
1443
1440 while lout:
1444 while lout:
1441 if not lout.endswith(b'\n'):
1445 if not lout.endswith(b'\n'):
1442 lout += b' (no-eol)\n'
1446 lout += b' (no-eol)\n'
1443
1447
1444 # Find the expected output at the current position.
1448 # Find the expected output at the current position.
1445 els = [None]
1449 els = [None]
1446 if expected.get(pos, None):
1450 if expected.get(pos, None):
1447 els = expected[pos]
1451 els = expected[pos]
1448
1452
1449 i = 0
1453 i = 0
1450 optional = []
1454 optional = []
1451 while i < len(els):
1455 while i < len(els):
1452 el = els[i]
1456 el = els[i]
1453
1457
1454 r = self.linematch(el, lout)
1458 r = self.linematch(el, lout)
1455 if isinstance(r, str):
1459 if isinstance(r, str):
1456 if r == '-glob':
1460 if r == '-glob':
1457 lout = ''.join(el.rsplit(' (glob)', 1))
1461 lout = ''.join(el.rsplit(' (glob)', 1))
1458 r = '' # Warn only this line.
1462 r = '' # Warn only this line.
1459 elif r == "retry":
1463 elif r == "retry":
1460 postout.append(b' ' + el)
1464 postout.append(b' ' + el)
1461 els.pop(i)
1465 els.pop(i)
1462 break
1466 break
1463 else:
1467 else:
1464 log('\ninfo, unknown linematch result: %r\n' % r)
1468 log('\ninfo, unknown linematch result: %r\n' % r)
1465 r = False
1469 r = False
1466 if r:
1470 if r:
1467 els.pop(i)
1471 els.pop(i)
1468 break
1472 break
1469 if el:
1473 if el:
1470 if el.endswith(b" (?)\n"):
1474 if el.endswith(b" (?)\n"):
1471 optional.append(i)
1475 optional.append(i)
1472 else:
1476 else:
1473 m = optline.match(el)
1477 m = optline.match(el)
1474 if m:
1478 if m:
1475 conditions = [
1479 conditions = [
1476 c for c in m.group(2).split(b' ')]
1480 c for c in m.group(2).split(b' ')]
1477
1481
1478 if not self._iftest(conditions):
1482 if not self._iftest(conditions):
1479 optional.append(i)
1483 optional.append(i)
1480
1484
1481 i += 1
1485 i += 1
1482
1486
1483 if r:
1487 if r:
1484 if r == "retry":
1488 if r == "retry":
1485 continue
1489 continue
1486 # clean up any optional leftovers
1490 # clean up any optional leftovers
1487 for i in optional:
1491 for i in optional:
1488 postout.append(b' ' + els[i])
1492 postout.append(b' ' + els[i])
1489 for i in reversed(optional):
1493 for i in reversed(optional):
1490 del els[i]
1494 del els[i]
1491 postout.append(b' ' + el)
1495 postout.append(b' ' + el)
1492 else:
1496 else:
1493 if self.NEEDESCAPE(lout):
1497 if self.NEEDESCAPE(lout):
1494 lout = TTest._stringescape(b'%s (esc)\n' %
1498 lout = TTest._stringescape(b'%s (esc)\n' %
1495 lout.rstrip(b'\n'))
1499 lout.rstrip(b'\n'))
1496 postout.append(b' ' + lout) # Let diff deal with it.
1500 postout.append(b' ' + lout) # Let diff deal with it.
1497 if r != '': # If line failed.
1501 if r != '': # If line failed.
1498 warnonly = 3 # for sure not
1502 warnonly = 3 # for sure not
1499 elif warnonly == 1: # Is "not yet" and line is warn only.
1503 elif warnonly == 1: # Is "not yet" and line is warn only.
1500 warnonly = 2 # Yes do warn.
1504 warnonly = 2 # Yes do warn.
1501 break
1505 break
1502 else:
1506 else:
1503 # clean up any optional leftovers
1507 # clean up any optional leftovers
1504 while expected.get(pos, None):
1508 while expected.get(pos, None):
1505 el = expected[pos].pop(0)
1509 el = expected[pos].pop(0)
1506 if el:
1510 if el:
1507 if not el.endswith(b" (?)\n"):
1511 if not el.endswith(b" (?)\n"):
1508 m = optline.match(el)
1512 m = optline.match(el)
1509 if m:
1513 if m:
1510 conditions = [c for c in m.group(2).split(b' ')]
1514 conditions = [c for c in m.group(2).split(b' ')]
1511
1515
1512 if self._iftest(conditions):
1516 if self._iftest(conditions):
1513 # Don't append as optional line
1517 # Don't append as optional line
1514 continue
1518 continue
1515 else:
1519 else:
1516 continue
1520 continue
1517 postout.append(b' ' + el)
1521 postout.append(b' ' + el)
1518
1522
1519 if lcmd:
1523 if lcmd:
1520 # Add on last return code.
1524 # Add on last return code.
1521 ret = int(lcmd.split()[1])
1525 ret = int(lcmd.split()[1])
1522 if ret != 0:
1526 if ret != 0:
1523 postout.append(b' [%d]\n' % ret)
1527 postout.append(b' [%d]\n' % ret)
1524 if pos in after:
1528 if pos in after:
1525 # Merge in non-active test bits.
1529 # Merge in non-active test bits.
1526 postout += after.pop(pos)
1530 postout += after.pop(pos)
1527 pos = int(lcmd.split()[0])
1531 pos = int(lcmd.split()[0])
1528
1532
1529 if pos in after:
1533 if pos in after:
1530 postout += after.pop(pos)
1534 postout += after.pop(pos)
1531
1535
1532 if warnonly == 2:
1536 if warnonly == 2:
1533 exitcode = False # Set exitcode to warned.
1537 exitcode = False # Set exitcode to warned.
1534
1538
1535 return exitcode, postout
1539 return exitcode, postout
1536
1540
1537 @staticmethod
1541 @staticmethod
1538 def rematch(el, l):
1542 def rematch(el, l):
1539 try:
1543 try:
1540 el = b'(?:' + el + b')'
1544 el = b'(?:' + el + b')'
1541 # use \Z to ensure that the regex matches to the end of the string
1545 # use \Z to ensure that the regex matches to the end of the string
1542 if os.name == 'nt':
1546 if os.name == 'nt':
1543 return re.match(el + br'\r?\n\Z', l)
1547 return re.match(el + br'\r?\n\Z', l)
1544 return re.match(el + br'\n\Z', l)
1548 return re.match(el + br'\n\Z', l)
1545 except re.error:
1549 except re.error:
1546 # el is an invalid regex
1550 # el is an invalid regex
1547 return False
1551 return False
1548
1552
1549 @staticmethod
1553 @staticmethod
1550 def globmatch(el, l):
1554 def globmatch(el, l):
1551 # The only supported special characters are * and ? plus / which also
1555 # The only supported special characters are * and ? plus / which also
1552 # matches \ on windows. Escaping of these characters is supported.
1556 # matches \ on windows. Escaping of these characters is supported.
1553 if el + b'\n' == l:
1557 if el + b'\n' == l:
1554 if os.altsep:
1558 if os.altsep:
1555 # matching on "/" is not needed for this line
1559 # matching on "/" is not needed for this line
1556 for pat in checkcodeglobpats:
1560 for pat in checkcodeglobpats:
1557 if pat.match(el):
1561 if pat.match(el):
1558 return True
1562 return True
1559 return b'-glob'
1563 return b'-glob'
1560 return True
1564 return True
1561 el = el.replace(b'$LOCALIP', b'*')
1565 el = el.replace(b'$LOCALIP', b'*')
1562 i, n = 0, len(el)
1566 i, n = 0, len(el)
1563 res = b''
1567 res = b''
1564 while i < n:
1568 while i < n:
1565 c = el[i:i + 1]
1569 c = el[i:i + 1]
1566 i += 1
1570 i += 1
1567 if c == b'\\' and i < n and el[i:i + 1] in b'*?\\/':
1571 if c == b'\\' and i < n and el[i:i + 1] in b'*?\\/':
1568 res += el[i - 1:i + 1]
1572 res += el[i - 1:i + 1]
1569 i += 1
1573 i += 1
1570 elif c == b'*':
1574 elif c == b'*':
1571 res += b'.*'
1575 res += b'.*'
1572 elif c == b'?':
1576 elif c == b'?':
1573 res += b'.'
1577 res += b'.'
1574 elif c == b'/' and os.altsep:
1578 elif c == b'/' and os.altsep:
1575 res += b'[/\\\\]'
1579 res += b'[/\\\\]'
1576 else:
1580 else:
1577 res += re.escape(c)
1581 res += re.escape(c)
1578 return TTest.rematch(res, l)
1582 return TTest.rematch(res, l)
1579
1583
1580 def linematch(self, el, l):
1584 def linematch(self, el, l):
1581 retry = False
1585 retry = False
1582 if el == l: # perfect match (fast)
1586 if el == l: # perfect match (fast)
1583 return True
1587 return True
1584 if el:
1588 if el:
1585 if el.endswith(b" (?)\n"):
1589 if el.endswith(b" (?)\n"):
1586 retry = "retry"
1590 retry = "retry"
1587 el = el[:-5] + b"\n"
1591 el = el[:-5] + b"\n"
1588 else:
1592 else:
1589 m = optline.match(el)
1593 m = optline.match(el)
1590 if m:
1594 if m:
1591 conditions = [c for c in m.group(2).split(b' ')]
1595 conditions = [c for c in m.group(2).split(b' ')]
1592
1596
1593 el = m.group(1) + b"\n"
1597 el = m.group(1) + b"\n"
1594 if not self._iftest(conditions):
1598 if not self._iftest(conditions):
1595 retry = "retry" # Not required by listed features
1599 retry = "retry" # Not required by listed features
1596
1600
1597 if el.endswith(b" (esc)\n"):
1601 if el.endswith(b" (esc)\n"):
1598 if PYTHON3:
1602 if PYTHON3:
1599 el = el[:-7].decode('unicode_escape') + '\n'
1603 el = el[:-7].decode('unicode_escape') + '\n'
1600 el = el.encode('utf-8')
1604 el = el.encode('utf-8')
1601 else:
1605 else:
1602 el = el[:-7].decode('string-escape') + '\n'
1606 el = el[:-7].decode('string-escape') + '\n'
1603 if el == l or os.name == 'nt' and el[:-1] + b'\r\n' == l:
1607 if el == l or os.name == 'nt' and el[:-1] + b'\r\n' == l:
1604 return True
1608 return True
1605 if el.endswith(b" (re)\n"):
1609 if el.endswith(b" (re)\n"):
1606 return TTest.rematch(el[:-6], l) or retry
1610 return TTest.rematch(el[:-6], l) or retry
1607 if el.endswith(b" (glob)\n"):
1611 if el.endswith(b" (glob)\n"):
1608 # ignore '(glob)' added to l by 'replacements'
1612 # ignore '(glob)' added to l by 'replacements'
1609 if l.endswith(b" (glob)\n"):
1613 if l.endswith(b" (glob)\n"):
1610 l = l[:-8] + b"\n"
1614 l = l[:-8] + b"\n"
1611 return TTest.globmatch(el[:-8], l) or retry
1615 return TTest.globmatch(el[:-8], l) or retry
1612 if os.altsep:
1616 if os.altsep:
1613 _l = l.replace(b'\\', b'/')
1617 _l = l.replace(b'\\', b'/')
1614 if el == _l or os.name == 'nt' and el[:-1] + b'\r\n' == _l:
1618 if el == _l or os.name == 'nt' and el[:-1] + b'\r\n' == _l:
1615 return True
1619 return True
1616 return retry
1620 return retry
1617
1621
1618 @staticmethod
1622 @staticmethod
1619 def parsehghaveoutput(lines):
1623 def parsehghaveoutput(lines):
1620 '''Parse hghave log lines.
1624 '''Parse hghave log lines.
1621
1625
1622 Return tuple of lists (missing, failed):
1626 Return tuple of lists (missing, failed):
1623 * the missing/unknown features
1627 * the missing/unknown features
1624 * the features for which existence check failed'''
1628 * the features for which existence check failed'''
1625 missing = []
1629 missing = []
1626 failed = []
1630 failed = []
1627 for line in lines:
1631 for line in lines:
1628 if line.startswith(TTest.SKIPPED_PREFIX):
1632 if line.startswith(TTest.SKIPPED_PREFIX):
1629 line = line.splitlines()[0]
1633 line = line.splitlines()[0]
1630 missing.append(line[len(TTest.SKIPPED_PREFIX):].decode('utf-8'))
1634 missing.append(line[len(TTest.SKIPPED_PREFIX):].decode('utf-8'))
1631 elif line.startswith(TTest.FAILED_PREFIX):
1635 elif line.startswith(TTest.FAILED_PREFIX):
1632 line = line.splitlines()[0]
1636 line = line.splitlines()[0]
1633 failed.append(line[len(TTest.FAILED_PREFIX):].decode('utf-8'))
1637 failed.append(line[len(TTest.FAILED_PREFIX):].decode('utf-8'))
1634
1638
1635 return missing, failed
1639 return missing, failed
1636
1640
1637 @staticmethod
1641 @staticmethod
1638 def _escapef(m):
1642 def _escapef(m):
1639 return TTest.ESCAPEMAP[m.group(0)]
1643 return TTest.ESCAPEMAP[m.group(0)]
1640
1644
1641 @staticmethod
1645 @staticmethod
1642 def _stringescape(s):
1646 def _stringescape(s):
1643 return TTest.ESCAPESUB(TTest._escapef, s)
1647 return TTest.ESCAPESUB(TTest._escapef, s)
1644
1648
1645 iolock = threading.RLock()
1649 iolock = threading.RLock()
1646 firstlock = threading.RLock()
1650 firstlock = threading.RLock()
1647 firsterror = False
1651 firsterror = False
1648
1652
1649 class TestResult(unittest._TextTestResult):
1653 class TestResult(unittest._TextTestResult):
1650 """Holds results when executing via unittest."""
1654 """Holds results when executing via unittest."""
1651 # Don't worry too much about accessing the non-public _TextTestResult.
1655 # Don't worry too much about accessing the non-public _TextTestResult.
1652 # It is relatively common in Python testing tools.
1656 # It is relatively common in Python testing tools.
1653 def __init__(self, options, *args, **kwargs):
1657 def __init__(self, options, *args, **kwargs):
1654 super(TestResult, self).__init__(*args, **kwargs)
1658 super(TestResult, self).__init__(*args, **kwargs)
1655
1659
1656 self._options = options
1660 self._options = options
1657
1661
1658 # unittest.TestResult didn't have skipped until 2.7. We need to
1662 # unittest.TestResult didn't have skipped until 2.7. We need to
1659 # polyfill it.
1663 # polyfill it.
1660 self.skipped = []
1664 self.skipped = []
1661
1665
1662 # We have a custom "ignored" result that isn't present in any Python
1666 # We have a custom "ignored" result that isn't present in any Python
1663 # unittest implementation. It is very similar to skipped. It may make
1667 # unittest implementation. It is very similar to skipped. It may make
1664 # sense to map it into skip some day.
1668 # sense to map it into skip some day.
1665 self.ignored = []
1669 self.ignored = []
1666
1670
1667 self.times = []
1671 self.times = []
1668 self._firststarttime = None
1672 self._firststarttime = None
1669 # Data stored for the benefit of generating xunit reports.
1673 # Data stored for the benefit of generating xunit reports.
1670 self.successes = []
1674 self.successes = []
1671 self.faildata = {}
1675 self.faildata = {}
1672
1676
1673 if options.color == 'auto':
1677 if options.color == 'auto':
1674 self.color = pygmentspresent and self.stream.isatty()
1678 self.color = pygmentspresent and self.stream.isatty()
1675 elif options.color == 'never':
1679 elif options.color == 'never':
1676 self.color = False
1680 self.color = False
1677 else: # 'always', for testing purposes
1681 else: # 'always', for testing purposes
1678 self.color = pygmentspresent
1682 self.color = pygmentspresent
1679
1683
1680 def addFailure(self, test, reason):
1684 def addFailure(self, test, reason):
1681 self.failures.append((test, reason))
1685 self.failures.append((test, reason))
1682
1686
1683 if self._options.first:
1687 if self._options.first:
1684 self.stop()
1688 self.stop()
1685 else:
1689 else:
1686 with iolock:
1690 with iolock:
1687 if reason == "timed out":
1691 if reason == "timed out":
1688 self.stream.write('t')
1692 self.stream.write('t')
1689 else:
1693 else:
1690 if not self._options.nodiff:
1694 if not self._options.nodiff:
1691 self.stream.write('\n')
1695 self.stream.write('\n')
1692 # Exclude the '\n' from highlighting to lex correctly
1696 # Exclude the '\n' from highlighting to lex correctly
1693 formatted = 'ERROR: %s output changed\n' % test
1697 formatted = 'ERROR: %s output changed\n' % test
1694 self.stream.write(highlightmsg(formatted, self.color))
1698 self.stream.write(highlightmsg(formatted, self.color))
1695 self.stream.write('!')
1699 self.stream.write('!')
1696
1700
1697 self.stream.flush()
1701 self.stream.flush()
1698
1702
1699 def addSuccess(self, test):
1703 def addSuccess(self, test):
1700 with iolock:
1704 with iolock:
1701 super(TestResult, self).addSuccess(test)
1705 super(TestResult, self).addSuccess(test)
1702 self.successes.append(test)
1706 self.successes.append(test)
1703
1707
1704 def addError(self, test, err):
1708 def addError(self, test, err):
1705 super(TestResult, self).addError(test, err)
1709 super(TestResult, self).addError(test, err)
1706 if self._options.first:
1710 if self._options.first:
1707 self.stop()
1711 self.stop()
1708
1712
1709 # Polyfill.
1713 # Polyfill.
1710 def addSkip(self, test, reason):
1714 def addSkip(self, test, reason):
1711 self.skipped.append((test, reason))
1715 self.skipped.append((test, reason))
1712 with iolock:
1716 with iolock:
1713 if self.showAll:
1717 if self.showAll:
1714 self.stream.writeln('skipped %s' % reason)
1718 self.stream.writeln('skipped %s' % reason)
1715 else:
1719 else:
1716 self.stream.write('s')
1720 self.stream.write('s')
1717 self.stream.flush()
1721 self.stream.flush()
1718
1722
1719 def addIgnore(self, test, reason):
1723 def addIgnore(self, test, reason):
1720 self.ignored.append((test, reason))
1724 self.ignored.append((test, reason))
1721 with iolock:
1725 with iolock:
1722 if self.showAll:
1726 if self.showAll:
1723 self.stream.writeln('ignored %s' % reason)
1727 self.stream.writeln('ignored %s' % reason)
1724 else:
1728 else:
1725 if reason not in ('not retesting', "doesn't match keyword"):
1729 if reason not in ('not retesting', "doesn't match keyword"):
1726 self.stream.write('i')
1730 self.stream.write('i')
1727 else:
1731 else:
1728 self.testsRun += 1
1732 self.testsRun += 1
1729 self.stream.flush()
1733 self.stream.flush()
1730
1734
1731 def addOutputMismatch(self, test, ret, got, expected):
1735 def addOutputMismatch(self, test, ret, got, expected):
1732 """Record a mismatch in test output for a particular test."""
1736 """Record a mismatch in test output for a particular test."""
1733 if self.shouldStop or firsterror:
1737 if self.shouldStop or firsterror:
1734 # don't print, some other test case already failed and
1738 # don't print, some other test case already failed and
1735 # printed, we're just stale and probably failed due to our
1739 # printed, we're just stale and probably failed due to our
1736 # temp dir getting cleaned up.
1740 # temp dir getting cleaned up.
1737 return
1741 return
1738
1742
1739 accepted = False
1743 accepted = False
1740 lines = []
1744 lines = []
1741
1745
1742 with iolock:
1746 with iolock:
1743 if self._options.nodiff:
1747 if self._options.nodiff:
1744 pass
1748 pass
1745 elif self._options.view:
1749 elif self._options.view:
1746 v = self._options.view
1750 v = self._options.view
1747 if PYTHON3:
1751 if PYTHON3:
1748 v = _bytespath(v)
1752 v = _bytespath(v)
1749 os.system(b"%s %s %s" %
1753 os.system(b"%s %s %s" %
1750 (v, test.refpath, test.errpath))
1754 (v, test.refpath, test.errpath))
1751 else:
1755 else:
1752 servefail, lines = getdiff(expected, got,
1756 servefail, lines = getdiff(expected, got,
1753 test.refpath, test.errpath)
1757 test.refpath, test.errpath)
1754 if servefail:
1758 if servefail:
1755 raise test.failureException(
1759 raise test.failureException(
1756 'server failed to start (HGPORT=%s)' % test._startport)
1760 'server failed to start (HGPORT=%s)' % test._startport)
1757 else:
1761 else:
1758 self.stream.write('\n')
1762 self.stream.write('\n')
1759 for line in lines:
1763 for line in lines:
1760 line = highlightdiff(line, self.color)
1764 line = highlightdiff(line, self.color)
1761 if PYTHON3:
1765 if PYTHON3:
1762 self.stream.flush()
1766 self.stream.flush()
1763 self.stream.buffer.write(line)
1767 self.stream.buffer.write(line)
1764 self.stream.buffer.flush()
1768 self.stream.buffer.flush()
1765 else:
1769 else:
1766 self.stream.write(line)
1770 self.stream.write(line)
1767 self.stream.flush()
1771 self.stream.flush()
1768
1772
1769 # handle interactive prompt without releasing iolock
1773 # handle interactive prompt without releasing iolock
1770 if self._options.interactive:
1774 if self._options.interactive:
1771 if test.readrefout() != expected:
1775 if test.readrefout() != expected:
1772 self.stream.write(
1776 self.stream.write(
1773 'Reference output has changed (run again to prompt '
1777 'Reference output has changed (run again to prompt '
1774 'changes)')
1778 'changes)')
1775 else:
1779 else:
1776 self.stream.write('Accept this change? [n] ')
1780 self.stream.write('Accept this change? [n] ')
1777 answer = sys.stdin.readline().strip()
1781 answer = sys.stdin.readline().strip()
1778 if answer.lower() in ('y', 'yes'):
1782 if answer.lower() in ('y', 'yes'):
1779 if test.path.endswith(b'.t'):
1783 if test.path.endswith(b'.t'):
1780 rename(test.errpath, test.path)
1784 rename(test.errpath, test.path)
1781 else:
1785 else:
1782 rename(test.errpath, '%s.out' % test.path)
1786 rename(test.errpath, '%s.out' % test.path)
1783 accepted = True
1787 accepted = True
1784 if not accepted:
1788 if not accepted:
1785 self.faildata[test.name] = b''.join(lines)
1789 self.faildata[test.name] = b''.join(lines)
1786
1790
1787 return accepted
1791 return accepted
1788
1792
1789 def startTest(self, test):
1793 def startTest(self, test):
1790 super(TestResult, self).startTest(test)
1794 super(TestResult, self).startTest(test)
1791
1795
1792 # os.times module computes the user time and system time spent by
1796 # os.times module computes the user time and system time spent by
1793 # child's processes along with real elapsed time taken by a process.
1797 # child's processes along with real elapsed time taken by a process.
1794 # This module has one limitation. It can only work for Linux user
1798 # This module has one limitation. It can only work for Linux user
1795 # and not for Windows.
1799 # and not for Windows.
1796 test.started = os.times()
1800 test.started = os.times()
1797 if self._firststarttime is None: # thread racy but irrelevant
1801 if self._firststarttime is None: # thread racy but irrelevant
1798 self._firststarttime = test.started[4]
1802 self._firststarttime = test.started[4]
1799
1803
1800 def stopTest(self, test, interrupted=False):
1804 def stopTest(self, test, interrupted=False):
1801 super(TestResult, self).stopTest(test)
1805 super(TestResult, self).stopTest(test)
1802
1806
1803 test.stopped = os.times()
1807 test.stopped = os.times()
1804
1808
1805 starttime = test.started
1809 starttime = test.started
1806 endtime = test.stopped
1810 endtime = test.stopped
1807 origin = self._firststarttime
1811 origin = self._firststarttime
1808 self.times.append((test.name,
1812 self.times.append((test.name,
1809 endtime[2] - starttime[2], # user space CPU time
1813 endtime[2] - starttime[2], # user space CPU time
1810 endtime[3] - starttime[3], # sys space CPU time
1814 endtime[3] - starttime[3], # sys space CPU time
1811 endtime[4] - starttime[4], # real time
1815 endtime[4] - starttime[4], # real time
1812 starttime[4] - origin, # start date in run context
1816 starttime[4] - origin, # start date in run context
1813 endtime[4] - origin, # end date in run context
1817 endtime[4] - origin, # end date in run context
1814 ))
1818 ))
1815
1819
1816 if interrupted:
1820 if interrupted:
1817 with iolock:
1821 with iolock:
1818 self.stream.writeln('INTERRUPTED: %s (after %d seconds)' % (
1822 self.stream.writeln('INTERRUPTED: %s (after %d seconds)' % (
1819 test.name, self.times[-1][3]))
1823 test.name, self.times[-1][3]))
1820
1824
1821 class TestSuite(unittest.TestSuite):
1825 class TestSuite(unittest.TestSuite):
1822 """Custom unittest TestSuite that knows how to execute Mercurial tests."""
1826 """Custom unittest TestSuite that knows how to execute Mercurial tests."""
1823
1827
1824 def __init__(self, testdir, jobs=1, whitelist=None, blacklist=None,
1828 def __init__(self, testdir, jobs=1, whitelist=None, blacklist=None,
1825 retest=False, keywords=None, loop=False, runs_per_test=1,
1829 retest=False, keywords=None, loop=False, runs_per_test=1,
1826 loadtest=None, showchannels=False,
1830 loadtest=None, showchannels=False,
1827 *args, **kwargs):
1831 *args, **kwargs):
1828 """Create a new instance that can run tests with a configuration.
1832 """Create a new instance that can run tests with a configuration.
1829
1833
1830 testdir specifies the directory where tests are executed from. This
1834 testdir specifies the directory where tests are executed from. This
1831 is typically the ``tests`` directory from Mercurial's source
1835 is typically the ``tests`` directory from Mercurial's source
1832 repository.
1836 repository.
1833
1837
1834 jobs specifies the number of jobs to run concurrently. Each test
1838 jobs specifies the number of jobs to run concurrently. Each test
1835 executes on its own thread. Tests actually spawn new processes, so
1839 executes on its own thread. Tests actually spawn new processes, so
1836 state mutation should not be an issue.
1840 state mutation should not be an issue.
1837
1841
1838 If there is only one job, it will use the main thread.
1842 If there is only one job, it will use the main thread.
1839
1843
1840 whitelist and blacklist denote tests that have been whitelisted and
1844 whitelist and blacklist denote tests that have been whitelisted and
1841 blacklisted, respectively. These arguments don't belong in TestSuite.
1845 blacklisted, respectively. These arguments don't belong in TestSuite.
1842 Instead, whitelist and blacklist should be handled by the thing that
1846 Instead, whitelist and blacklist should be handled by the thing that
1843 populates the TestSuite with tests. They are present to preserve
1847 populates the TestSuite with tests. They are present to preserve
1844 backwards compatible behavior which reports skipped tests as part
1848 backwards compatible behavior which reports skipped tests as part
1845 of the results.
1849 of the results.
1846
1850
1847 retest denotes whether to retest failed tests. This arguably belongs
1851 retest denotes whether to retest failed tests. This arguably belongs
1848 outside of TestSuite.
1852 outside of TestSuite.
1849
1853
1850 keywords denotes key words that will be used to filter which tests
1854 keywords denotes key words that will be used to filter which tests
1851 to execute. This arguably belongs outside of TestSuite.
1855 to execute. This arguably belongs outside of TestSuite.
1852
1856
1853 loop denotes whether to loop over tests forever.
1857 loop denotes whether to loop over tests forever.
1854 """
1858 """
1855 super(TestSuite, self).__init__(*args, **kwargs)
1859 super(TestSuite, self).__init__(*args, **kwargs)
1856
1860
1857 self._jobs = jobs
1861 self._jobs = jobs
1858 self._whitelist = whitelist
1862 self._whitelist = whitelist
1859 self._blacklist = blacklist
1863 self._blacklist = blacklist
1860 self._retest = retest
1864 self._retest = retest
1861 self._keywords = keywords
1865 self._keywords = keywords
1862 self._loop = loop
1866 self._loop = loop
1863 self._runs_per_test = runs_per_test
1867 self._runs_per_test = runs_per_test
1864 self._loadtest = loadtest
1868 self._loadtest = loadtest
1865 self._showchannels = showchannels
1869 self._showchannels = showchannels
1866
1870
1867 def run(self, result):
1871 def run(self, result):
1868 # We have a number of filters that need to be applied. We do this
1872 # We have a number of filters that need to be applied. We do this
1869 # here instead of inside Test because it makes the running logic for
1873 # here instead of inside Test because it makes the running logic for
1870 # Test simpler.
1874 # Test simpler.
1871 tests = []
1875 tests = []
1872 num_tests = [0]
1876 num_tests = [0]
1873 for test in self._tests:
1877 for test in self._tests:
1874 def get():
1878 def get():
1875 num_tests[0] += 1
1879 num_tests[0] += 1
1876 if getattr(test, 'should_reload', False):
1880 if getattr(test, 'should_reload', False):
1877 return self._loadtest(test, num_tests[0])
1881 return self._loadtest(test, num_tests[0])
1878 return test
1882 return test
1879 if not os.path.exists(test.path):
1883 if not os.path.exists(test.path):
1880 result.addSkip(test, "Doesn't exist")
1884 result.addSkip(test, "Doesn't exist")
1881 continue
1885 continue
1882
1886
1883 if not (self._whitelist and test.bname in self._whitelist):
1887 if not (self._whitelist and test.bname in self._whitelist):
1884 if self._blacklist and test.bname in self._blacklist:
1888 if self._blacklist and test.bname in self._blacklist:
1885 result.addSkip(test, 'blacklisted')
1889 result.addSkip(test, 'blacklisted')
1886 continue
1890 continue
1887
1891
1888 if self._retest and not os.path.exists(test.errpath):
1892 if self._retest and not os.path.exists(test.errpath):
1889 result.addIgnore(test, 'not retesting')
1893 result.addIgnore(test, 'not retesting')
1890 continue
1894 continue
1891
1895
1892 if self._keywords:
1896 if self._keywords:
1893 with open(test.path, 'rb') as f:
1897 with open(test.path, 'rb') as f:
1894 t = f.read().lower() + test.bname.lower()
1898 t = f.read().lower() + test.bname.lower()
1895 ignored = False
1899 ignored = False
1896 for k in self._keywords.lower().split():
1900 for k in self._keywords.lower().split():
1897 if k not in t:
1901 if k not in t:
1898 result.addIgnore(test, "doesn't match keyword")
1902 result.addIgnore(test, "doesn't match keyword")
1899 ignored = True
1903 ignored = True
1900 break
1904 break
1901
1905
1902 if ignored:
1906 if ignored:
1903 continue
1907 continue
1904 for _ in xrange(self._runs_per_test):
1908 for _ in xrange(self._runs_per_test):
1905 tests.append(get())
1909 tests.append(get())
1906
1910
1907 runtests = list(tests)
1911 runtests = list(tests)
1908 done = queue.Queue()
1912 done = queue.Queue()
1909 running = 0
1913 running = 0
1910
1914
1911 channels = [""] * self._jobs
1915 channels = [""] * self._jobs
1912
1916
1913 def job(test, result):
1917 def job(test, result):
1914 for n, v in enumerate(channels):
1918 for n, v in enumerate(channels):
1915 if not v:
1919 if not v:
1916 channel = n
1920 channel = n
1917 break
1921 break
1918 else:
1922 else:
1919 raise ValueError('Could not find output channel')
1923 raise ValueError('Could not find output channel')
1920 channels[channel] = "=" + test.name[5:].split(".")[0]
1924 channels[channel] = "=" + test.name[5:].split(".")[0]
1921 try:
1925 try:
1922 test(result)
1926 test(result)
1923 done.put(None)
1927 done.put(None)
1924 except KeyboardInterrupt:
1928 except KeyboardInterrupt:
1925 pass
1929 pass
1926 except: # re-raises
1930 except: # re-raises
1927 done.put(('!', test, 'run-test raised an error, see traceback'))
1931 done.put(('!', test, 'run-test raised an error, see traceback'))
1928 raise
1932 raise
1929 finally:
1933 finally:
1930 try:
1934 try:
1931 channels[channel] = ''
1935 channels[channel] = ''
1932 except IndexError:
1936 except IndexError:
1933 pass
1937 pass
1934
1938
1935 def stat():
1939 def stat():
1936 count = 0
1940 count = 0
1937 while channels:
1941 while channels:
1938 d = '\n%03s ' % count
1942 d = '\n%03s ' % count
1939 for n, v in enumerate(channels):
1943 for n, v in enumerate(channels):
1940 if v:
1944 if v:
1941 d += v[0]
1945 d += v[0]
1942 channels[n] = v[1:] or '.'
1946 channels[n] = v[1:] or '.'
1943 else:
1947 else:
1944 d += ' '
1948 d += ' '
1945 d += ' '
1949 d += ' '
1946 with iolock:
1950 with iolock:
1947 sys.stdout.write(d + ' ')
1951 sys.stdout.write(d + ' ')
1948 sys.stdout.flush()
1952 sys.stdout.flush()
1949 for x in xrange(10):
1953 for x in xrange(10):
1950 if channels:
1954 if channels:
1951 time.sleep(.1)
1955 time.sleep(.1)
1952 count += 1
1956 count += 1
1953
1957
1954 stoppedearly = False
1958 stoppedearly = False
1955
1959
1956 if self._showchannels:
1960 if self._showchannels:
1957 statthread = threading.Thread(target=stat, name="stat")
1961 statthread = threading.Thread(target=stat, name="stat")
1958 statthread.start()
1962 statthread.start()
1959
1963
1960 try:
1964 try:
1961 while tests or running:
1965 while tests or running:
1962 if not done.empty() or running == self._jobs or not tests:
1966 if not done.empty() or running == self._jobs or not tests:
1963 try:
1967 try:
1964 done.get(True, 1)
1968 done.get(True, 1)
1965 running -= 1
1969 running -= 1
1966 if result and result.shouldStop:
1970 if result and result.shouldStop:
1967 stoppedearly = True
1971 stoppedearly = True
1968 break
1972 break
1969 except queue.Empty:
1973 except queue.Empty:
1970 continue
1974 continue
1971 if tests and not running == self._jobs:
1975 if tests and not running == self._jobs:
1972 test = tests.pop(0)
1976 test = tests.pop(0)
1973 if self._loop:
1977 if self._loop:
1974 if getattr(test, 'should_reload', False):
1978 if getattr(test, 'should_reload', False):
1975 num_tests[0] += 1
1979 num_tests[0] += 1
1976 tests.append(
1980 tests.append(
1977 self._loadtest(test, num_tests[0]))
1981 self._loadtest(test, num_tests[0]))
1978 else:
1982 else:
1979 tests.append(test)
1983 tests.append(test)
1980 if self._jobs == 1:
1984 if self._jobs == 1:
1981 job(test, result)
1985 job(test, result)
1982 else:
1986 else:
1983 t = threading.Thread(target=job, name=test.name,
1987 t = threading.Thread(target=job, name=test.name,
1984 args=(test, result))
1988 args=(test, result))
1985 t.start()
1989 t.start()
1986 running += 1
1990 running += 1
1987
1991
1988 # If we stop early we still need to wait on started tests to
1992 # If we stop early we still need to wait on started tests to
1989 # finish. Otherwise, there is a race between the test completing
1993 # finish. Otherwise, there is a race between the test completing
1990 # and the test's cleanup code running. This could result in the
1994 # and the test's cleanup code running. This could result in the
1991 # test reporting incorrect.
1995 # test reporting incorrect.
1992 if stoppedearly:
1996 if stoppedearly:
1993 while running:
1997 while running:
1994 try:
1998 try:
1995 done.get(True, 1)
1999 done.get(True, 1)
1996 running -= 1
2000 running -= 1
1997 except queue.Empty:
2001 except queue.Empty:
1998 continue
2002 continue
1999 except KeyboardInterrupt:
2003 except KeyboardInterrupt:
2000 for test in runtests:
2004 for test in runtests:
2001 test.abort()
2005 test.abort()
2002
2006
2003 channels = []
2007 channels = []
2004
2008
2005 return result
2009 return result
2006
2010
2007 # Save the most recent 5 wall-clock runtimes of each test to a
2011 # Save the most recent 5 wall-clock runtimes of each test to a
2008 # human-readable text file named .testtimes. Tests are sorted
2012 # human-readable text file named .testtimes. Tests are sorted
2009 # alphabetically, while times for each test are listed from oldest to
2013 # alphabetically, while times for each test are listed from oldest to
2010 # newest.
2014 # newest.
2011
2015
2012 def loadtimes(outputdir):
2016 def loadtimes(outputdir):
2013 times = []
2017 times = []
2014 try:
2018 try:
2015 with open(os.path.join(outputdir, b'.testtimes-')) as fp:
2019 with open(os.path.join(outputdir, b'.testtimes-')) as fp:
2016 for line in fp:
2020 for line in fp:
2017 ts = line.split()
2021 ts = line.split()
2018 times.append((ts[0], [float(t) for t in ts[1:]]))
2022 times.append((ts[0], [float(t) for t in ts[1:]]))
2019 except IOError as err:
2023 except IOError as err:
2020 if err.errno != errno.ENOENT:
2024 if err.errno != errno.ENOENT:
2021 raise
2025 raise
2022 return times
2026 return times
2023
2027
2024 def savetimes(outputdir, result):
2028 def savetimes(outputdir, result):
2025 saved = dict(loadtimes(outputdir))
2029 saved = dict(loadtimes(outputdir))
2026 maxruns = 5
2030 maxruns = 5
2027 skipped = set([str(t[0]) for t in result.skipped])
2031 skipped = set([str(t[0]) for t in result.skipped])
2028 for tdata in result.times:
2032 for tdata in result.times:
2029 test, real = tdata[0], tdata[3]
2033 test, real = tdata[0], tdata[3]
2030 if test not in skipped:
2034 if test not in skipped:
2031 ts = saved.setdefault(test, [])
2035 ts = saved.setdefault(test, [])
2032 ts.append(real)
2036 ts.append(real)
2033 ts[:] = ts[-maxruns:]
2037 ts[:] = ts[-maxruns:]
2034
2038
2035 fd, tmpname = tempfile.mkstemp(prefix=b'.testtimes',
2039 fd, tmpname = tempfile.mkstemp(prefix=b'.testtimes',
2036 dir=outputdir, text=True)
2040 dir=outputdir, text=True)
2037 with os.fdopen(fd, 'w') as fp:
2041 with os.fdopen(fd, 'w') as fp:
2038 for name, ts in sorted(saved.items()):
2042 for name, ts in sorted(saved.items()):
2039 fp.write('%s %s\n' % (name, ' '.join(['%.3f' % (t,) for t in ts])))
2043 fp.write('%s %s\n' % (name, ' '.join(['%.3f' % (t,) for t in ts])))
2040 timepath = os.path.join(outputdir, b'.testtimes')
2044 timepath = os.path.join(outputdir, b'.testtimes')
2041 try:
2045 try:
2042 os.unlink(timepath)
2046 os.unlink(timepath)
2043 except OSError:
2047 except OSError:
2044 pass
2048 pass
2045 try:
2049 try:
2046 os.rename(tmpname, timepath)
2050 os.rename(tmpname, timepath)
2047 except OSError:
2051 except OSError:
2048 pass
2052 pass
2049
2053
2050 class TextTestRunner(unittest.TextTestRunner):
2054 class TextTestRunner(unittest.TextTestRunner):
2051 """Custom unittest test runner that uses appropriate settings."""
2055 """Custom unittest test runner that uses appropriate settings."""
2052
2056
2053 def __init__(self, runner, *args, **kwargs):
2057 def __init__(self, runner, *args, **kwargs):
2054 super(TextTestRunner, self).__init__(*args, **kwargs)
2058 super(TextTestRunner, self).__init__(*args, **kwargs)
2055
2059
2056 self._runner = runner
2060 self._runner = runner
2057
2061
2058 def listtests(self, test):
2062 def listtests(self, test):
2059 result = TestResult(self._runner.options, self.stream,
2063 result = TestResult(self._runner.options, self.stream,
2060 self.descriptions, 0)
2064 self.descriptions, 0)
2061 test = sorted(test, key=lambda t: t.name)
2065 test = sorted(test, key=lambda t: t.name)
2062 for t in test:
2066 for t in test:
2063 print(t.name)
2067 print(t.name)
2064 result.addSuccess(t)
2068 result.addSuccess(t)
2065
2069
2066 if self._runner.options.xunit:
2070 if self._runner.options.xunit:
2067 with open(self._runner.options.xunit, "wb") as xuf:
2071 with open(self._runner.options.xunit, "wb") as xuf:
2068 self._writexunit(result, xuf)
2072 self._writexunit(result, xuf)
2069
2073
2070 if self._runner.options.json:
2074 if self._runner.options.json:
2071 jsonpath = os.path.join(self._runner._outputdir, b'report.json')
2075 jsonpath = os.path.join(self._runner._outputdir, b'report.json')
2072 with open(jsonpath, 'w') as fp:
2076 with open(jsonpath, 'w') as fp:
2073 self._writejson(result, fp)
2077 self._writejson(result, fp)
2074
2078
2075 return result
2079 return result
2076
2080
2077 def run(self, test):
2081 def run(self, test):
2078 result = TestResult(self._runner.options, self.stream,
2082 result = TestResult(self._runner.options, self.stream,
2079 self.descriptions, self.verbosity)
2083 self.descriptions, self.verbosity)
2080
2084
2081 test(result)
2085 test(result)
2082
2086
2083 failed = len(result.failures)
2087 failed = len(result.failures)
2084 skipped = len(result.skipped)
2088 skipped = len(result.skipped)
2085 ignored = len(result.ignored)
2089 ignored = len(result.ignored)
2086
2090
2087 with iolock:
2091 with iolock:
2088 self.stream.writeln('')
2092 self.stream.writeln('')
2089
2093
2090 if not self._runner.options.noskips:
2094 if not self._runner.options.noskips:
2091 for test, msg in result.skipped:
2095 for test, msg in result.skipped:
2092 formatted = 'Skipped %s: %s\n' % (test.name, msg)
2096 formatted = 'Skipped %s: %s\n' % (test.name, msg)
2093 self.stream.write(highlightmsg(formatted, result.color))
2097 self.stream.write(highlightmsg(formatted, result.color))
2094 for test, msg in result.failures:
2098 for test, msg in result.failures:
2095 formatted = 'Failed %s: %s\n' % (test.name, msg)
2099 formatted = 'Failed %s: %s\n' % (test.name, msg)
2096 self.stream.write(highlightmsg(formatted, result.color))
2100 self.stream.write(highlightmsg(formatted, result.color))
2097 for test, msg in result.errors:
2101 for test, msg in result.errors:
2098 self.stream.writeln('Errored %s: %s' % (test.name, msg))
2102 self.stream.writeln('Errored %s: %s' % (test.name, msg))
2099
2103
2100 if self._runner.options.xunit:
2104 if self._runner.options.xunit:
2101 with open(self._runner.options.xunit, "wb") as xuf:
2105 with open(self._runner.options.xunit, "wb") as xuf:
2102 self._writexunit(result, xuf)
2106 self._writexunit(result, xuf)
2103
2107
2104 if self._runner.options.json:
2108 if self._runner.options.json:
2105 jsonpath = os.path.join(self._runner._outputdir, b'report.json')
2109 jsonpath = os.path.join(self._runner._outputdir, b'report.json')
2106 with open(jsonpath, 'w') as fp:
2110 with open(jsonpath, 'w') as fp:
2107 self._writejson(result, fp)
2111 self._writejson(result, fp)
2108
2112
2109 self._runner._checkhglib('Tested')
2113 self._runner._checkhglib('Tested')
2110
2114
2111 savetimes(self._runner._outputdir, result)
2115 savetimes(self._runner._outputdir, result)
2112
2116
2113 if failed and self._runner.options.known_good_rev:
2117 if failed and self._runner.options.known_good_rev:
2114 self._bisecttests(t for t, m in result.failures)
2118 self._bisecttests(t for t, m in result.failures)
2115 self.stream.writeln(
2119 self.stream.writeln(
2116 '# Ran %d tests, %d skipped, %d failed.'
2120 '# Ran %d tests, %d skipped, %d failed.'
2117 % (result.testsRun, skipped + ignored, failed))
2121 % (result.testsRun, skipped + ignored, failed))
2118 if failed:
2122 if failed:
2119 self.stream.writeln('python hash seed: %s' %
2123 self.stream.writeln('python hash seed: %s' %
2120 os.environ['PYTHONHASHSEED'])
2124 os.environ['PYTHONHASHSEED'])
2121 if self._runner.options.time:
2125 if self._runner.options.time:
2122 self.printtimes(result.times)
2126 self.printtimes(result.times)
2123
2127
2124 if self._runner.options.exceptions:
2128 if self._runner.options.exceptions:
2125 exceptions = aggregateexceptions(
2129 exceptions = aggregateexceptions(
2126 os.path.join(self._runner._outputdir, b'exceptions'))
2130 os.path.join(self._runner._outputdir, b'exceptions'))
2127 total = sum(exceptions.values())
2131 total = sum(exceptions.values())
2128
2132
2129 self.stream.writeln('Exceptions Report:')
2133 self.stream.writeln('Exceptions Report:')
2130 self.stream.writeln('%d total from %d frames' %
2134 self.stream.writeln('%d total from %d frames' %
2131 (total, len(exceptions)))
2135 (total, len(exceptions)))
2132 for (frame, line, exc), count in exceptions.most_common():
2136 for (frame, line, exc), count in exceptions.most_common():
2133 self.stream.writeln('%d\t%s: %s' % (count, frame, exc))
2137 self.stream.writeln('%d\t%s: %s' % (count, frame, exc))
2134
2138
2135 self.stream.flush()
2139 self.stream.flush()
2136
2140
2137 return result
2141 return result
2138
2142
2139 def _bisecttests(self, tests):
2143 def _bisecttests(self, tests):
2140 bisectcmd = ['hg', 'bisect']
2144 bisectcmd = ['hg', 'bisect']
2141 bisectrepo = self._runner.options.bisect_repo
2145 bisectrepo = self._runner.options.bisect_repo
2142 if bisectrepo:
2146 if bisectrepo:
2143 bisectcmd.extend(['-R', os.path.abspath(bisectrepo)])
2147 bisectcmd.extend(['-R', os.path.abspath(bisectrepo)])
2144 def pread(args):
2148 def pread(args):
2145 env = os.environ.copy()
2149 env = os.environ.copy()
2146 env['HGPLAIN'] = '1'
2150 env['HGPLAIN'] = '1'
2147 p = subprocess.Popen(args, stderr=subprocess.STDOUT,
2151 p = subprocess.Popen(args, stderr=subprocess.STDOUT,
2148 stdout=subprocess.PIPE, env=env)
2152 stdout=subprocess.PIPE, env=env)
2149 data = p.stdout.read()
2153 data = p.stdout.read()
2150 p.wait()
2154 p.wait()
2151 return data
2155 return data
2152 for test in tests:
2156 for test in tests:
2153 pread(bisectcmd + ['--reset']),
2157 pread(bisectcmd + ['--reset']),
2154 pread(bisectcmd + ['--bad', '.'])
2158 pread(bisectcmd + ['--bad', '.'])
2155 pread(bisectcmd + ['--good', self._runner.options.known_good_rev])
2159 pread(bisectcmd + ['--good', self._runner.options.known_good_rev])
2156 # TODO: we probably need to forward more options
2160 # TODO: we probably need to forward more options
2157 # that alter hg's behavior inside the tests.
2161 # that alter hg's behavior inside the tests.
2158 opts = ''
2162 opts = ''
2159 withhg = self._runner.options.with_hg
2163 withhg = self._runner.options.with_hg
2160 if withhg:
2164 if withhg:
2161 opts += ' --with-hg=%s ' % shellquote(_strpath(withhg))
2165 opts += ' --with-hg=%s ' % shellquote(_strpath(withhg))
2162 rtc = '%s %s %s %s' % (sys.executable, sys.argv[0], opts,
2166 rtc = '%s %s %s %s' % (sys.executable, sys.argv[0], opts,
2163 test)
2167 test)
2164 data = pread(bisectcmd + ['--command', rtc])
2168 data = pread(bisectcmd + ['--command', rtc])
2165 m = re.search(
2169 m = re.search(
2166 (br'\nThe first (?P<goodbad>bad|good) revision '
2170 (br'\nThe first (?P<goodbad>bad|good) revision '
2167 br'is:\nchangeset: +\d+:(?P<node>[a-f0-9]+)\n.*\n'
2171 br'is:\nchangeset: +\d+:(?P<node>[a-f0-9]+)\n.*\n'
2168 br'summary: +(?P<summary>[^\n]+)\n'),
2172 br'summary: +(?P<summary>[^\n]+)\n'),
2169 data, (re.MULTILINE | re.DOTALL))
2173 data, (re.MULTILINE | re.DOTALL))
2170 if m is None:
2174 if m is None:
2171 self.stream.writeln(
2175 self.stream.writeln(
2172 'Failed to identify failure point for %s' % test)
2176 'Failed to identify failure point for %s' % test)
2173 continue
2177 continue
2174 dat = m.groupdict()
2178 dat = m.groupdict()
2175 verb = 'broken' if dat['goodbad'] == 'bad' else 'fixed'
2179 verb = 'broken' if dat['goodbad'] == 'bad' else 'fixed'
2176 self.stream.writeln(
2180 self.stream.writeln(
2177 '%s %s by %s (%s)' % (
2181 '%s %s by %s (%s)' % (
2178 test, verb, dat['node'], dat['summary']))
2182 test, verb, dat['node'], dat['summary']))
2179
2183
2180 def printtimes(self, times):
2184 def printtimes(self, times):
2181 # iolock held by run
2185 # iolock held by run
2182 self.stream.writeln('# Producing time report')
2186 self.stream.writeln('# Producing time report')
2183 times.sort(key=lambda t: (t[3]))
2187 times.sort(key=lambda t: (t[3]))
2184 cols = '%7.3f %7.3f %7.3f %7.3f %7.3f %s'
2188 cols = '%7.3f %7.3f %7.3f %7.3f %7.3f %s'
2185 self.stream.writeln('%-7s %-7s %-7s %-7s %-7s %s' %
2189 self.stream.writeln('%-7s %-7s %-7s %-7s %-7s %s' %
2186 ('start', 'end', 'cuser', 'csys', 'real', 'Test'))
2190 ('start', 'end', 'cuser', 'csys', 'real', 'Test'))
2187 for tdata in times:
2191 for tdata in times:
2188 test = tdata[0]
2192 test = tdata[0]
2189 cuser, csys, real, start, end = tdata[1:6]
2193 cuser, csys, real, start, end = tdata[1:6]
2190 self.stream.writeln(cols % (start, end, cuser, csys, real, test))
2194 self.stream.writeln(cols % (start, end, cuser, csys, real, test))
2191
2195
2192 @staticmethod
2196 @staticmethod
2193 def _writexunit(result, outf):
2197 def _writexunit(result, outf):
2194 # See http://llg.cubic.org/docs/junit/ for a reference.
2198 # See http://llg.cubic.org/docs/junit/ for a reference.
2195 timesd = dict((t[0], t[3]) for t in result.times)
2199 timesd = dict((t[0], t[3]) for t in result.times)
2196 doc = minidom.Document()
2200 doc = minidom.Document()
2197 s = doc.createElement('testsuite')
2201 s = doc.createElement('testsuite')
2198 s.setAttribute('name', 'run-tests')
2202 s.setAttribute('name', 'run-tests')
2199 s.setAttribute('tests', str(result.testsRun))
2203 s.setAttribute('tests', str(result.testsRun))
2200 s.setAttribute('errors', "0") # TODO
2204 s.setAttribute('errors', "0") # TODO
2201 s.setAttribute('failures', str(len(result.failures)))
2205 s.setAttribute('failures', str(len(result.failures)))
2202 s.setAttribute('skipped', str(len(result.skipped) +
2206 s.setAttribute('skipped', str(len(result.skipped) +
2203 len(result.ignored)))
2207 len(result.ignored)))
2204 doc.appendChild(s)
2208 doc.appendChild(s)
2205 for tc in result.successes:
2209 for tc in result.successes:
2206 t = doc.createElement('testcase')
2210 t = doc.createElement('testcase')
2207 t.setAttribute('name', tc.name)
2211 t.setAttribute('name', tc.name)
2208 tctime = timesd.get(tc.name)
2212 tctime = timesd.get(tc.name)
2209 if tctime is not None:
2213 if tctime is not None:
2210 t.setAttribute('time', '%.3f' % tctime)
2214 t.setAttribute('time', '%.3f' % tctime)
2211 s.appendChild(t)
2215 s.appendChild(t)
2212 for tc, err in sorted(result.faildata.items()):
2216 for tc, err in sorted(result.faildata.items()):
2213 t = doc.createElement('testcase')
2217 t = doc.createElement('testcase')
2214 t.setAttribute('name', tc)
2218 t.setAttribute('name', tc)
2215 tctime = timesd.get(tc)
2219 tctime = timesd.get(tc)
2216 if tctime is not None:
2220 if tctime is not None:
2217 t.setAttribute('time', '%.3f' % tctime)
2221 t.setAttribute('time', '%.3f' % tctime)
2218 # createCDATASection expects a unicode or it will
2222 # createCDATASection expects a unicode or it will
2219 # convert using default conversion rules, which will
2223 # convert using default conversion rules, which will
2220 # fail if string isn't ASCII.
2224 # fail if string isn't ASCII.
2221 err = cdatasafe(err).decode('utf-8', 'replace')
2225 err = cdatasafe(err).decode('utf-8', 'replace')
2222 cd = doc.createCDATASection(err)
2226 cd = doc.createCDATASection(err)
2223 # Use 'failure' here instead of 'error' to match errors = 0,
2227 # Use 'failure' here instead of 'error' to match errors = 0,
2224 # failures = len(result.failures) in the testsuite element.
2228 # failures = len(result.failures) in the testsuite element.
2225 failelem = doc.createElement('failure')
2229 failelem = doc.createElement('failure')
2226 failelem.setAttribute('message', 'output changed')
2230 failelem.setAttribute('message', 'output changed')
2227 failelem.setAttribute('type', 'output-mismatch')
2231 failelem.setAttribute('type', 'output-mismatch')
2228 failelem.appendChild(cd)
2232 failelem.appendChild(cd)
2229 t.appendChild(failelem)
2233 t.appendChild(failelem)
2230 s.appendChild(t)
2234 s.appendChild(t)
2231 for tc, message in result.skipped:
2235 for tc, message in result.skipped:
2232 # According to the schema, 'skipped' has no attributes. So store
2236 # According to the schema, 'skipped' has no attributes. So store
2233 # the skip message as a text node instead.
2237 # the skip message as a text node instead.
2234 t = doc.createElement('testcase')
2238 t = doc.createElement('testcase')
2235 t.setAttribute('name', tc.name)
2239 t.setAttribute('name', tc.name)
2236 binmessage = message.encode('utf-8')
2240 binmessage = message.encode('utf-8')
2237 message = cdatasafe(binmessage).decode('utf-8', 'replace')
2241 message = cdatasafe(binmessage).decode('utf-8', 'replace')
2238 cd = doc.createCDATASection(message)
2242 cd = doc.createCDATASection(message)
2239 skipelem = doc.createElement('skipped')
2243 skipelem = doc.createElement('skipped')
2240 skipelem.appendChild(cd)
2244 skipelem.appendChild(cd)
2241 t.appendChild(skipelem)
2245 t.appendChild(skipelem)
2242 s.appendChild(t)
2246 s.appendChild(t)
2243 outf.write(doc.toprettyxml(indent=' ', encoding='utf-8'))
2247 outf.write(doc.toprettyxml(indent=' ', encoding='utf-8'))
2244
2248
2245 @staticmethod
2249 @staticmethod
2246 def _writejson(result, outf):
2250 def _writejson(result, outf):
2247 timesd = {}
2251 timesd = {}
2248 for tdata in result.times:
2252 for tdata in result.times:
2249 test = tdata[0]
2253 test = tdata[0]
2250 timesd[test] = tdata[1:]
2254 timesd[test] = tdata[1:]
2251
2255
2252 outcome = {}
2256 outcome = {}
2253 groups = [('success', ((tc, None)
2257 groups = [('success', ((tc, None)
2254 for tc in result.successes)),
2258 for tc in result.successes)),
2255 ('failure', result.failures),
2259 ('failure', result.failures),
2256 ('skip', result.skipped)]
2260 ('skip', result.skipped)]
2257 for res, testcases in groups:
2261 for res, testcases in groups:
2258 for tc, __ in testcases:
2262 for tc, __ in testcases:
2259 if tc.name in timesd:
2263 if tc.name in timesd:
2260 diff = result.faildata.get(tc.name, b'')
2264 diff = result.faildata.get(tc.name, b'')
2261 try:
2265 try:
2262 diff = diff.decode('unicode_escape')
2266 diff = diff.decode('unicode_escape')
2263 except UnicodeDecodeError as e:
2267 except UnicodeDecodeError as e:
2264 diff = '%r decoding diff, sorry' % e
2268 diff = '%r decoding diff, sorry' % e
2265 tres = {'result': res,
2269 tres = {'result': res,
2266 'time': ('%0.3f' % timesd[tc.name][2]),
2270 'time': ('%0.3f' % timesd[tc.name][2]),
2267 'cuser': ('%0.3f' % timesd[tc.name][0]),
2271 'cuser': ('%0.3f' % timesd[tc.name][0]),
2268 'csys': ('%0.3f' % timesd[tc.name][1]),
2272 'csys': ('%0.3f' % timesd[tc.name][1]),
2269 'start': ('%0.3f' % timesd[tc.name][3]),
2273 'start': ('%0.3f' % timesd[tc.name][3]),
2270 'end': ('%0.3f' % timesd[tc.name][4]),
2274 'end': ('%0.3f' % timesd[tc.name][4]),
2271 'diff': diff,
2275 'diff': diff,
2272 }
2276 }
2273 else:
2277 else:
2274 # blacklisted test
2278 # blacklisted test
2275 tres = {'result': res}
2279 tres = {'result': res}
2276
2280
2277 outcome[tc.name] = tres
2281 outcome[tc.name] = tres
2278 jsonout = json.dumps(outcome, sort_keys=True, indent=4,
2282 jsonout = json.dumps(outcome, sort_keys=True, indent=4,
2279 separators=(',', ': '))
2283 separators=(',', ': '))
2280 outf.writelines(("testreport =", jsonout))
2284 outf.writelines(("testreport =", jsonout))
2281
2285
2282 def sorttests(testdescs, shuffle=False):
2286 def sorttests(testdescs, shuffle=False):
2283 """Do an in-place sort of tests."""
2287 """Do an in-place sort of tests."""
2284 if shuffle:
2288 if shuffle:
2285 random.shuffle(testdescs)
2289 random.shuffle(testdescs)
2286 return
2290 return
2287
2291
2288 # keywords for slow tests
2292 # keywords for slow tests
2289 slow = {b'svn': 10,
2293 slow = {b'svn': 10,
2290 b'cvs': 10,
2294 b'cvs': 10,
2291 b'hghave': 10,
2295 b'hghave': 10,
2292 b'largefiles-update': 10,
2296 b'largefiles-update': 10,
2293 b'run-tests': 10,
2297 b'run-tests': 10,
2294 b'corruption': 10,
2298 b'corruption': 10,
2295 b'race': 10,
2299 b'race': 10,
2296 b'i18n': 10,
2300 b'i18n': 10,
2297 b'check': 100,
2301 b'check': 100,
2298 b'gendoc': 100,
2302 b'gendoc': 100,
2299 b'contrib-perf': 200,
2303 b'contrib-perf': 200,
2300 }
2304 }
2301 perf = {}
2305 perf = {}
2302
2306
2303 def sortkey(f):
2307 def sortkey(f):
2304 # run largest tests first, as they tend to take the longest
2308 # run largest tests first, as they tend to take the longest
2305 f = f['path']
2309 f = f['path']
2306 try:
2310 try:
2307 return perf[f]
2311 return perf[f]
2308 except KeyError:
2312 except KeyError:
2309 try:
2313 try:
2310 val = -os.stat(f).st_size
2314 val = -os.stat(f).st_size
2311 except OSError as e:
2315 except OSError as e:
2312 if e.errno != errno.ENOENT:
2316 if e.errno != errno.ENOENT:
2313 raise
2317 raise
2314 perf[f] = -1e9 # file does not exist, tell early
2318 perf[f] = -1e9 # file does not exist, tell early
2315 return -1e9
2319 return -1e9
2316 for kw, mul in slow.items():
2320 for kw, mul in slow.items():
2317 if kw in f:
2321 if kw in f:
2318 val *= mul
2322 val *= mul
2319 if f.endswith(b'.py'):
2323 if f.endswith(b'.py'):
2320 val /= 10.0
2324 val /= 10.0
2321 perf[f] = val / 1000.0
2325 perf[f] = val / 1000.0
2322 return perf[f]
2326 return perf[f]
2323
2327
2324 testdescs.sort(key=sortkey)
2328 testdescs.sort(key=sortkey)
2325
2329
2326 class TestRunner(object):
2330 class TestRunner(object):
2327 """Holds context for executing tests.
2331 """Holds context for executing tests.
2328
2332
2329 Tests rely on a lot of state. This object holds it for them.
2333 Tests rely on a lot of state. This object holds it for them.
2330 """
2334 """
2331
2335
2332 # Programs required to run tests.
2336 # Programs required to run tests.
2333 REQUIREDTOOLS = [
2337 REQUIREDTOOLS = [
2334 b'diff',
2338 b'diff',
2335 b'grep',
2339 b'grep',
2336 b'unzip',
2340 b'unzip',
2337 b'gunzip',
2341 b'gunzip',
2338 b'bunzip2',
2342 b'bunzip2',
2339 b'sed',
2343 b'sed',
2340 ]
2344 ]
2341
2345
2342 # Maps file extensions to test class.
2346 # Maps file extensions to test class.
2343 TESTTYPES = [
2347 TESTTYPES = [
2344 (b'.py', PythonTest),
2348 (b'.py', PythonTest),
2345 (b'.t', TTest),
2349 (b'.t', TTest),
2346 ]
2350 ]
2347
2351
2348 def __init__(self):
2352 def __init__(self):
2349 self.options = None
2353 self.options = None
2350 self._hgroot = None
2354 self._hgroot = None
2351 self._testdir = None
2355 self._testdir = None
2352 self._outputdir = None
2356 self._outputdir = None
2353 self._hgtmp = None
2357 self._hgtmp = None
2354 self._installdir = None
2358 self._installdir = None
2355 self._bindir = None
2359 self._bindir = None
2356 self._tmpbinddir = None
2360 self._tmpbinddir = None
2357 self._pythondir = None
2361 self._pythondir = None
2358 self._coveragefile = None
2362 self._coveragefile = None
2359 self._createdfiles = []
2363 self._createdfiles = []
2360 self._hgcommand = None
2364 self._hgcommand = None
2361 self._hgpath = None
2365 self._hgpath = None
2362 self._portoffset = 0
2366 self._portoffset = 0
2363 self._ports = {}
2367 self._ports = {}
2364
2368
2365 def run(self, args, parser=None):
2369 def run(self, args, parser=None):
2366 """Run the test suite."""
2370 """Run the test suite."""
2367 oldmask = os.umask(0o22)
2371 oldmask = os.umask(0o22)
2368 try:
2372 try:
2369 parser = parser or getparser()
2373 parser = parser or getparser()
2370 options = parseargs(args, parser)
2374 options = parseargs(args, parser)
2371 tests = [_bytespath(a) for a in options.tests]
2375 tests = [_bytespath(a) for a in options.tests]
2372 if options.test_list is not None:
2376 if options.test_list is not None:
2373 for listfile in options.test_list:
2377 for listfile in options.test_list:
2374 with open(listfile, 'rb') as f:
2378 with open(listfile, 'rb') as f:
2375 tests.extend(t for t in f.read().splitlines() if t)
2379 tests.extend(t for t in f.read().splitlines() if t)
2376 self.options = options
2380 self.options = options
2377
2381
2378 self._checktools()
2382 self._checktools()
2379 testdescs = self.findtests(tests)
2383 testdescs = self.findtests(tests)
2380 if options.profile_runner:
2384 if options.profile_runner:
2381 import statprof
2385 import statprof
2382 statprof.start()
2386 statprof.start()
2383 result = self._run(testdescs)
2387 result = self._run(testdescs)
2384 if options.profile_runner:
2388 if options.profile_runner:
2385 statprof.stop()
2389 statprof.stop()
2386 statprof.display()
2390 statprof.display()
2387 return result
2391 return result
2388
2392
2389 finally:
2393 finally:
2390 os.umask(oldmask)
2394 os.umask(oldmask)
2391
2395
2392 def _run(self, testdescs):
2396 def _run(self, testdescs):
2393 sorttests(testdescs, shuffle=self.options.random)
2397 sorttests(testdescs, shuffle=self.options.random)
2394
2398
2395 self._testdir = osenvironb[b'TESTDIR'] = getattr(
2399 self._testdir = osenvironb[b'TESTDIR'] = getattr(
2396 os, 'getcwdb', os.getcwd)()
2400 os, 'getcwdb', os.getcwd)()
2397 # assume all tests in same folder for now
2401 # assume all tests in same folder for now
2398 if testdescs:
2402 if testdescs:
2399 pathname = os.path.dirname(testdescs[0]['path'])
2403 pathname = os.path.dirname(testdescs[0]['path'])
2400 if pathname:
2404 if pathname:
2401 osenvironb[b'TESTDIR'] = os.path.join(osenvironb[b'TESTDIR'],
2405 osenvironb[b'TESTDIR'] = os.path.join(osenvironb[b'TESTDIR'],
2402 pathname)
2406 pathname)
2403 if self.options.outputdir:
2407 if self.options.outputdir:
2404 self._outputdir = canonpath(_bytespath(self.options.outputdir))
2408 self._outputdir = canonpath(_bytespath(self.options.outputdir))
2405 else:
2409 else:
2406 self._outputdir = self._testdir
2410 self._outputdir = self._testdir
2407 if testdescs and pathname:
2411 if testdescs and pathname:
2408 self._outputdir = os.path.join(self._outputdir, pathname)
2412 self._outputdir = os.path.join(self._outputdir, pathname)
2409
2413
2410 if 'PYTHONHASHSEED' not in os.environ:
2414 if 'PYTHONHASHSEED' not in os.environ:
2411 # use a random python hash seed all the time
2415 # use a random python hash seed all the time
2412 # we do the randomness ourself to know what seed is used
2416 # we do the randomness ourself to know what seed is used
2413 os.environ['PYTHONHASHSEED'] = str(random.getrandbits(32))
2417 os.environ['PYTHONHASHSEED'] = str(random.getrandbits(32))
2414
2418
2415 if self.options.tmpdir:
2419 if self.options.tmpdir:
2416 self.options.keep_tmpdir = True
2420 self.options.keep_tmpdir = True
2417 tmpdir = _bytespath(self.options.tmpdir)
2421 tmpdir = _bytespath(self.options.tmpdir)
2418 if os.path.exists(tmpdir):
2422 if os.path.exists(tmpdir):
2419 # Meaning of tmpdir has changed since 1.3: we used to create
2423 # Meaning of tmpdir has changed since 1.3: we used to create
2420 # HGTMP inside tmpdir; now HGTMP is tmpdir. So fail if
2424 # HGTMP inside tmpdir; now HGTMP is tmpdir. So fail if
2421 # tmpdir already exists.
2425 # tmpdir already exists.
2422 print("error: temp dir %r already exists" % tmpdir)
2426 print("error: temp dir %r already exists" % tmpdir)
2423 return 1
2427 return 1
2424
2428
2425 os.makedirs(tmpdir)
2429 os.makedirs(tmpdir)
2426 else:
2430 else:
2427 d = None
2431 d = None
2428 if os.name == 'nt':
2432 if os.name == 'nt':
2429 # without this, we get the default temp dir location, but
2433 # without this, we get the default temp dir location, but
2430 # in all lowercase, which causes troubles with paths (issue3490)
2434 # in all lowercase, which causes troubles with paths (issue3490)
2431 d = osenvironb.get(b'TMP', None)
2435 d = osenvironb.get(b'TMP', None)
2432 tmpdir = tempfile.mkdtemp(b'', b'hgtests.', d)
2436 tmpdir = tempfile.mkdtemp(b'', b'hgtests.', d)
2433
2437
2434 self._hgtmp = osenvironb[b'HGTMP'] = (
2438 self._hgtmp = osenvironb[b'HGTMP'] = (
2435 os.path.realpath(tmpdir))
2439 os.path.realpath(tmpdir))
2436
2440
2437 if self.options.with_hg:
2441 if self.options.with_hg:
2438 self._installdir = None
2442 self._installdir = None
2439 whg = self.options.with_hg
2443 whg = self.options.with_hg
2440 self._bindir = os.path.dirname(os.path.realpath(whg))
2444 self._bindir = os.path.dirname(os.path.realpath(whg))
2441 assert isinstance(self._bindir, bytes)
2445 assert isinstance(self._bindir, bytes)
2442 self._hgcommand = os.path.basename(whg)
2446 self._hgcommand = os.path.basename(whg)
2443 self._tmpbindir = os.path.join(self._hgtmp, b'install', b'bin')
2447 self._tmpbindir = os.path.join(self._hgtmp, b'install', b'bin')
2444 os.makedirs(self._tmpbindir)
2448 os.makedirs(self._tmpbindir)
2445
2449
2446 normbin = os.path.normpath(os.path.abspath(whg))
2450 normbin = os.path.normpath(os.path.abspath(whg))
2447 normbin = normbin.replace(os.sep.encode('ascii'), b'/')
2451 normbin = normbin.replace(os.sep.encode('ascii'), b'/')
2448
2452
2449 # Other Python scripts in the test harness need to
2453 # Other Python scripts in the test harness need to
2450 # `import mercurial`. If `hg` is a Python script, we assume
2454 # `import mercurial`. If `hg` is a Python script, we assume
2451 # the Mercurial modules are relative to its path and tell the tests
2455 # the Mercurial modules are relative to its path and tell the tests
2452 # to load Python modules from its directory.
2456 # to load Python modules from its directory.
2453 with open(whg, 'rb') as fh:
2457 with open(whg, 'rb') as fh:
2454 initial = fh.read(1024)
2458 initial = fh.read(1024)
2455
2459
2456 if re.match(b'#!.*python', initial):
2460 if re.match(b'#!.*python', initial):
2457 self._pythondir = self._bindir
2461 self._pythondir = self._bindir
2458 # If it looks like our in-repo Rust binary, use the source root.
2462 # If it looks like our in-repo Rust binary, use the source root.
2459 # This is a bit hacky. But rhg is still not supported outside the
2463 # This is a bit hacky. But rhg is still not supported outside the
2460 # source directory. So until it is, do the simple thing.
2464 # source directory. So until it is, do the simple thing.
2461 elif re.search(b'/rust/target/[^/]+/hg', normbin):
2465 elif re.search(b'/rust/target/[^/]+/hg', normbin):
2462 self._pythondir = os.path.dirname(self._testdir)
2466 self._pythondir = os.path.dirname(self._testdir)
2463 # Fall back to the legacy behavior.
2467 # Fall back to the legacy behavior.
2464 else:
2468 else:
2465 self._pythondir = self._bindir
2469 self._pythondir = self._bindir
2466
2470
2467 else:
2471 else:
2468 self._installdir = os.path.join(self._hgtmp, b"install")
2472 self._installdir = os.path.join(self._hgtmp, b"install")
2469 self._bindir = os.path.join(self._installdir, b"bin")
2473 self._bindir = os.path.join(self._installdir, b"bin")
2470 self._hgcommand = b'hg'
2474 self._hgcommand = b'hg'
2471 self._tmpbindir = self._bindir
2475 self._tmpbindir = self._bindir
2472 self._pythondir = os.path.join(self._installdir, b"lib", b"python")
2476 self._pythondir = os.path.join(self._installdir, b"lib", b"python")
2473
2477
2474 # set CHGHG, then replace "hg" command by "chg"
2478 # set CHGHG, then replace "hg" command by "chg"
2475 chgbindir = self._bindir
2479 chgbindir = self._bindir
2476 if self.options.chg or self.options.with_chg:
2480 if self.options.chg or self.options.with_chg:
2477 osenvironb[b'CHGHG'] = os.path.join(self._bindir, self._hgcommand)
2481 osenvironb[b'CHGHG'] = os.path.join(self._bindir, self._hgcommand)
2478 else:
2482 else:
2479 osenvironb.pop(b'CHGHG', None) # drop flag for hghave
2483 osenvironb.pop(b'CHGHG', None) # drop flag for hghave
2480 if self.options.chg:
2484 if self.options.chg:
2481 self._hgcommand = b'chg'
2485 self._hgcommand = b'chg'
2482 elif self.options.with_chg:
2486 elif self.options.with_chg:
2483 chgbindir = os.path.dirname(os.path.realpath(self.options.with_chg))
2487 chgbindir = os.path.dirname(os.path.realpath(self.options.with_chg))
2484 self._hgcommand = os.path.basename(self.options.with_chg)
2488 self._hgcommand = os.path.basename(self.options.with_chg)
2485
2489
2486 osenvironb[b"BINDIR"] = self._bindir
2490 osenvironb[b"BINDIR"] = self._bindir
2487 osenvironb[b"PYTHON"] = PYTHON
2491 osenvironb[b"PYTHON"] = PYTHON
2488
2492
2489 if self.options.with_python3:
2493 if self.options.with_python3:
2490 osenvironb[b'PYTHON3'] = self.options.with_python3
2494 osenvironb[b'PYTHON3'] = self.options.with_python3
2491
2495
2492 fileb = _bytespath(__file__)
2496 fileb = _bytespath(__file__)
2493 runtestdir = os.path.abspath(os.path.dirname(fileb))
2497 runtestdir = os.path.abspath(os.path.dirname(fileb))
2494 osenvironb[b'RUNTESTDIR'] = runtestdir
2498 osenvironb[b'RUNTESTDIR'] = runtestdir
2495 if PYTHON3:
2499 if PYTHON3:
2496 sepb = _bytespath(os.pathsep)
2500 sepb = _bytespath(os.pathsep)
2497 else:
2501 else:
2498 sepb = os.pathsep
2502 sepb = os.pathsep
2499 path = [self._bindir, runtestdir] + osenvironb[b"PATH"].split(sepb)
2503 path = [self._bindir, runtestdir] + osenvironb[b"PATH"].split(sepb)
2500 if os.path.islink(__file__):
2504 if os.path.islink(__file__):
2501 # test helper will likely be at the end of the symlink
2505 # test helper will likely be at the end of the symlink
2502 realfile = os.path.realpath(fileb)
2506 realfile = os.path.realpath(fileb)
2503 realdir = os.path.abspath(os.path.dirname(realfile))
2507 realdir = os.path.abspath(os.path.dirname(realfile))
2504 path.insert(2, realdir)
2508 path.insert(2, realdir)
2505 if chgbindir != self._bindir:
2509 if chgbindir != self._bindir:
2506 path.insert(1, chgbindir)
2510 path.insert(1, chgbindir)
2507 if self._testdir != runtestdir:
2511 if self._testdir != runtestdir:
2508 path = [self._testdir] + path
2512 path = [self._testdir] + path
2509 if self._tmpbindir != self._bindir:
2513 if self._tmpbindir != self._bindir:
2510 path = [self._tmpbindir] + path
2514 path = [self._tmpbindir] + path
2511 osenvironb[b"PATH"] = sepb.join(path)
2515 osenvironb[b"PATH"] = sepb.join(path)
2512
2516
2513 # Include TESTDIR in PYTHONPATH so that out-of-tree extensions
2517 # Include TESTDIR in PYTHONPATH so that out-of-tree extensions
2514 # can run .../tests/run-tests.py test-foo where test-foo
2518 # can run .../tests/run-tests.py test-foo where test-foo
2515 # adds an extension to HGRC. Also include run-test.py directory to
2519 # adds an extension to HGRC. Also include run-test.py directory to
2516 # import modules like heredoctest.
2520 # import modules like heredoctest.
2517 pypath = [self._pythondir, self._testdir, runtestdir]
2521 pypath = [self._pythondir, self._testdir, runtestdir]
2518 # We have to augment PYTHONPATH, rather than simply replacing
2522 # We have to augment PYTHONPATH, rather than simply replacing
2519 # it, in case external libraries are only available via current
2523 # it, in case external libraries are only available via current
2520 # PYTHONPATH. (In particular, the Subversion bindings on OS X
2524 # PYTHONPATH. (In particular, the Subversion bindings on OS X
2521 # are in /opt/subversion.)
2525 # are in /opt/subversion.)
2522 oldpypath = osenvironb.get(IMPL_PATH)
2526 oldpypath = osenvironb.get(IMPL_PATH)
2523 if oldpypath:
2527 if oldpypath:
2524 pypath.append(oldpypath)
2528 pypath.append(oldpypath)
2525 osenvironb[IMPL_PATH] = sepb.join(pypath)
2529 osenvironb[IMPL_PATH] = sepb.join(pypath)
2526
2530
2527 if self.options.pure:
2531 if self.options.pure:
2528 os.environ["HGTEST_RUN_TESTS_PURE"] = "--pure"
2532 os.environ["HGTEST_RUN_TESTS_PURE"] = "--pure"
2529 os.environ["HGMODULEPOLICY"] = "py"
2533 os.environ["HGMODULEPOLICY"] = "py"
2530
2534
2531 if self.options.allow_slow_tests:
2535 if self.options.allow_slow_tests:
2532 os.environ["HGTEST_SLOW"] = "slow"
2536 os.environ["HGTEST_SLOW"] = "slow"
2533 elif 'HGTEST_SLOW' in os.environ:
2537 elif 'HGTEST_SLOW' in os.environ:
2534 del os.environ['HGTEST_SLOW']
2538 del os.environ['HGTEST_SLOW']
2535
2539
2536 self._coveragefile = os.path.join(self._testdir, b'.coverage')
2540 self._coveragefile = os.path.join(self._testdir, b'.coverage')
2537
2541
2538 if self.options.exceptions:
2542 if self.options.exceptions:
2539 exceptionsdir = os.path.join(self._outputdir, b'exceptions')
2543 exceptionsdir = os.path.join(self._outputdir, b'exceptions')
2540 try:
2544 try:
2541 os.makedirs(exceptionsdir)
2545 os.makedirs(exceptionsdir)
2542 except OSError as e:
2546 except OSError as e:
2543 if e.errno != errno.EEXIST:
2547 if e.errno != errno.EEXIST:
2544 raise
2548 raise
2545
2549
2546 # Remove all existing exception reports.
2550 # Remove all existing exception reports.
2547 for f in os.listdir(exceptionsdir):
2551 for f in os.listdir(exceptionsdir):
2548 os.unlink(os.path.join(exceptionsdir, f))
2552 os.unlink(os.path.join(exceptionsdir, f))
2549
2553
2550 osenvironb[b'HGEXCEPTIONSDIR'] = exceptionsdir
2554 osenvironb[b'HGEXCEPTIONSDIR'] = exceptionsdir
2551 logexceptions = os.path.join(self._testdir, b'logexceptions.py')
2555 logexceptions = os.path.join(self._testdir, b'logexceptions.py')
2552 self.options.extra_config_opt.append(
2556 self.options.extra_config_opt.append(
2553 'extensions.logexceptions=%s' % logexceptions.decode('utf-8'))
2557 'extensions.logexceptions=%s' % logexceptions.decode('utf-8'))
2554
2558
2555 vlog("# Using TESTDIR", self._testdir)
2559 vlog("# Using TESTDIR", self._testdir)
2556 vlog("# Using RUNTESTDIR", osenvironb[b'RUNTESTDIR'])
2560 vlog("# Using RUNTESTDIR", osenvironb[b'RUNTESTDIR'])
2557 vlog("# Using HGTMP", self._hgtmp)
2561 vlog("# Using HGTMP", self._hgtmp)
2558 vlog("# Using PATH", os.environ["PATH"])
2562 vlog("# Using PATH", os.environ["PATH"])
2559 vlog("# Using", IMPL_PATH, osenvironb[IMPL_PATH])
2563 vlog("# Using", IMPL_PATH, osenvironb[IMPL_PATH])
2560 vlog("# Writing to directory", self._outputdir)
2564 vlog("# Writing to directory", self._outputdir)
2561
2565
2562 try:
2566 try:
2563 return self._runtests(testdescs) or 0
2567 return self._runtests(testdescs) or 0
2564 finally:
2568 finally:
2565 time.sleep(.1)
2569 time.sleep(.1)
2566 self._cleanup()
2570 self._cleanup()
2567
2571
2568 def findtests(self, args):
2572 def findtests(self, args):
2569 """Finds possible test files from arguments.
2573 """Finds possible test files from arguments.
2570
2574
2571 If you wish to inject custom tests into the test harness, this would
2575 If you wish to inject custom tests into the test harness, this would
2572 be a good function to monkeypatch or override in a derived class.
2576 be a good function to monkeypatch or override in a derived class.
2573 """
2577 """
2574 if not args:
2578 if not args:
2575 if self.options.changed:
2579 if self.options.changed:
2576 proc = Popen4('hg st --rev "%s" -man0 .' %
2580 proc = Popen4('hg st --rev "%s" -man0 .' %
2577 self.options.changed, None, 0)
2581 self.options.changed, None, 0)
2578 stdout, stderr = proc.communicate()
2582 stdout, stderr = proc.communicate()
2579 args = stdout.strip(b'\0').split(b'\0')
2583 args = stdout.strip(b'\0').split(b'\0')
2580 else:
2584 else:
2581 args = os.listdir(b'.')
2585 args = os.listdir(b'.')
2582
2586
2583 expanded_args = []
2587 expanded_args = []
2584 for arg in args:
2588 for arg in args:
2585 if os.path.isdir(arg):
2589 if os.path.isdir(arg):
2586 if not arg.endswith(b'/'):
2590 if not arg.endswith(b'/'):
2587 arg += b'/'
2591 arg += b'/'
2588 expanded_args.extend([arg + a for a in os.listdir(arg)])
2592 expanded_args.extend([arg + a for a in os.listdir(arg)])
2589 else:
2593 else:
2590 expanded_args.append(arg)
2594 expanded_args.append(arg)
2591 args = expanded_args
2595 args = expanded_args
2592
2596
2593 tests = []
2597 tests = []
2594 for t in args:
2598 for t in args:
2595 if not (os.path.basename(t).startswith(b'test-')
2599 if not (os.path.basename(t).startswith(b'test-')
2596 and (t.endswith(b'.py') or t.endswith(b'.t'))):
2600 and (t.endswith(b'.py') or t.endswith(b'.t'))):
2597 continue
2601 continue
2598 if t.endswith(b'.t'):
2602 if t.endswith(b'.t'):
2599 # .t file may contain multiple test cases
2603 # .t file may contain multiple test cases
2600 cases = sorted(parsettestcases(t))
2604 cases = sorted(parsettestcases(t))
2601 if cases:
2605 if cases:
2602 tests += [{'path': t, 'case': c} for c in sorted(cases)]
2606 tests += [{'path': t, 'case': c} for c in sorted(cases)]
2603 else:
2607 else:
2604 tests.append({'path': t})
2608 tests.append({'path': t})
2605 else:
2609 else:
2606 tests.append({'path': t})
2610 tests.append({'path': t})
2607 return tests
2611 return tests
2608
2612
2609 def _runtests(self, testdescs):
2613 def _runtests(self, testdescs):
2610 def _reloadtest(test, i):
2614 def _reloadtest(test, i):
2611 # convert a test back to its description dict
2615 # convert a test back to its description dict
2612 desc = {'path': test.path}
2616 desc = {'path': test.path}
2613 case = getattr(test, '_case', None)
2617 case = getattr(test, '_case', None)
2614 if case:
2618 if case:
2615 desc['case'] = case
2619 desc['case'] = case
2616 return self._gettest(desc, i)
2620 return self._gettest(desc, i)
2617
2621
2618 try:
2622 try:
2619 if self.options.restart:
2623 if self.options.restart:
2620 orig = list(testdescs)
2624 orig = list(testdescs)
2621 while testdescs:
2625 while testdescs:
2622 desc = testdescs[0]
2626 desc = testdescs[0]
2623 # desc['path'] is a relative path
2627 # desc['path'] is a relative path
2624 if 'case' in desc:
2628 if 'case' in desc:
2625 errpath = b'%s.%s.err' % (desc['path'], desc['case'])
2629 errpath = b'%s.%s.err' % (desc['path'], desc['case'])
2626 else:
2630 else:
2627 errpath = b'%s.err' % desc['path']
2631 errpath = b'%s.err' % desc['path']
2628 errpath = os.path.join(self._outputdir, errpath)
2632 errpath = os.path.join(self._outputdir, errpath)
2629 if os.path.exists(errpath):
2633 if os.path.exists(errpath):
2630 break
2634 break
2631 testdescs.pop(0)
2635 testdescs.pop(0)
2632 if not testdescs:
2636 if not testdescs:
2633 print("running all tests")
2637 print("running all tests")
2634 testdescs = orig
2638 testdescs = orig
2635
2639
2636 tests = [self._gettest(d, i) for i, d in enumerate(testdescs)]
2640 tests = [self._gettest(d, i) for i, d in enumerate(testdescs)]
2637
2641
2638 failed = False
2642 failed = False
2639 kws = self.options.keywords
2643 kws = self.options.keywords
2640 if kws is not None and PYTHON3:
2644 if kws is not None and PYTHON3:
2641 kws = kws.encode('utf-8')
2645 kws = kws.encode('utf-8')
2642
2646
2643 suite = TestSuite(self._testdir,
2647 suite = TestSuite(self._testdir,
2644 jobs=self.options.jobs,
2648 jobs=self.options.jobs,
2645 whitelist=self.options.whitelisted,
2649 whitelist=self.options.whitelisted,
2646 blacklist=self.options.blacklist,
2650 blacklist=self.options.blacklist,
2647 retest=self.options.retest,
2651 retest=self.options.retest,
2648 keywords=kws,
2652 keywords=kws,
2649 loop=self.options.loop,
2653 loop=self.options.loop,
2650 runs_per_test=self.options.runs_per_test,
2654 runs_per_test=self.options.runs_per_test,
2651 showchannels=self.options.showchannels,
2655 showchannels=self.options.showchannels,
2652 tests=tests, loadtest=_reloadtest)
2656 tests=tests, loadtest=_reloadtest)
2653 verbosity = 1
2657 verbosity = 1
2654 if self.options.verbose:
2658 if self.options.verbose:
2655 verbosity = 2
2659 verbosity = 2
2656 runner = TextTestRunner(self, verbosity=verbosity)
2660 runner = TextTestRunner(self, verbosity=verbosity)
2657
2661
2658 if self.options.list_tests:
2662 if self.options.list_tests:
2659 result = runner.listtests(suite)
2663 result = runner.listtests(suite)
2660 else:
2664 else:
2661 if self._installdir:
2665 if self._installdir:
2662 self._installhg()
2666 self._installhg()
2663 self._checkhglib("Testing")
2667 self._checkhglib("Testing")
2664 else:
2668 else:
2665 self._usecorrectpython()
2669 self._usecorrectpython()
2666 if self.options.chg:
2670 if self.options.chg:
2667 assert self._installdir
2671 assert self._installdir
2668 self._installchg()
2672 self._installchg()
2669
2673
2670 result = runner.run(suite)
2674 result = runner.run(suite)
2671
2675
2672 if result.failures:
2676 if result.failures:
2673 failed = True
2677 failed = True
2674
2678
2675 if self.options.anycoverage:
2679 if self.options.anycoverage:
2676 self._outputcoverage()
2680 self._outputcoverage()
2677 except KeyboardInterrupt:
2681 except KeyboardInterrupt:
2678 failed = True
2682 failed = True
2679 print("\ninterrupted!")
2683 print("\ninterrupted!")
2680
2684
2681 if failed:
2685 if failed:
2682 return 1
2686 return 1
2683
2687
2684 def _getport(self, count):
2688 def _getport(self, count):
2685 port = self._ports.get(count) # do we have a cached entry?
2689 port = self._ports.get(count) # do we have a cached entry?
2686 if port is None:
2690 if port is None:
2687 portneeded = 3
2691 portneeded = 3
2688 # above 100 tries we just give up and let test reports failure
2692 # above 100 tries we just give up and let test reports failure
2689 for tries in xrange(100):
2693 for tries in xrange(100):
2690 allfree = True
2694 allfree = True
2691 port = self.options.port + self._portoffset
2695 port = self.options.port + self._portoffset
2692 for idx in xrange(portneeded):
2696 for idx in xrange(portneeded):
2693 if not checkportisavailable(port + idx):
2697 if not checkportisavailable(port + idx):
2694 allfree = False
2698 allfree = False
2695 break
2699 break
2696 self._portoffset += portneeded
2700 self._portoffset += portneeded
2697 if allfree:
2701 if allfree:
2698 break
2702 break
2699 self._ports[count] = port
2703 self._ports[count] = port
2700 return port
2704 return port
2701
2705
2702 def _gettest(self, testdesc, count):
2706 def _gettest(self, testdesc, count):
2703 """Obtain a Test by looking at its filename.
2707 """Obtain a Test by looking at its filename.
2704
2708
2705 Returns a Test instance. The Test may not be runnable if it doesn't
2709 Returns a Test instance. The Test may not be runnable if it doesn't
2706 map to a known type.
2710 map to a known type.
2707 """
2711 """
2708 path = testdesc['path']
2712 path = testdesc['path']
2709 lctest = path.lower()
2713 lctest = path.lower()
2710 testcls = Test
2714 testcls = Test
2711
2715
2712 for ext, cls in self.TESTTYPES:
2716 for ext, cls in self.TESTTYPES:
2713 if lctest.endswith(ext):
2717 if lctest.endswith(ext):
2714 testcls = cls
2718 testcls = cls
2715 break
2719 break
2716
2720
2717 refpath = os.path.join(self._testdir, path)
2721 refpath = os.path.join(self._testdir, path)
2718 tmpdir = os.path.join(self._hgtmp, b'child%d' % count)
2722 tmpdir = os.path.join(self._hgtmp, b'child%d' % count)
2719
2723
2720 # extra keyword parameters. 'case' is used by .t tests
2724 # extra keyword parameters. 'case' is used by .t tests
2721 kwds = dict((k, testdesc[k]) for k in ['case'] if k in testdesc)
2725 kwds = dict((k, testdesc[k]) for k in ['case'] if k in testdesc)
2722
2726
2723 t = testcls(refpath, self._outputdir, tmpdir,
2727 t = testcls(refpath, self._outputdir, tmpdir,
2724 keeptmpdir=self.options.keep_tmpdir,
2728 keeptmpdir=self.options.keep_tmpdir,
2725 debug=self.options.debug,
2729 debug=self.options.debug,
2726 first=self.options.first,
2730 first=self.options.first,
2727 timeout=self.options.timeout,
2731 timeout=self.options.timeout,
2728 startport=self._getport(count),
2732 startport=self._getport(count),
2729 extraconfigopts=self.options.extra_config_opt,
2733 extraconfigopts=self.options.extra_config_opt,
2730 py3kwarnings=self.options.py3k_warnings,
2734 py3kwarnings=self.options.py3k_warnings,
2731 shell=self.options.shell,
2735 shell=self.options.shell,
2732 hgcommand=self._hgcommand,
2736 hgcommand=self._hgcommand,
2733 usechg=bool(self.options.with_chg or self.options.chg),
2737 usechg=bool(self.options.with_chg or self.options.chg),
2734 useipv6=useipv6, **kwds)
2738 useipv6=useipv6, **kwds)
2735 t.should_reload = True
2739 t.should_reload = True
2736 return t
2740 return t
2737
2741
2738 def _cleanup(self):
2742 def _cleanup(self):
2739 """Clean up state from this test invocation."""
2743 """Clean up state from this test invocation."""
2740 if self.options.keep_tmpdir:
2744 if self.options.keep_tmpdir:
2741 return
2745 return
2742
2746
2743 vlog("# Cleaning up HGTMP", self._hgtmp)
2747 vlog("# Cleaning up HGTMP", self._hgtmp)
2744 shutil.rmtree(self._hgtmp, True)
2748 shutil.rmtree(self._hgtmp, True)
2745 for f in self._createdfiles:
2749 for f in self._createdfiles:
2746 try:
2750 try:
2747 os.remove(f)
2751 os.remove(f)
2748 except OSError:
2752 except OSError:
2749 pass
2753 pass
2750
2754
2751 def _usecorrectpython(self):
2755 def _usecorrectpython(self):
2752 """Configure the environment to use the appropriate Python in tests."""
2756 """Configure the environment to use the appropriate Python in tests."""
2753 # Tests must use the same interpreter as us or bad things will happen.
2757 # Tests must use the same interpreter as us or bad things will happen.
2754 pyexename = sys.platform == 'win32' and b'python.exe' or b'python'
2758 pyexename = sys.platform == 'win32' and b'python.exe' or b'python'
2755 if getattr(os, 'symlink', None):
2759 if getattr(os, 'symlink', None):
2756 vlog("# Making python executable in test path a symlink to '%s'" %
2760 vlog("# Making python executable in test path a symlink to '%s'" %
2757 sys.executable)
2761 sys.executable)
2758 mypython = os.path.join(self._tmpbindir, pyexename)
2762 mypython = os.path.join(self._tmpbindir, pyexename)
2759 try:
2763 try:
2760 if os.readlink(mypython) == sys.executable:
2764 if os.readlink(mypython) == sys.executable:
2761 return
2765 return
2762 os.unlink(mypython)
2766 os.unlink(mypython)
2763 except OSError as err:
2767 except OSError as err:
2764 if err.errno != errno.ENOENT:
2768 if err.errno != errno.ENOENT:
2765 raise
2769 raise
2766 if self._findprogram(pyexename) != sys.executable:
2770 if self._findprogram(pyexename) != sys.executable:
2767 try:
2771 try:
2768 os.symlink(sys.executable, mypython)
2772 os.symlink(sys.executable, mypython)
2769 self._createdfiles.append(mypython)
2773 self._createdfiles.append(mypython)
2770 except OSError as err:
2774 except OSError as err:
2771 # child processes may race, which is harmless
2775 # child processes may race, which is harmless
2772 if err.errno != errno.EEXIST:
2776 if err.errno != errno.EEXIST:
2773 raise
2777 raise
2774 else:
2778 else:
2775 exedir, exename = os.path.split(sys.executable)
2779 exedir, exename = os.path.split(sys.executable)
2776 vlog("# Modifying search path to find %s as %s in '%s'" %
2780 vlog("# Modifying search path to find %s as %s in '%s'" %
2777 (exename, pyexename, exedir))
2781 (exename, pyexename, exedir))
2778 path = os.environ['PATH'].split(os.pathsep)
2782 path = os.environ['PATH'].split(os.pathsep)
2779 while exedir in path:
2783 while exedir in path:
2780 path.remove(exedir)
2784 path.remove(exedir)
2781 os.environ['PATH'] = os.pathsep.join([exedir] + path)
2785 os.environ['PATH'] = os.pathsep.join([exedir] + path)
2782 if not self._findprogram(pyexename):
2786 if not self._findprogram(pyexename):
2783 print("WARNING: Cannot find %s in search path" % pyexename)
2787 print("WARNING: Cannot find %s in search path" % pyexename)
2784
2788
2785 def _installhg(self):
2789 def _installhg(self):
2786 """Install hg into the test environment.
2790 """Install hg into the test environment.
2787
2791
2788 This will also configure hg with the appropriate testing settings.
2792 This will also configure hg with the appropriate testing settings.
2789 """
2793 """
2790 vlog("# Performing temporary installation of HG")
2794 vlog("# Performing temporary installation of HG")
2791 installerrs = os.path.join(self._hgtmp, b"install.err")
2795 installerrs = os.path.join(self._hgtmp, b"install.err")
2792 compiler = ''
2796 compiler = ''
2793 if self.options.compiler:
2797 if self.options.compiler:
2794 compiler = '--compiler ' + self.options.compiler
2798 compiler = '--compiler ' + self.options.compiler
2795 if self.options.pure:
2799 if self.options.pure:
2796 pure = b"--pure"
2800 pure = b"--pure"
2797 else:
2801 else:
2798 pure = b""
2802 pure = b""
2799
2803
2800 # Run installer in hg root
2804 # Run installer in hg root
2801 script = os.path.realpath(sys.argv[0])
2805 script = os.path.realpath(sys.argv[0])
2802 exe = sys.executable
2806 exe = sys.executable
2803 if PYTHON3:
2807 if PYTHON3:
2804 compiler = _bytespath(compiler)
2808 compiler = _bytespath(compiler)
2805 script = _bytespath(script)
2809 script = _bytespath(script)
2806 exe = _bytespath(exe)
2810 exe = _bytespath(exe)
2807 hgroot = os.path.dirname(os.path.dirname(script))
2811 hgroot = os.path.dirname(os.path.dirname(script))
2808 self._hgroot = hgroot
2812 self._hgroot = hgroot
2809 os.chdir(hgroot)
2813 os.chdir(hgroot)
2810 nohome = b'--home=""'
2814 nohome = b'--home=""'
2811 if os.name == 'nt':
2815 if os.name == 'nt':
2812 # The --home="" trick works only on OS where os.sep == '/'
2816 # The --home="" trick works only on OS where os.sep == '/'
2813 # because of a distutils convert_path() fast-path. Avoid it at
2817 # because of a distutils convert_path() fast-path. Avoid it at
2814 # least on Windows for now, deal with .pydistutils.cfg bugs
2818 # least on Windows for now, deal with .pydistutils.cfg bugs
2815 # when they happen.
2819 # when they happen.
2816 nohome = b''
2820 nohome = b''
2817 cmd = (b'%(exe)s setup.py %(pure)s clean --all'
2821 cmd = (b'%(exe)s setup.py %(pure)s clean --all'
2818 b' build %(compiler)s --build-base="%(base)s"'
2822 b' build %(compiler)s --build-base="%(base)s"'
2819 b' install --force --prefix="%(prefix)s"'
2823 b' install --force --prefix="%(prefix)s"'
2820 b' --install-lib="%(libdir)s"'
2824 b' --install-lib="%(libdir)s"'
2821 b' --install-scripts="%(bindir)s" %(nohome)s >%(logfile)s 2>&1'
2825 b' --install-scripts="%(bindir)s" %(nohome)s >%(logfile)s 2>&1'
2822 % {b'exe': exe, b'pure': pure,
2826 % {b'exe': exe, b'pure': pure,
2823 b'compiler': compiler,
2827 b'compiler': compiler,
2824 b'base': os.path.join(self._hgtmp, b"build"),
2828 b'base': os.path.join(self._hgtmp, b"build"),
2825 b'prefix': self._installdir, b'libdir': self._pythondir,
2829 b'prefix': self._installdir, b'libdir': self._pythondir,
2826 b'bindir': self._bindir,
2830 b'bindir': self._bindir,
2827 b'nohome': nohome, b'logfile': installerrs})
2831 b'nohome': nohome, b'logfile': installerrs})
2828
2832
2829 # setuptools requires install directories to exist.
2833 # setuptools requires install directories to exist.
2830 def makedirs(p):
2834 def makedirs(p):
2831 try:
2835 try:
2832 os.makedirs(p)
2836 os.makedirs(p)
2833 except OSError as e:
2837 except OSError as e:
2834 if e.errno != errno.EEXIST:
2838 if e.errno != errno.EEXIST:
2835 raise
2839 raise
2836 makedirs(self._pythondir)
2840 makedirs(self._pythondir)
2837 makedirs(self._bindir)
2841 makedirs(self._bindir)
2838
2842
2839 vlog("# Running", cmd)
2843 vlog("# Running", cmd)
2840 if os.system(cmd) == 0:
2844 if os.system(cmd) == 0:
2841 if not self.options.verbose:
2845 if not self.options.verbose:
2842 try:
2846 try:
2843 os.remove(installerrs)
2847 os.remove(installerrs)
2844 except OSError as e:
2848 except OSError as e:
2845 if e.errno != errno.ENOENT:
2849 if e.errno != errno.ENOENT:
2846 raise
2850 raise
2847 else:
2851 else:
2848 with open(installerrs, 'rb') as f:
2852 with open(installerrs, 'rb') as f:
2849 for line in f:
2853 for line in f:
2850 if PYTHON3:
2854 if PYTHON3:
2851 sys.stdout.buffer.write(line)
2855 sys.stdout.buffer.write(line)
2852 else:
2856 else:
2853 sys.stdout.write(line)
2857 sys.stdout.write(line)
2854 sys.exit(1)
2858 sys.exit(1)
2855 os.chdir(self._testdir)
2859 os.chdir(self._testdir)
2856
2860
2857 self._usecorrectpython()
2861 self._usecorrectpython()
2858
2862
2859 if self.options.py3k_warnings and not self.options.anycoverage:
2863 if self.options.py3k_warnings and not self.options.anycoverage:
2860 vlog("# Updating hg command to enable Py3k Warnings switch")
2864 vlog("# Updating hg command to enable Py3k Warnings switch")
2861 with open(os.path.join(self._bindir, 'hg'), 'rb') as f:
2865 with open(os.path.join(self._bindir, 'hg'), 'rb') as f:
2862 lines = [line.rstrip() for line in f]
2866 lines = [line.rstrip() for line in f]
2863 lines[0] += ' -3'
2867 lines[0] += ' -3'
2864 with open(os.path.join(self._bindir, 'hg'), 'wb') as f:
2868 with open(os.path.join(self._bindir, 'hg'), 'wb') as f:
2865 for line in lines:
2869 for line in lines:
2866 f.write(line + '\n')
2870 f.write(line + '\n')
2867
2871
2868 hgbat = os.path.join(self._bindir, b'hg.bat')
2872 hgbat = os.path.join(self._bindir, b'hg.bat')
2869 if os.path.isfile(hgbat):
2873 if os.path.isfile(hgbat):
2870 # hg.bat expects to be put in bin/scripts while run-tests.py
2874 # hg.bat expects to be put in bin/scripts while run-tests.py
2871 # installation layout put it in bin/ directly. Fix it
2875 # installation layout put it in bin/ directly. Fix it
2872 with open(hgbat, 'rb') as f:
2876 with open(hgbat, 'rb') as f:
2873 data = f.read()
2877 data = f.read()
2874 if b'"%~dp0..\python" "%~dp0hg" %*' in data:
2878 if b'"%~dp0..\python" "%~dp0hg" %*' in data:
2875 data = data.replace(b'"%~dp0..\python" "%~dp0hg" %*',
2879 data = data.replace(b'"%~dp0..\python" "%~dp0hg" %*',
2876 b'"%~dp0python" "%~dp0hg" %*')
2880 b'"%~dp0python" "%~dp0hg" %*')
2877 with open(hgbat, 'wb') as f:
2881 with open(hgbat, 'wb') as f:
2878 f.write(data)
2882 f.write(data)
2879 else:
2883 else:
2880 print('WARNING: cannot fix hg.bat reference to python.exe')
2884 print('WARNING: cannot fix hg.bat reference to python.exe')
2881
2885
2882 if self.options.anycoverage:
2886 if self.options.anycoverage:
2883 custom = os.path.join(self._testdir, 'sitecustomize.py')
2887 custom = os.path.join(self._testdir, 'sitecustomize.py')
2884 target = os.path.join(self._pythondir, 'sitecustomize.py')
2888 target = os.path.join(self._pythondir, 'sitecustomize.py')
2885 vlog('# Installing coverage trigger to %s' % target)
2889 vlog('# Installing coverage trigger to %s' % target)
2886 shutil.copyfile(custom, target)
2890 shutil.copyfile(custom, target)
2887 rc = os.path.join(self._testdir, '.coveragerc')
2891 rc = os.path.join(self._testdir, '.coveragerc')
2888 vlog('# Installing coverage rc to %s' % rc)
2892 vlog('# Installing coverage rc to %s' % rc)
2889 os.environ['COVERAGE_PROCESS_START'] = rc
2893 os.environ['COVERAGE_PROCESS_START'] = rc
2890 covdir = os.path.join(self._installdir, '..', 'coverage')
2894 covdir = os.path.join(self._installdir, '..', 'coverage')
2891 try:
2895 try:
2892 os.mkdir(covdir)
2896 os.mkdir(covdir)
2893 except OSError as e:
2897 except OSError as e:
2894 if e.errno != errno.EEXIST:
2898 if e.errno != errno.EEXIST:
2895 raise
2899 raise
2896
2900
2897 os.environ['COVERAGE_DIR'] = covdir
2901 os.environ['COVERAGE_DIR'] = covdir
2898
2902
2899 def _checkhglib(self, verb):
2903 def _checkhglib(self, verb):
2900 """Ensure that the 'mercurial' package imported by python is
2904 """Ensure that the 'mercurial' package imported by python is
2901 the one we expect it to be. If not, print a warning to stderr."""
2905 the one we expect it to be. If not, print a warning to stderr."""
2902 if ((self._bindir == self._pythondir) and
2906 if ((self._bindir == self._pythondir) and
2903 (self._bindir != self._tmpbindir)):
2907 (self._bindir != self._tmpbindir)):
2904 # The pythondir has been inferred from --with-hg flag.
2908 # The pythondir has been inferred from --with-hg flag.
2905 # We cannot expect anything sensible here.
2909 # We cannot expect anything sensible here.
2906 return
2910 return
2907 expecthg = os.path.join(self._pythondir, b'mercurial')
2911 expecthg = os.path.join(self._pythondir, b'mercurial')
2908 actualhg = self._gethgpath()
2912 actualhg = self._gethgpath()
2909 if os.path.abspath(actualhg) != os.path.abspath(expecthg):
2913 if os.path.abspath(actualhg) != os.path.abspath(expecthg):
2910 sys.stderr.write('warning: %s with unexpected mercurial lib: %s\n'
2914 sys.stderr.write('warning: %s with unexpected mercurial lib: %s\n'
2911 ' (expected %s)\n'
2915 ' (expected %s)\n'
2912 % (verb, actualhg, expecthg))
2916 % (verb, actualhg, expecthg))
2913 def _gethgpath(self):
2917 def _gethgpath(self):
2914 """Return the path to the mercurial package that is actually found by
2918 """Return the path to the mercurial package that is actually found by
2915 the current Python interpreter."""
2919 the current Python interpreter."""
2916 if self._hgpath is not None:
2920 if self._hgpath is not None:
2917 return self._hgpath
2921 return self._hgpath
2918
2922
2919 cmd = b'%s -c "import mercurial; print (mercurial.__path__[0])"'
2923 cmd = b'%s -c "import mercurial; print (mercurial.__path__[0])"'
2920 cmd = cmd % PYTHON
2924 cmd = cmd % PYTHON
2921 if PYTHON3:
2925 if PYTHON3:
2922 cmd = _strpath(cmd)
2926 cmd = _strpath(cmd)
2923 pipe = os.popen(cmd)
2927 pipe = os.popen(cmd)
2924 try:
2928 try:
2925 self._hgpath = _bytespath(pipe.read().strip())
2929 self._hgpath = _bytespath(pipe.read().strip())
2926 finally:
2930 finally:
2927 pipe.close()
2931 pipe.close()
2928
2932
2929 return self._hgpath
2933 return self._hgpath
2930
2934
2931 def _installchg(self):
2935 def _installchg(self):
2932 """Install chg into the test environment"""
2936 """Install chg into the test environment"""
2933 vlog('# Performing temporary installation of CHG')
2937 vlog('# Performing temporary installation of CHG')
2934 assert os.path.dirname(self._bindir) == self._installdir
2938 assert os.path.dirname(self._bindir) == self._installdir
2935 assert self._hgroot, 'must be called after _installhg()'
2939 assert self._hgroot, 'must be called after _installhg()'
2936 cmd = (b'"%(make)s" clean install PREFIX="%(prefix)s"'
2940 cmd = (b'"%(make)s" clean install PREFIX="%(prefix)s"'
2937 % {b'make': 'make', # TODO: switch by option or environment?
2941 % {b'make': 'make', # TODO: switch by option or environment?
2938 b'prefix': self._installdir})
2942 b'prefix': self._installdir})
2939 cwd = os.path.join(self._hgroot, b'contrib', b'chg')
2943 cwd = os.path.join(self._hgroot, b'contrib', b'chg')
2940 vlog("# Running", cmd)
2944 vlog("# Running", cmd)
2941 proc = subprocess.Popen(cmd, shell=True, cwd=cwd,
2945 proc = subprocess.Popen(cmd, shell=True, cwd=cwd,
2942 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
2946 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
2943 stderr=subprocess.STDOUT)
2947 stderr=subprocess.STDOUT)
2944 out, _err = proc.communicate()
2948 out, _err = proc.communicate()
2945 if proc.returncode != 0:
2949 if proc.returncode != 0:
2946 if PYTHON3:
2950 if PYTHON3:
2947 sys.stdout.buffer.write(out)
2951 sys.stdout.buffer.write(out)
2948 else:
2952 else:
2949 sys.stdout.write(out)
2953 sys.stdout.write(out)
2950 sys.exit(1)
2954 sys.exit(1)
2951
2955
2952 def _outputcoverage(self):
2956 def _outputcoverage(self):
2953 """Produce code coverage output."""
2957 """Produce code coverage output."""
2954 import coverage
2958 import coverage
2955 coverage = coverage.coverage
2959 coverage = coverage.coverage
2956
2960
2957 vlog('# Producing coverage report')
2961 vlog('# Producing coverage report')
2958 # chdir is the easiest way to get short, relative paths in the
2962 # chdir is the easiest way to get short, relative paths in the
2959 # output.
2963 # output.
2960 os.chdir(self._hgroot)
2964 os.chdir(self._hgroot)
2961 covdir = os.path.join(self._installdir, '..', 'coverage')
2965 covdir = os.path.join(self._installdir, '..', 'coverage')
2962 cov = coverage(data_file=os.path.join(covdir, 'cov'))
2966 cov = coverage(data_file=os.path.join(covdir, 'cov'))
2963
2967
2964 # Map install directory paths back to source directory.
2968 # Map install directory paths back to source directory.
2965 cov.config.paths['srcdir'] = ['.', self._pythondir]
2969 cov.config.paths['srcdir'] = ['.', self._pythondir]
2966
2970
2967 cov.combine()
2971 cov.combine()
2968
2972
2969 omit = [os.path.join(x, '*') for x in [self._bindir, self._testdir]]
2973 omit = [os.path.join(x, '*') for x in [self._bindir, self._testdir]]
2970 cov.report(ignore_errors=True, omit=omit)
2974 cov.report(ignore_errors=True, omit=omit)
2971
2975
2972 if self.options.htmlcov:
2976 if self.options.htmlcov:
2973 htmldir = os.path.join(self._outputdir, 'htmlcov')
2977 htmldir = os.path.join(self._outputdir, 'htmlcov')
2974 cov.html_report(directory=htmldir, omit=omit)
2978 cov.html_report(directory=htmldir, omit=omit)
2975 if self.options.annotate:
2979 if self.options.annotate:
2976 adir = os.path.join(self._outputdir, 'annotated')
2980 adir = os.path.join(self._outputdir, 'annotated')
2977 if not os.path.isdir(adir):
2981 if not os.path.isdir(adir):
2978 os.mkdir(adir)
2982 os.mkdir(adir)
2979 cov.annotate(directory=adir, omit=omit)
2983 cov.annotate(directory=adir, omit=omit)
2980
2984
2981 def _findprogram(self, program):
2985 def _findprogram(self, program):
2982 """Search PATH for a executable program"""
2986 """Search PATH for a executable program"""
2983 dpb = _bytespath(os.defpath)
2987 dpb = _bytespath(os.defpath)
2984 sepb = _bytespath(os.pathsep)
2988 sepb = _bytespath(os.pathsep)
2985 for p in osenvironb.get(b'PATH', dpb).split(sepb):
2989 for p in osenvironb.get(b'PATH', dpb).split(sepb):
2986 name = os.path.join(p, program)
2990 name = os.path.join(p, program)
2987 if os.name == 'nt' or os.access(name, os.X_OK):
2991 if os.name == 'nt' or os.access(name, os.X_OK):
2988 return name
2992 return name
2989 return None
2993 return None
2990
2994
2991 def _checktools(self):
2995 def _checktools(self):
2992 """Ensure tools required to run tests are present."""
2996 """Ensure tools required to run tests are present."""
2993 for p in self.REQUIREDTOOLS:
2997 for p in self.REQUIREDTOOLS:
2994 if os.name == 'nt' and not p.endswith('.exe'):
2998 if os.name == 'nt' and not p.endswith('.exe'):
2995 p += '.exe'
2999 p += '.exe'
2996 found = self._findprogram(p)
3000 found = self._findprogram(p)
2997 if found:
3001 if found:
2998 vlog("# Found prerequisite", p, "at", found)
3002 vlog("# Found prerequisite", p, "at", found)
2999 else:
3003 else:
3000 print("WARNING: Did not find prerequisite tool: %s " %
3004 print("WARNING: Did not find prerequisite tool: %s " %
3001 p.decode("utf-8"))
3005 p.decode("utf-8"))
3002
3006
3003 def aggregateexceptions(path):
3007 def aggregateexceptions(path):
3004 exceptions = collections.Counter()
3008 exceptions = collections.Counter()
3005
3009
3006 for f in os.listdir(path):
3010 for f in os.listdir(path):
3007 with open(os.path.join(path, f), 'rb') as fh:
3011 with open(os.path.join(path, f), 'rb') as fh:
3008 data = fh.read().split(b'\0')
3012 data = fh.read().split(b'\0')
3009 if len(data) != 4:
3013 if len(data) != 4:
3010 continue
3014 continue
3011
3015
3012 exc, mainframe, hgframe, hgline = data
3016 exc, mainframe, hgframe, hgline = data
3013 exc = exc.decode('utf-8')
3017 exc = exc.decode('utf-8')
3014 mainframe = mainframe.decode('utf-8')
3018 mainframe = mainframe.decode('utf-8')
3015 hgframe = hgframe.decode('utf-8')
3019 hgframe = hgframe.decode('utf-8')
3016 hgline = hgline.decode('utf-8')
3020 hgline = hgline.decode('utf-8')
3017 exceptions[(hgframe, hgline, exc)] += 1
3021 exceptions[(hgframe, hgline, exc)] += 1
3018
3022
3019 return exceptions
3023 return exceptions
3020
3024
3021 if __name__ == '__main__':
3025 if __name__ == '__main__':
3022 runner = TestRunner()
3026 runner = TestRunner()
3023
3027
3024 try:
3028 try:
3025 import msvcrt
3029 import msvcrt
3026 msvcrt.setmode(sys.stdin.fileno(), os.O_BINARY)
3030 msvcrt.setmode(sys.stdin.fileno(), os.O_BINARY)
3027 msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)
3031 msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)
3028 msvcrt.setmode(sys.stderr.fileno(), os.O_BINARY)
3032 msvcrt.setmode(sys.stderr.fileno(), os.O_BINARY)
3029 except ImportError:
3033 except ImportError:
3030 pass
3034 pass
3031
3035
3032 sys.exit(runner.run(sys.argv[1:]))
3036 sys.exit(runner.run(sys.argv[1:]))
General Comments 0
You need to be logged in to leave comments. Login now