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