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