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