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