##// END OF EJS Templates
run-tests: make retest a named argument of TestSuite.__init__
Gregory Szorc -
r21530:78289625 default
parent child Browse files
Show More
@@ -1,1751 +1,1757 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 #
38 #
39 # (You could use any subset of the tests: test-s* happens to match
39 # (You could use any subset of the tests: test-s* happens to match
40 # enough that it's worth doing parallel runs, few enough that it
40 # enough that it's worth doing parallel runs, few enough that it
41 # completes fairly quickly, includes both shell and Python scripts, and
41 # completes fairly quickly, includes both shell and Python scripts, and
42 # includes some scripts that run daemon processes.)
42 # includes some scripts that run daemon processes.)
43
43
44 from distutils import version
44 from distutils import version
45 import difflib
45 import difflib
46 import errno
46 import errno
47 import optparse
47 import optparse
48 import os
48 import os
49 import shutil
49 import shutil
50 import subprocess
50 import subprocess
51 import signal
51 import signal
52 import sys
52 import sys
53 import tempfile
53 import tempfile
54 import time
54 import time
55 import random
55 import random
56 import re
56 import re
57 import threading
57 import threading
58 import killdaemons as killmod
58 import killdaemons as killmod
59 import Queue as queue
59 import Queue as queue
60 import unittest
60 import unittest
61
61
62 processlock = threading.Lock()
62 processlock = threading.Lock()
63
63
64 # subprocess._cleanup can race with any Popen.wait or Popen.poll on py24
64 # subprocess._cleanup can race with any Popen.wait or Popen.poll on py24
65 # http://bugs.python.org/issue1731717 for details. We shouldn't be producing
65 # http://bugs.python.org/issue1731717 for details. We shouldn't be producing
66 # zombies but it's pretty harmless even if we do.
66 # zombies but it's pretty harmless even if we do.
67 if sys.version_info < (2, 5):
67 if sys.version_info < (2, 5):
68 subprocess._cleanup = lambda: None
68 subprocess._cleanup = lambda: None
69
69
70 closefds = os.name == 'posix'
70 closefds = os.name == 'posix'
71 def Popen4(cmd, wd, timeout, env=None):
71 def Popen4(cmd, wd, timeout, env=None):
72 processlock.acquire()
72 processlock.acquire()
73 p = subprocess.Popen(cmd, shell=True, bufsize=-1, cwd=wd, env=env,
73 p = subprocess.Popen(cmd, shell=True, bufsize=-1, cwd=wd, env=env,
74 close_fds=closefds,
74 close_fds=closefds,
75 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
75 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
76 stderr=subprocess.STDOUT)
76 stderr=subprocess.STDOUT)
77 processlock.release()
77 processlock.release()
78
78
79 p.fromchild = p.stdout
79 p.fromchild = p.stdout
80 p.tochild = p.stdin
80 p.tochild = p.stdin
81 p.childerr = p.stderr
81 p.childerr = p.stderr
82
82
83 p.timeout = False
83 p.timeout = False
84 if timeout:
84 if timeout:
85 def t():
85 def t():
86 start = time.time()
86 start = time.time()
87 while time.time() - start < timeout and p.returncode is None:
87 while time.time() - start < timeout and p.returncode is None:
88 time.sleep(.1)
88 time.sleep(.1)
89 p.timeout = True
89 p.timeout = True
90 if p.returncode is None:
90 if p.returncode is None:
91 terminate(p)
91 terminate(p)
92 threading.Thread(target=t).start()
92 threading.Thread(target=t).start()
93
93
94 return p
94 return p
95
95
96 PYTHON = sys.executable.replace('\\', '/')
96 PYTHON = sys.executable.replace('\\', '/')
97 IMPL_PATH = 'PYTHONPATH'
97 IMPL_PATH = 'PYTHONPATH'
98 if 'java' in sys.platform:
98 if 'java' in sys.platform:
99 IMPL_PATH = 'JYTHONPATH'
99 IMPL_PATH = 'JYTHONPATH'
100
100
101 TESTDIR = HGTMP = INST = BINDIR = TMPBINDIR = PYTHONDIR = None
101 TESTDIR = HGTMP = INST = BINDIR = TMPBINDIR = PYTHONDIR = None
102
102
103 defaults = {
103 defaults = {
104 'jobs': ('HGTEST_JOBS', 1),
104 'jobs': ('HGTEST_JOBS', 1),
105 'timeout': ('HGTEST_TIMEOUT', 180),
105 'timeout': ('HGTEST_TIMEOUT', 180),
106 'port': ('HGTEST_PORT', 20059),
106 'port': ('HGTEST_PORT', 20059),
107 'shell': ('HGTEST_SHELL', 'sh'),
107 'shell': ('HGTEST_SHELL', 'sh'),
108 }
108 }
109
109
110 def parselistfiles(files, listtype, warn=True):
110 def parselistfiles(files, listtype, warn=True):
111 entries = dict()
111 entries = dict()
112 for filename in files:
112 for filename in files:
113 try:
113 try:
114 path = os.path.expanduser(os.path.expandvars(filename))
114 path = os.path.expanduser(os.path.expandvars(filename))
115 f = open(path, "r")
115 f = open(path, "r")
116 except IOError, err:
116 except IOError, err:
117 if err.errno != errno.ENOENT:
117 if err.errno != errno.ENOENT:
118 raise
118 raise
119 if warn:
119 if warn:
120 print "warning: no such %s file: %s" % (listtype, filename)
120 print "warning: no such %s file: %s" % (listtype, filename)
121 continue
121 continue
122
122
123 for line in f.readlines():
123 for line in f.readlines():
124 line = line.split('#', 1)[0].strip()
124 line = line.split('#', 1)[0].strip()
125 if line:
125 if line:
126 entries[line] = filename
126 entries[line] = filename
127
127
128 f.close()
128 f.close()
129 return entries
129 return entries
130
130
131 def getparser():
131 def getparser():
132 """Obtain the OptionParser used by the CLI."""
132 """Obtain the OptionParser used by the CLI."""
133 parser = optparse.OptionParser("%prog [options] [tests]")
133 parser = optparse.OptionParser("%prog [options] [tests]")
134
134
135 # keep these sorted
135 # keep these sorted
136 parser.add_option("--blacklist", action="append",
136 parser.add_option("--blacklist", action="append",
137 help="skip tests listed in the specified blacklist file")
137 help="skip tests listed in the specified blacklist file")
138 parser.add_option("--whitelist", action="append",
138 parser.add_option("--whitelist", action="append",
139 help="always run tests listed in the specified whitelist file")
139 help="always run tests listed in the specified whitelist file")
140 parser.add_option("--changed", type="string",
140 parser.add_option("--changed", type="string",
141 help="run tests that are changed in parent rev or working directory")
141 help="run tests that are changed in parent rev or working directory")
142 parser.add_option("-C", "--annotate", action="store_true",
142 parser.add_option("-C", "--annotate", action="store_true",
143 help="output files annotated with coverage")
143 help="output files annotated with coverage")
144 parser.add_option("-c", "--cover", action="store_true",
144 parser.add_option("-c", "--cover", action="store_true",
145 help="print a test coverage report")
145 help="print a test coverage report")
146 parser.add_option("-d", "--debug", action="store_true",
146 parser.add_option("-d", "--debug", action="store_true",
147 help="debug mode: write output of test scripts to console"
147 help="debug mode: write output of test scripts to console"
148 " rather than capturing and diffing it (disables timeout)")
148 " rather than capturing and diffing it (disables timeout)")
149 parser.add_option("-f", "--first", action="store_true",
149 parser.add_option("-f", "--first", action="store_true",
150 help="exit on the first test failure")
150 help="exit on the first test failure")
151 parser.add_option("-H", "--htmlcov", action="store_true",
151 parser.add_option("-H", "--htmlcov", action="store_true",
152 help="create an HTML report of the coverage of the files")
152 help="create an HTML report of the coverage of the files")
153 parser.add_option("-i", "--interactive", action="store_true",
153 parser.add_option("-i", "--interactive", action="store_true",
154 help="prompt to accept changed output")
154 help="prompt to accept changed output")
155 parser.add_option("-j", "--jobs", type="int",
155 parser.add_option("-j", "--jobs", type="int",
156 help="number of jobs to run in parallel"
156 help="number of jobs to run in parallel"
157 " (default: $%s or %d)" % defaults['jobs'])
157 " (default: $%s or %d)" % defaults['jobs'])
158 parser.add_option("--keep-tmpdir", action="store_true",
158 parser.add_option("--keep-tmpdir", action="store_true",
159 help="keep temporary directory after running tests")
159 help="keep temporary directory after running tests")
160 parser.add_option("-k", "--keywords",
160 parser.add_option("-k", "--keywords",
161 help="run tests matching keywords")
161 help="run tests matching keywords")
162 parser.add_option("-l", "--local", action="store_true",
162 parser.add_option("-l", "--local", action="store_true",
163 help="shortcut for --with-hg=<testdir>/../hg")
163 help="shortcut for --with-hg=<testdir>/../hg")
164 parser.add_option("--loop", action="store_true",
164 parser.add_option("--loop", action="store_true",
165 help="loop tests repeatedly")
165 help="loop tests repeatedly")
166 parser.add_option("-n", "--nodiff", action="store_true",
166 parser.add_option("-n", "--nodiff", action="store_true",
167 help="skip showing test changes")
167 help="skip showing test changes")
168 parser.add_option("-p", "--port", type="int",
168 parser.add_option("-p", "--port", type="int",
169 help="port on which servers should listen"
169 help="port on which servers should listen"
170 " (default: $%s or %d)" % defaults['port'])
170 " (default: $%s or %d)" % defaults['port'])
171 parser.add_option("--compiler", type="string",
171 parser.add_option("--compiler", type="string",
172 help="compiler to build with")
172 help="compiler to build with")
173 parser.add_option("--pure", action="store_true",
173 parser.add_option("--pure", action="store_true",
174 help="use pure Python code instead of C extensions")
174 help="use pure Python code instead of C extensions")
175 parser.add_option("-R", "--restart", action="store_true",
175 parser.add_option("-R", "--restart", action="store_true",
176 help="restart at last error")
176 help="restart at last error")
177 parser.add_option("-r", "--retest", action="store_true",
177 parser.add_option("-r", "--retest", action="store_true",
178 help="retest failed tests")
178 help="retest failed tests")
179 parser.add_option("-S", "--noskips", action="store_true",
179 parser.add_option("-S", "--noskips", action="store_true",
180 help="don't report skip tests verbosely")
180 help="don't report skip tests verbosely")
181 parser.add_option("--shell", type="string",
181 parser.add_option("--shell", type="string",
182 help="shell to use (default: $%s or %s)" % defaults['shell'])
182 help="shell to use (default: $%s or %s)" % defaults['shell'])
183 parser.add_option("-t", "--timeout", type="int",
183 parser.add_option("-t", "--timeout", type="int",
184 help="kill errant tests after TIMEOUT seconds"
184 help="kill errant tests after TIMEOUT seconds"
185 " (default: $%s or %d)" % defaults['timeout'])
185 " (default: $%s or %d)" % defaults['timeout'])
186 parser.add_option("--time", action="store_true",
186 parser.add_option("--time", action="store_true",
187 help="time how long each test takes")
187 help="time how long each test takes")
188 parser.add_option("--tmpdir", type="string",
188 parser.add_option("--tmpdir", type="string",
189 help="run tests in the given temporary directory"
189 help="run tests in the given temporary directory"
190 " (implies --keep-tmpdir)")
190 " (implies --keep-tmpdir)")
191 parser.add_option("-v", "--verbose", action="store_true",
191 parser.add_option("-v", "--verbose", action="store_true",
192 help="output verbose messages")
192 help="output verbose messages")
193 parser.add_option("--view", type="string",
193 parser.add_option("--view", type="string",
194 help="external diff viewer")
194 help="external diff viewer")
195 parser.add_option("--with-hg", type="string",
195 parser.add_option("--with-hg", type="string",
196 metavar="HG",
196 metavar="HG",
197 help="test using specified hg script rather than a "
197 help="test using specified hg script rather than a "
198 "temporary installation")
198 "temporary installation")
199 parser.add_option("-3", "--py3k-warnings", action="store_true",
199 parser.add_option("-3", "--py3k-warnings", action="store_true",
200 help="enable Py3k warnings on Python 2.6+")
200 help="enable Py3k warnings on Python 2.6+")
201 parser.add_option('--extra-config-opt', action="append",
201 parser.add_option('--extra-config-opt', action="append",
202 help='set the given config opt in the test hgrc')
202 help='set the given config opt in the test hgrc')
203 parser.add_option('--random', action="store_true",
203 parser.add_option('--random', action="store_true",
204 help='run tests in random order')
204 help='run tests in random order')
205
205
206 for option, (envvar, default) in defaults.items():
206 for option, (envvar, default) in defaults.items():
207 defaults[option] = type(default)(os.environ.get(envvar, default))
207 defaults[option] = type(default)(os.environ.get(envvar, default))
208 parser.set_defaults(**defaults)
208 parser.set_defaults(**defaults)
209
209
210 return parser
210 return parser
211
211
212 def parseargs(args, parser):
212 def parseargs(args, parser):
213 """Parse arguments with our OptionParser and validate results."""
213 """Parse arguments with our OptionParser and validate results."""
214 (options, args) = parser.parse_args(args)
214 (options, args) = parser.parse_args(args)
215
215
216 # jython is always pure
216 # jython is always pure
217 if 'java' in sys.platform or '__pypy__' in sys.modules:
217 if 'java' in sys.platform or '__pypy__' in sys.modules:
218 options.pure = True
218 options.pure = True
219
219
220 if options.with_hg:
220 if options.with_hg:
221 options.with_hg = os.path.expanduser(options.with_hg)
221 options.with_hg = os.path.expanduser(options.with_hg)
222 if not (os.path.isfile(options.with_hg) and
222 if not (os.path.isfile(options.with_hg) and
223 os.access(options.with_hg, os.X_OK)):
223 os.access(options.with_hg, os.X_OK)):
224 parser.error('--with-hg must specify an executable hg script')
224 parser.error('--with-hg must specify an executable hg script')
225 if not os.path.basename(options.with_hg) == 'hg':
225 if not os.path.basename(options.with_hg) == 'hg':
226 sys.stderr.write('warning: --with-hg should specify an hg script\n')
226 sys.stderr.write('warning: --with-hg should specify an hg script\n')
227 if options.local:
227 if options.local:
228 testdir = os.path.dirname(os.path.realpath(sys.argv[0]))
228 testdir = os.path.dirname(os.path.realpath(sys.argv[0]))
229 hgbin = os.path.join(os.path.dirname(testdir), 'hg')
229 hgbin = os.path.join(os.path.dirname(testdir), 'hg')
230 if os.name != 'nt' and not os.access(hgbin, os.X_OK):
230 if os.name != 'nt' and not os.access(hgbin, os.X_OK):
231 parser.error('--local specified, but %r not found or not executable'
231 parser.error('--local specified, but %r not found or not executable'
232 % hgbin)
232 % hgbin)
233 options.with_hg = hgbin
233 options.with_hg = hgbin
234
234
235 options.anycoverage = options.cover or options.annotate or options.htmlcov
235 options.anycoverage = options.cover or options.annotate or options.htmlcov
236 if options.anycoverage:
236 if options.anycoverage:
237 try:
237 try:
238 import coverage
238 import coverage
239 covver = version.StrictVersion(coverage.__version__).version
239 covver = version.StrictVersion(coverage.__version__).version
240 if covver < (3, 3):
240 if covver < (3, 3):
241 parser.error('coverage options require coverage 3.3 or later')
241 parser.error('coverage options require coverage 3.3 or later')
242 except ImportError:
242 except ImportError:
243 parser.error('coverage options now require the coverage package')
243 parser.error('coverage options now require the coverage package')
244
244
245 if options.anycoverage and options.local:
245 if options.anycoverage and options.local:
246 # this needs some path mangling somewhere, I guess
246 # this needs some path mangling somewhere, I guess
247 parser.error("sorry, coverage options do not work when --local "
247 parser.error("sorry, coverage options do not work when --local "
248 "is specified")
248 "is specified")
249
249
250 global verbose
250 global verbose
251 if options.verbose:
251 if options.verbose:
252 verbose = ''
252 verbose = ''
253
253
254 if options.tmpdir:
254 if options.tmpdir:
255 options.tmpdir = os.path.expanduser(options.tmpdir)
255 options.tmpdir = os.path.expanduser(options.tmpdir)
256
256
257 if options.jobs < 1:
257 if options.jobs < 1:
258 parser.error('--jobs must be positive')
258 parser.error('--jobs must be positive')
259 if options.interactive and options.debug:
259 if options.interactive and options.debug:
260 parser.error("-i/--interactive and -d/--debug are incompatible")
260 parser.error("-i/--interactive and -d/--debug are incompatible")
261 if options.debug:
261 if options.debug:
262 if options.timeout != defaults['timeout']:
262 if options.timeout != defaults['timeout']:
263 sys.stderr.write(
263 sys.stderr.write(
264 'warning: --timeout option ignored with --debug\n')
264 'warning: --timeout option ignored with --debug\n')
265 options.timeout = 0
265 options.timeout = 0
266 if options.py3k_warnings:
266 if options.py3k_warnings:
267 if sys.version_info[:2] < (2, 6) or sys.version_info[:2] >= (3, 0):
267 if sys.version_info[:2] < (2, 6) or sys.version_info[:2] >= (3, 0):
268 parser.error('--py3k-warnings can only be used on Python 2.6+')
268 parser.error('--py3k-warnings can only be used on Python 2.6+')
269 if options.blacklist:
269 if options.blacklist:
270 options.blacklist = parselistfiles(options.blacklist, 'blacklist')
270 options.blacklist = parselistfiles(options.blacklist, 'blacklist')
271 if options.whitelist:
271 if options.whitelist:
272 options.whitelisted = parselistfiles(options.whitelist, 'whitelist')
272 options.whitelisted = parselistfiles(options.whitelist, 'whitelist')
273 else:
273 else:
274 options.whitelisted = {}
274 options.whitelisted = {}
275
275
276 return (options, args)
276 return (options, args)
277
277
278 def rename(src, dst):
278 def rename(src, dst):
279 """Like os.rename(), trade atomicity and opened files friendliness
279 """Like os.rename(), trade atomicity and opened files friendliness
280 for existing destination support.
280 for existing destination support.
281 """
281 """
282 shutil.copy(src, dst)
282 shutil.copy(src, dst)
283 os.remove(src)
283 os.remove(src)
284
284
285 def getdiff(expected, output, ref, err):
285 def getdiff(expected, output, ref, err):
286 servefail = False
286 servefail = False
287 lines = []
287 lines = []
288 for line in difflib.unified_diff(expected, output, ref, err):
288 for line in difflib.unified_diff(expected, output, ref, err):
289 lines.append(line)
289 lines.append(line)
290 if not servefail and line.startswith(
290 if not servefail and line.startswith(
291 '+ abort: child process failed to start'):
291 '+ abort: child process failed to start'):
292 servefail = True
292 servefail = True
293
293
294 return servefail, lines
294 return servefail, lines
295
295
296 verbose = False
296 verbose = False
297 def vlog(*msg):
297 def vlog(*msg):
298 if verbose is not False:
298 if verbose is not False:
299 iolock.acquire()
299 iolock.acquire()
300 if verbose:
300 if verbose:
301 print verbose,
301 print verbose,
302 for m in msg:
302 for m in msg:
303 print m,
303 print m,
304 print
304 print
305 sys.stdout.flush()
305 sys.stdout.flush()
306 iolock.release()
306 iolock.release()
307
307
308 def log(*msg):
308 def log(*msg):
309 iolock.acquire()
309 iolock.acquire()
310 if verbose:
310 if verbose:
311 print verbose,
311 print verbose,
312 for m in msg:
312 for m in msg:
313 print m,
313 print m,
314 print
314 print
315 sys.stdout.flush()
315 sys.stdout.flush()
316 iolock.release()
316 iolock.release()
317
317
318 def terminate(proc):
318 def terminate(proc):
319 """Terminate subprocess (with fallback for Python versions < 2.6)"""
319 """Terminate subprocess (with fallback for Python versions < 2.6)"""
320 vlog('# Terminating process %d' % proc.pid)
320 vlog('# Terminating process %d' % proc.pid)
321 try:
321 try:
322 getattr(proc, 'terminate', lambda : os.kill(proc.pid, signal.SIGTERM))()
322 getattr(proc, 'terminate', lambda : os.kill(proc.pid, signal.SIGTERM))()
323 except OSError:
323 except OSError:
324 pass
324 pass
325
325
326 def killdaemons(pidfile):
326 def killdaemons(pidfile):
327 return killmod.killdaemons(pidfile, tryhard=False, remove=True,
327 return killmod.killdaemons(pidfile, tryhard=False, remove=True,
328 logfn=vlog)
328 logfn=vlog)
329
329
330 class Test(unittest.TestCase):
330 class Test(unittest.TestCase):
331 """Encapsulates a single, runnable test.
331 """Encapsulates a single, runnable test.
332
332
333 While this class conforms to the unittest.TestCase API, it differs in that
333 While this class conforms to the unittest.TestCase API, it differs in that
334 instances need to be instantiated manually. (Typically, unittest.TestCase
334 instances need to be instantiated manually. (Typically, unittest.TestCase
335 classes are instantiated automatically by scanning modules.)
335 classes are instantiated automatically by scanning modules.)
336 """
336 """
337
337
338 # Status code reserved for skipped tests (used by hghave).
338 # Status code reserved for skipped tests (used by hghave).
339 SKIPPED_STATUS = 80
339 SKIPPED_STATUS = 80
340
340
341 def __init__(self, path, tmpdir, keeptmpdir=False,
341 def __init__(self, path, tmpdir, keeptmpdir=False,
342 debug=False,
342 debug=False,
343 timeout=defaults['timeout'],
343 timeout=defaults['timeout'],
344 startport=defaults['port'], extraconfigopts=None,
344 startport=defaults['port'], extraconfigopts=None,
345 py3kwarnings=False, shell=None):
345 py3kwarnings=False, shell=None):
346 """Create a test from parameters.
346 """Create a test from parameters.
347
347
348 path is the full path to the file defining the test.
348 path is the full path to the file defining the test.
349
349
350 tmpdir is the main temporary directory to use for this test.
350 tmpdir is the main temporary directory to use for this test.
351
351
352 keeptmpdir determines whether to keep the test's temporary directory
352 keeptmpdir determines whether to keep the test's temporary directory
353 after execution. It defaults to removal (False).
353 after execution. It defaults to removal (False).
354
354
355 debug mode will make the test execute verbosely, with unfiltered
355 debug mode will make the test execute verbosely, with unfiltered
356 output.
356 output.
357
357
358 timeout controls the maximum run time of the test. It is ignored when
358 timeout controls the maximum run time of the test. It is ignored when
359 debug is True.
359 debug is True.
360
360
361 startport controls the starting port number to use for this test. Each
361 startport controls the starting port number to use for this test. Each
362 test will reserve 3 port numbers for execution. It is the caller's
362 test will reserve 3 port numbers for execution. It is the caller's
363 responsibility to allocate a non-overlapping port range to Test
363 responsibility to allocate a non-overlapping port range to Test
364 instances.
364 instances.
365
365
366 extraconfigopts is an iterable of extra hgrc config options. Values
366 extraconfigopts is an iterable of extra hgrc config options. Values
367 must have the form "key=value" (something understood by hgrc). Values
367 must have the form "key=value" (something understood by hgrc). Values
368 of the form "foo.key=value" will result in "[foo] key=value".
368 of the form "foo.key=value" will result in "[foo] key=value".
369
369
370 py3kwarnings enables Py3k warnings.
370 py3kwarnings enables Py3k warnings.
371
371
372 shell is the shell to execute tests in.
372 shell is the shell to execute tests in.
373 """
373 """
374
374
375 self.path = path
375 self.path = path
376 self.name = os.path.basename(path)
376 self.name = os.path.basename(path)
377 self._testdir = os.path.dirname(path)
377 self._testdir = os.path.dirname(path)
378 self.errpath = os.path.join(self._testdir, '%s.err' % self.name)
378 self.errpath = os.path.join(self._testdir, '%s.err' % self.name)
379
379
380 self._threadtmp = tmpdir
380 self._threadtmp = tmpdir
381 self._keeptmpdir = keeptmpdir
381 self._keeptmpdir = keeptmpdir
382 self._debug = debug
382 self._debug = debug
383 self._timeout = timeout
383 self._timeout = timeout
384 self._startport = startport
384 self._startport = startport
385 self._extraconfigopts = extraconfigopts or []
385 self._extraconfigopts = extraconfigopts or []
386 self._py3kwarnings = py3kwarnings
386 self._py3kwarnings = py3kwarnings
387 self._shell = shell
387 self._shell = shell
388
388
389 self._aborted = False
389 self._aborted = False
390 self._daemonpids = []
390 self._daemonpids = []
391 self._finished = None
391 self._finished = None
392 self._ret = None
392 self._ret = None
393 self._out = None
393 self._out = None
394 self._skipped = None
394 self._skipped = None
395 self._testtmp = None
395 self._testtmp = None
396
396
397 # If we're not in --debug mode and reference output file exists,
397 # If we're not in --debug mode and reference output file exists,
398 # check test output against it.
398 # check test output against it.
399 if debug:
399 if debug:
400 self._refout = None # to match "out is None"
400 self._refout = None # to match "out is None"
401 elif os.path.exists(self.refpath):
401 elif os.path.exists(self.refpath):
402 f = open(self.refpath, 'r')
402 f = open(self.refpath, 'r')
403 self._refout = f.read().splitlines(True)
403 self._refout = f.read().splitlines(True)
404 f.close()
404 f.close()
405 else:
405 else:
406 self._refout = []
406 self._refout = []
407
407
408 def __str__(self):
408 def __str__(self):
409 return self.name
409 return self.name
410
410
411 def shortDescription(self):
411 def shortDescription(self):
412 return self.name
412 return self.name
413
413
414 def setUp(self):
414 def setUp(self):
415 """Tasks to perform before run()."""
415 """Tasks to perform before run()."""
416 self._finished = False
416 self._finished = False
417 self._ret = None
417 self._ret = None
418 self._out = None
418 self._out = None
419 self._skipped = None
419 self._skipped = None
420
420
421 try:
421 try:
422 os.mkdir(self._threadtmp)
422 os.mkdir(self._threadtmp)
423 except OSError, e:
423 except OSError, e:
424 if e.errno != errno.EEXIST:
424 if e.errno != errno.EEXIST:
425 raise
425 raise
426
426
427 self._testtmp = os.path.join(self._threadtmp,
427 self._testtmp = os.path.join(self._threadtmp,
428 os.path.basename(self.path))
428 os.path.basename(self.path))
429 os.mkdir(self._testtmp)
429 os.mkdir(self._testtmp)
430
430
431 # Remove any previous output files.
431 # Remove any previous output files.
432 if os.path.exists(self.errpath):
432 if os.path.exists(self.errpath):
433 os.remove(self.errpath)
433 os.remove(self.errpath)
434
434
435 def run(self, result):
435 def run(self, result):
436 self._result = result
436 self._result = result
437 result.startTest(self)
437 result.startTest(self)
438 try:
438 try:
439 try:
439 try:
440 self.setUp()
440 self.setUp()
441 except (KeyboardInterrupt, SystemExit):
441 except (KeyboardInterrupt, SystemExit):
442 self._aborted = True
442 self._aborted = True
443 raise
443 raise
444 except Exception:
444 except Exception:
445 result.addError(self, sys.exc_info())
445 result.addError(self, sys.exc_info())
446 return
446 return
447
447
448 success = False
448 success = False
449 try:
449 try:
450 self.runTest()
450 self.runTest()
451 except KeyboardInterrupt:
451 except KeyboardInterrupt:
452 self._aborted = True
452 self._aborted = True
453 raise
453 raise
454 except SkipTest, e:
454 except SkipTest, e:
455 result.addSkip(self, str(e))
455 result.addSkip(self, str(e))
456 except IgnoreTest, e:
456 except IgnoreTest, e:
457 result.addIgnore(self, str(e))
457 result.addIgnore(self, str(e))
458 except WarnTest, e:
458 except WarnTest, e:
459 result.addWarn(self, str(e))
459 result.addWarn(self, str(e))
460 except self.failureException, e:
460 except self.failureException, e:
461 # This differs from unittest in that we don't capture
461 # This differs from unittest in that we don't capture
462 # the stack trace. This is for historical reasons and
462 # the stack trace. This is for historical reasons and
463 # this decision could be revisted in the future,
463 # this decision could be revisted in the future,
464 # especially for PythonTest instances.
464 # especially for PythonTest instances.
465 result.addFailure(self, str(e))
465 result.addFailure(self, str(e))
466 except Exception:
466 except Exception:
467 result.addError(self, sys.exc_info())
467 result.addError(self, sys.exc_info())
468 else:
468 else:
469 success = True
469 success = True
470
470
471 try:
471 try:
472 self.tearDown()
472 self.tearDown()
473 except (KeyboardInterrupt, SystemExit):
473 except (KeyboardInterrupt, SystemExit):
474 self._aborted = True
474 self._aborted = True
475 raise
475 raise
476 except Exception:
476 except Exception:
477 result.addError(self, sys.exc_info())
477 result.addError(self, sys.exc_info())
478 success = False
478 success = False
479
479
480 if success:
480 if success:
481 result.addSuccess(self)
481 result.addSuccess(self)
482 finally:
482 finally:
483 result.stopTest(self, interrupted=self._aborted)
483 result.stopTest(self, interrupted=self._aborted)
484
484
485 def runTest(self):
485 def runTest(self):
486 """Run this test instance.
486 """Run this test instance.
487
487
488 This will return a tuple describing the result of the test.
488 This will return a tuple describing the result of the test.
489 """
489 """
490 replacements = self._getreplacements()
490 replacements = self._getreplacements()
491 env = self._getenv()
491 env = self._getenv()
492 self._daemonpids.append(env['DAEMON_PIDS'])
492 self._daemonpids.append(env['DAEMON_PIDS'])
493 self._createhgrc(env['HGRCPATH'])
493 self._createhgrc(env['HGRCPATH'])
494
494
495 vlog('# Test', self.name)
495 vlog('# Test', self.name)
496
496
497 ret, out = self._run(replacements, env)
497 ret, out = self._run(replacements, env)
498 self._finished = True
498 self._finished = True
499 self._ret = ret
499 self._ret = ret
500 self._out = out
500 self._out = out
501
501
502 def describe(ret):
502 def describe(ret):
503 if ret < 0:
503 if ret < 0:
504 return 'killed by signal: %d' % -ret
504 return 'killed by signal: %d' % -ret
505 return 'returned error code %d' % ret
505 return 'returned error code %d' % ret
506
506
507 self._skipped = False
507 self._skipped = False
508
508
509 if ret == self.SKIPPED_STATUS:
509 if ret == self.SKIPPED_STATUS:
510 if out is None: # Debug mode, nothing to parse.
510 if out is None: # Debug mode, nothing to parse.
511 missing = ['unknown']
511 missing = ['unknown']
512 failed = None
512 failed = None
513 else:
513 else:
514 missing, failed = TTest.parsehghaveoutput(out)
514 missing, failed = TTest.parsehghaveoutput(out)
515
515
516 if not missing:
516 if not missing:
517 missing = ['irrelevant']
517 missing = ['irrelevant']
518
518
519 if failed:
519 if failed:
520 self.fail('hg have failed checking for %s' % failed[-1])
520 self.fail('hg have failed checking for %s' % failed[-1])
521 else:
521 else:
522 self._skipped = True
522 self._skipped = True
523 raise SkipTest(missing[-1])
523 raise SkipTest(missing[-1])
524 elif ret == 'timeout':
524 elif ret == 'timeout':
525 self.fail('timed out')
525 self.fail('timed out')
526 elif ret is False:
526 elif ret is False:
527 raise WarnTest('no result code from test')
527 raise WarnTest('no result code from test')
528 elif out != self._refout:
528 elif out != self._refout:
529 # The result object handles diff calculation for us.
529 # The result object handles diff calculation for us.
530 self._result.addOutputMismatch(self, ret, out, self._refout)
530 self._result.addOutputMismatch(self, ret, out, self._refout)
531
531
532 if ret:
532 if ret:
533 msg = 'output changed and ' + describe(ret)
533 msg = 'output changed and ' + describe(ret)
534 else:
534 else:
535 msg = 'output changed'
535 msg = 'output changed'
536
536
537 if (ret != 0 or out != self._refout) and not self._skipped \
537 if (ret != 0 or out != self._refout) and not self._skipped \
538 and not self._debug:
538 and not self._debug:
539 f = open(self.errpath, 'wb')
539 f = open(self.errpath, 'wb')
540 for line in out:
540 for line in out:
541 f.write(line)
541 f.write(line)
542 f.close()
542 f.close()
543
543
544 self.fail(msg)
544 self.fail(msg)
545 elif ret:
545 elif ret:
546 self.fail(describe(ret))
546 self.fail(describe(ret))
547
547
548 def tearDown(self):
548 def tearDown(self):
549 """Tasks to perform after run()."""
549 """Tasks to perform after run()."""
550 for entry in self._daemonpids:
550 for entry in self._daemonpids:
551 killdaemons(entry)
551 killdaemons(entry)
552 self._daemonpids = []
552 self._daemonpids = []
553
553
554 if not self._keeptmpdir:
554 if not self._keeptmpdir:
555 shutil.rmtree(self._testtmp, True)
555 shutil.rmtree(self._testtmp, True)
556 shutil.rmtree(self._threadtmp, True)
556 shutil.rmtree(self._threadtmp, True)
557
557
558 if (self._ret != 0 or self._out != self._refout) and not self._skipped \
558 if (self._ret != 0 or self._out != self._refout) and not self._skipped \
559 and not self._debug and self._out:
559 and not self._debug and self._out:
560 f = open(self.errpath, 'wb')
560 f = open(self.errpath, 'wb')
561 for line in self._out:
561 for line in self._out:
562 f.write(line)
562 f.write(line)
563 f.close()
563 f.close()
564
564
565 vlog("# Ret was:", self._ret)
565 vlog("# Ret was:", self._ret)
566
566
567 def _run(self, replacements, env):
567 def _run(self, replacements, env):
568 # This should be implemented in child classes to run tests.
568 # This should be implemented in child classes to run tests.
569 raise SkipTest('unknown test type')
569 raise SkipTest('unknown test type')
570
570
571 def abort(self):
571 def abort(self):
572 """Terminate execution of this test."""
572 """Terminate execution of this test."""
573 self._aborted = True
573 self._aborted = True
574
574
575 def _getreplacements(self):
575 def _getreplacements(self):
576 r = [
576 r = [
577 (r':%s\b' % self._startport, ':$HGPORT'),
577 (r':%s\b' % self._startport, ':$HGPORT'),
578 (r':%s\b' % (self._startport + 1), ':$HGPORT1'),
578 (r':%s\b' % (self._startport + 1), ':$HGPORT1'),
579 (r':%s\b' % (self._startport + 2), ':$HGPORT2'),
579 (r':%s\b' % (self._startport + 2), ':$HGPORT2'),
580 ]
580 ]
581
581
582 if os.name == 'nt':
582 if os.name == 'nt':
583 r.append(
583 r.append(
584 (''.join(c.isalpha() and '[%s%s]' % (c.lower(), c.upper()) or
584 (''.join(c.isalpha() and '[%s%s]' % (c.lower(), c.upper()) or
585 c in '/\\' and r'[/\\]' or c.isdigit() and c or '\\' + c
585 c in '/\\' and r'[/\\]' or c.isdigit() and c or '\\' + c
586 for c in self._testtmp), '$TESTTMP'))
586 for c in self._testtmp), '$TESTTMP'))
587 else:
587 else:
588 r.append((re.escape(self._testtmp), '$TESTTMP'))
588 r.append((re.escape(self._testtmp), '$TESTTMP'))
589
589
590 return r
590 return r
591
591
592 def _getenv(self):
592 def _getenv(self):
593 env = os.environ.copy()
593 env = os.environ.copy()
594 env['TESTTMP'] = self._testtmp
594 env['TESTTMP'] = self._testtmp
595 env['HOME'] = self._testtmp
595 env['HOME'] = self._testtmp
596 env["HGPORT"] = str(self._startport)
596 env["HGPORT"] = str(self._startport)
597 env["HGPORT1"] = str(self._startport + 1)
597 env["HGPORT1"] = str(self._startport + 1)
598 env["HGPORT2"] = str(self._startport + 2)
598 env["HGPORT2"] = str(self._startport + 2)
599 env["HGRCPATH"] = os.path.join(self._threadtmp, '.hgrc')
599 env["HGRCPATH"] = os.path.join(self._threadtmp, '.hgrc')
600 env["DAEMON_PIDS"] = os.path.join(self._threadtmp, 'daemon.pids')
600 env["DAEMON_PIDS"] = os.path.join(self._threadtmp, 'daemon.pids')
601 env["HGEDITOR"] = sys.executable + ' -c "import sys; sys.exit(0)"'
601 env["HGEDITOR"] = sys.executable + ' -c "import sys; sys.exit(0)"'
602 env["HGMERGE"] = "internal:merge"
602 env["HGMERGE"] = "internal:merge"
603 env["HGUSER"] = "test"
603 env["HGUSER"] = "test"
604 env["HGENCODING"] = "ascii"
604 env["HGENCODING"] = "ascii"
605 env["HGENCODINGMODE"] = "strict"
605 env["HGENCODINGMODE"] = "strict"
606
606
607 # Reset some environment variables to well-known values so that
607 # Reset some environment variables to well-known values so that
608 # the tests produce repeatable output.
608 # the tests produce repeatable output.
609 env['LANG'] = env['LC_ALL'] = env['LANGUAGE'] = 'C'
609 env['LANG'] = env['LC_ALL'] = env['LANGUAGE'] = 'C'
610 env['TZ'] = 'GMT'
610 env['TZ'] = 'GMT'
611 env["EMAIL"] = "Foo Bar <foo.bar@example.com>"
611 env["EMAIL"] = "Foo Bar <foo.bar@example.com>"
612 env['COLUMNS'] = '80'
612 env['COLUMNS'] = '80'
613 env['TERM'] = 'xterm'
613 env['TERM'] = 'xterm'
614
614
615 for k in ('HG HGPROF CDPATH GREP_OPTIONS http_proxy no_proxy ' +
615 for k in ('HG HGPROF CDPATH GREP_OPTIONS http_proxy no_proxy ' +
616 'NO_PROXY').split():
616 'NO_PROXY').split():
617 if k in env:
617 if k in env:
618 del env[k]
618 del env[k]
619
619
620 # unset env related to hooks
620 # unset env related to hooks
621 for k in env.keys():
621 for k in env.keys():
622 if k.startswith('HG_'):
622 if k.startswith('HG_'):
623 del env[k]
623 del env[k]
624
624
625 return env
625 return env
626
626
627 def _createhgrc(self, path):
627 def _createhgrc(self, path):
628 # create a fresh hgrc
628 # create a fresh hgrc
629 hgrc = open(path, 'w')
629 hgrc = open(path, 'w')
630 hgrc.write('[ui]\n')
630 hgrc.write('[ui]\n')
631 hgrc.write('slash = True\n')
631 hgrc.write('slash = True\n')
632 hgrc.write('interactive = False\n')
632 hgrc.write('interactive = False\n')
633 hgrc.write('[defaults]\n')
633 hgrc.write('[defaults]\n')
634 hgrc.write('backout = -d "0 0"\n')
634 hgrc.write('backout = -d "0 0"\n')
635 hgrc.write('commit = -d "0 0"\n')
635 hgrc.write('commit = -d "0 0"\n')
636 hgrc.write('shelve = --date "0 0"\n')
636 hgrc.write('shelve = --date "0 0"\n')
637 hgrc.write('tag = -d "0 0"\n')
637 hgrc.write('tag = -d "0 0"\n')
638 for opt in self._extraconfigopts:
638 for opt in self._extraconfigopts:
639 section, key = opt.split('.', 1)
639 section, key = opt.split('.', 1)
640 assert '=' in key, ('extra config opt %s must '
640 assert '=' in key, ('extra config opt %s must '
641 'have an = for assignment' % opt)
641 'have an = for assignment' % opt)
642 hgrc.write('[%s]\n%s\n' % (section, key))
642 hgrc.write('[%s]\n%s\n' % (section, key))
643 hgrc.close()
643 hgrc.close()
644
644
645 def fail(self, msg):
645 def fail(self, msg):
646 # unittest differentiates between errored and failed.
646 # unittest differentiates between errored and failed.
647 # Failed is denoted by AssertionError (by default at least).
647 # Failed is denoted by AssertionError (by default at least).
648 raise AssertionError(msg)
648 raise AssertionError(msg)
649
649
650 class PythonTest(Test):
650 class PythonTest(Test):
651 """A Python-based test."""
651 """A Python-based test."""
652
652
653 @property
653 @property
654 def refpath(self):
654 def refpath(self):
655 return os.path.join(self._testdir, '%s.out' % self.name)
655 return os.path.join(self._testdir, '%s.out' % self.name)
656
656
657 def _run(self, replacements, env):
657 def _run(self, replacements, env):
658 py3kswitch = self._py3kwarnings and ' -3' or ''
658 py3kswitch = self._py3kwarnings and ' -3' or ''
659 cmd = '%s%s "%s"' % (PYTHON, py3kswitch, self.path)
659 cmd = '%s%s "%s"' % (PYTHON, py3kswitch, self.path)
660 vlog("# Running", cmd)
660 vlog("# Running", cmd)
661 if os.name == 'nt':
661 if os.name == 'nt':
662 replacements.append((r'\r\n', '\n'))
662 replacements.append((r'\r\n', '\n'))
663 result = run(cmd, self._testtmp, replacements, env,
663 result = run(cmd, self._testtmp, replacements, env,
664 debug=self._debug, timeout=self._timeout)
664 debug=self._debug, timeout=self._timeout)
665 if self._aborted:
665 if self._aborted:
666 raise KeyboardInterrupt()
666 raise KeyboardInterrupt()
667
667
668 return result
668 return result
669
669
670 class TTest(Test):
670 class TTest(Test):
671 """A "t test" is a test backed by a .t file."""
671 """A "t test" is a test backed by a .t file."""
672
672
673 SKIPPED_PREFIX = 'skipped: '
673 SKIPPED_PREFIX = 'skipped: '
674 FAILED_PREFIX = 'hghave check failed: '
674 FAILED_PREFIX = 'hghave check failed: '
675 NEEDESCAPE = re.compile(r'[\x00-\x08\x0b-\x1f\x7f-\xff]').search
675 NEEDESCAPE = re.compile(r'[\x00-\x08\x0b-\x1f\x7f-\xff]').search
676
676
677 ESCAPESUB = re.compile(r'[\x00-\x08\x0b-\x1f\\\x7f-\xff]').sub
677 ESCAPESUB = re.compile(r'[\x00-\x08\x0b-\x1f\\\x7f-\xff]').sub
678 ESCAPEMAP = dict((chr(i), r'\x%02x' % i) for i in range(256)).update(
678 ESCAPEMAP = dict((chr(i), r'\x%02x' % i) for i in range(256)).update(
679 {'\\': '\\\\', '\r': r'\r'})
679 {'\\': '\\\\', '\r': r'\r'})
680
680
681 @property
681 @property
682 def refpath(self):
682 def refpath(self):
683 return os.path.join(self._testdir, self.name)
683 return os.path.join(self._testdir, self.name)
684
684
685 def _run(self, replacements, env):
685 def _run(self, replacements, env):
686 f = open(self.path)
686 f = open(self.path)
687 lines = f.readlines()
687 lines = f.readlines()
688 f.close()
688 f.close()
689
689
690 salt, script, after, expected = self._parsetest(lines)
690 salt, script, after, expected = self._parsetest(lines)
691
691
692 # Write out the generated script.
692 # Write out the generated script.
693 fname = '%s.sh' % self._testtmp
693 fname = '%s.sh' % self._testtmp
694 f = open(fname, 'w')
694 f = open(fname, 'w')
695 for l in script:
695 for l in script:
696 f.write(l)
696 f.write(l)
697 f.close()
697 f.close()
698
698
699 cmd = '%s "%s"' % (self._shell, fname)
699 cmd = '%s "%s"' % (self._shell, fname)
700 vlog("# Running", cmd)
700 vlog("# Running", cmd)
701
701
702 exitcode, output = run(cmd, self._testtmp, replacements, env,
702 exitcode, output = run(cmd, self._testtmp, replacements, env,
703 debug=self._debug, timeout=self._timeout)
703 debug=self._debug, timeout=self._timeout)
704
704
705 if self._aborted:
705 if self._aborted:
706 raise KeyboardInterrupt()
706 raise KeyboardInterrupt()
707
707
708 # Do not merge output if skipped. Return hghave message instead.
708 # Do not merge output if skipped. Return hghave message instead.
709 # Similarly, with --debug, output is None.
709 # Similarly, with --debug, output is None.
710 if exitcode == self.SKIPPED_STATUS or output is None:
710 if exitcode == self.SKIPPED_STATUS or output is None:
711 return exitcode, output
711 return exitcode, output
712
712
713 return self._processoutput(exitcode, output, salt, after, expected)
713 return self._processoutput(exitcode, output, salt, after, expected)
714
714
715 def _hghave(self, reqs):
715 def _hghave(self, reqs):
716 # TODO do something smarter when all other uses of hghave are gone.
716 # TODO do something smarter when all other uses of hghave are gone.
717 tdir = self._testdir.replace('\\', '/')
717 tdir = self._testdir.replace('\\', '/')
718 proc = Popen4('%s -c "%s/hghave %s"' %
718 proc = Popen4('%s -c "%s/hghave %s"' %
719 (self._shell, tdir, ' '.join(reqs)),
719 (self._shell, tdir, ' '.join(reqs)),
720 self._testtmp, 0)
720 self._testtmp, 0)
721 stdout, stderr = proc.communicate()
721 stdout, stderr = proc.communicate()
722 ret = proc.wait()
722 ret = proc.wait()
723 if wifexited(ret):
723 if wifexited(ret):
724 ret = os.WEXITSTATUS(ret)
724 ret = os.WEXITSTATUS(ret)
725 if ret == 2:
725 if ret == 2:
726 print stdout
726 print stdout
727 sys.exit(1)
727 sys.exit(1)
728
728
729 return ret == 0
729 return ret == 0
730
730
731 def _parsetest(self, lines):
731 def _parsetest(self, lines):
732 # We generate a shell script which outputs unique markers to line
732 # We generate a shell script which outputs unique markers to line
733 # up script results with our source. These markers include input
733 # up script results with our source. These markers include input
734 # line number and the last return code.
734 # line number and the last return code.
735 salt = "SALT" + str(time.time())
735 salt = "SALT" + str(time.time())
736 def addsalt(line, inpython):
736 def addsalt(line, inpython):
737 if inpython:
737 if inpython:
738 script.append('%s %d 0\n' % (salt, line))
738 script.append('%s %d 0\n' % (salt, line))
739 else:
739 else:
740 script.append('echo %s %s $?\n' % (salt, line))
740 script.append('echo %s %s $?\n' % (salt, line))
741
741
742 script = []
742 script = []
743
743
744 # After we run the shell script, we re-unify the script output
744 # After we run the shell script, we re-unify the script output
745 # with non-active parts of the source, with synchronization by our
745 # with non-active parts of the source, with synchronization by our
746 # SALT line number markers. The after table contains the non-active
746 # SALT line number markers. The after table contains the non-active
747 # components, ordered by line number.
747 # components, ordered by line number.
748 after = {}
748 after = {}
749
749
750 # Expected shell script output.
750 # Expected shell script output.
751 expected = {}
751 expected = {}
752
752
753 pos = prepos = -1
753 pos = prepos = -1
754
754
755 # True or False when in a true or false conditional section
755 # True or False when in a true or false conditional section
756 skipping = None
756 skipping = None
757
757
758 # We keep track of whether or not we're in a Python block so we
758 # We keep track of whether or not we're in a Python block so we
759 # can generate the surrounding doctest magic.
759 # can generate the surrounding doctest magic.
760 inpython = False
760 inpython = False
761
761
762 if self._debug:
762 if self._debug:
763 script.append('set -x\n')
763 script.append('set -x\n')
764 if os.getenv('MSYSTEM'):
764 if os.getenv('MSYSTEM'):
765 script.append('alias pwd="pwd -W"\n')
765 script.append('alias pwd="pwd -W"\n')
766
766
767 for n, l in enumerate(lines):
767 for n, l in enumerate(lines):
768 if not l.endswith('\n'):
768 if not l.endswith('\n'):
769 l += '\n'
769 l += '\n'
770 if l.startswith('#if'):
770 if l.startswith('#if'):
771 lsplit = l.split()
771 lsplit = l.split()
772 if len(lsplit) < 2 or lsplit[0] != '#if':
772 if len(lsplit) < 2 or lsplit[0] != '#if':
773 after.setdefault(pos, []).append(' !!! invalid #if\n')
773 after.setdefault(pos, []).append(' !!! invalid #if\n')
774 if skipping is not None:
774 if skipping is not None:
775 after.setdefault(pos, []).append(' !!! nested #if\n')
775 after.setdefault(pos, []).append(' !!! nested #if\n')
776 skipping = not self._hghave(lsplit[1:])
776 skipping = not self._hghave(lsplit[1:])
777 after.setdefault(pos, []).append(l)
777 after.setdefault(pos, []).append(l)
778 elif l.startswith('#else'):
778 elif l.startswith('#else'):
779 if skipping is None:
779 if skipping is None:
780 after.setdefault(pos, []).append(' !!! missing #if\n')
780 after.setdefault(pos, []).append(' !!! missing #if\n')
781 skipping = not skipping
781 skipping = not skipping
782 after.setdefault(pos, []).append(l)
782 after.setdefault(pos, []).append(l)
783 elif l.startswith('#endif'):
783 elif l.startswith('#endif'):
784 if skipping is None:
784 if skipping is None:
785 after.setdefault(pos, []).append(' !!! missing #if\n')
785 after.setdefault(pos, []).append(' !!! missing #if\n')
786 skipping = None
786 skipping = None
787 after.setdefault(pos, []).append(l)
787 after.setdefault(pos, []).append(l)
788 elif skipping:
788 elif skipping:
789 after.setdefault(pos, []).append(l)
789 after.setdefault(pos, []).append(l)
790 elif l.startswith(' >>> '): # python inlines
790 elif l.startswith(' >>> '): # python inlines
791 after.setdefault(pos, []).append(l)
791 after.setdefault(pos, []).append(l)
792 prepos = pos
792 prepos = pos
793 pos = n
793 pos = n
794 if not inpython:
794 if not inpython:
795 # We've just entered a Python block. Add the header.
795 # We've just entered a Python block. Add the header.
796 inpython = True
796 inpython = True
797 addsalt(prepos, False) # Make sure we report the exit code.
797 addsalt(prepos, False) # Make sure we report the exit code.
798 script.append('%s -m heredoctest <<EOF\n' % PYTHON)
798 script.append('%s -m heredoctest <<EOF\n' % PYTHON)
799 addsalt(n, True)
799 addsalt(n, True)
800 script.append(l[2:])
800 script.append(l[2:])
801 elif l.startswith(' ... '): # python inlines
801 elif l.startswith(' ... '): # python inlines
802 after.setdefault(prepos, []).append(l)
802 after.setdefault(prepos, []).append(l)
803 script.append(l[2:])
803 script.append(l[2:])
804 elif l.startswith(' $ '): # commands
804 elif l.startswith(' $ '): # commands
805 if inpython:
805 if inpython:
806 script.append('EOF\n')
806 script.append('EOF\n')
807 inpython = False
807 inpython = False
808 after.setdefault(pos, []).append(l)
808 after.setdefault(pos, []).append(l)
809 prepos = pos
809 prepos = pos
810 pos = n
810 pos = n
811 addsalt(n, False)
811 addsalt(n, False)
812 cmd = l[4:].split()
812 cmd = l[4:].split()
813 if len(cmd) == 2 and cmd[0] == 'cd':
813 if len(cmd) == 2 and cmd[0] == 'cd':
814 l = ' $ cd %s || exit 1\n' % cmd[1]
814 l = ' $ cd %s || exit 1\n' % cmd[1]
815 script.append(l[4:])
815 script.append(l[4:])
816 elif l.startswith(' > '): # continuations
816 elif l.startswith(' > '): # continuations
817 after.setdefault(prepos, []).append(l)
817 after.setdefault(prepos, []).append(l)
818 script.append(l[4:])
818 script.append(l[4:])
819 elif l.startswith(' '): # results
819 elif l.startswith(' '): # results
820 # Queue up a list of expected results.
820 # Queue up a list of expected results.
821 expected.setdefault(pos, []).append(l[2:])
821 expected.setdefault(pos, []).append(l[2:])
822 else:
822 else:
823 if inpython:
823 if inpython:
824 script.append('EOF\n')
824 script.append('EOF\n')
825 inpython = False
825 inpython = False
826 # Non-command/result. Queue up for merged output.
826 # Non-command/result. Queue up for merged output.
827 after.setdefault(pos, []).append(l)
827 after.setdefault(pos, []).append(l)
828
828
829 if inpython:
829 if inpython:
830 script.append('EOF\n')
830 script.append('EOF\n')
831 if skipping is not None:
831 if skipping is not None:
832 after.setdefault(pos, []).append(' !!! missing #endif\n')
832 after.setdefault(pos, []).append(' !!! missing #endif\n')
833 addsalt(n + 1, False)
833 addsalt(n + 1, False)
834
834
835 return salt, script, after, expected
835 return salt, script, after, expected
836
836
837 def _processoutput(self, exitcode, output, salt, after, expected):
837 def _processoutput(self, exitcode, output, salt, after, expected):
838 # Merge the script output back into a unified test.
838 # Merge the script output back into a unified test.
839 warnonly = 1 # 1: not yet; 2: yes; 3: for sure not
839 warnonly = 1 # 1: not yet; 2: yes; 3: for sure not
840 if exitcode != 0:
840 if exitcode != 0:
841 warnonly = 3
841 warnonly = 3
842
842
843 pos = -1
843 pos = -1
844 postout = []
844 postout = []
845 for l in output:
845 for l in output:
846 lout, lcmd = l, None
846 lout, lcmd = l, None
847 if salt in l:
847 if salt in l:
848 lout, lcmd = l.split(salt, 1)
848 lout, lcmd = l.split(salt, 1)
849
849
850 if lout:
850 if lout:
851 if not lout.endswith('\n'):
851 if not lout.endswith('\n'):
852 lout += ' (no-eol)\n'
852 lout += ' (no-eol)\n'
853
853
854 # Find the expected output at the current position.
854 # Find the expected output at the current position.
855 el = None
855 el = None
856 if expected.get(pos, None):
856 if expected.get(pos, None):
857 el = expected[pos].pop(0)
857 el = expected[pos].pop(0)
858
858
859 r = TTest.linematch(el, lout)
859 r = TTest.linematch(el, lout)
860 if isinstance(r, str):
860 if isinstance(r, str):
861 if r == '+glob':
861 if r == '+glob':
862 lout = el[:-1] + ' (glob)\n'
862 lout = el[:-1] + ' (glob)\n'
863 r = '' # Warn only this line.
863 r = '' # Warn only this line.
864 elif r == '-glob':
864 elif r == '-glob':
865 lout = ''.join(el.rsplit(' (glob)', 1))
865 lout = ''.join(el.rsplit(' (glob)', 1))
866 r = '' # Warn only this line.
866 r = '' # Warn only this line.
867 else:
867 else:
868 log('\ninfo, unknown linematch result: %r\n' % r)
868 log('\ninfo, unknown linematch result: %r\n' % r)
869 r = False
869 r = False
870 if r:
870 if r:
871 postout.append(' ' + el)
871 postout.append(' ' + el)
872 else:
872 else:
873 if self.NEEDESCAPE(lout):
873 if self.NEEDESCAPE(lout):
874 lout = TTest.stringescape('%s (esc)\n' %
874 lout = TTest.stringescape('%s (esc)\n' %
875 lout.rstrip('\n'))
875 lout.rstrip('\n'))
876 postout.append(' ' + lout) # Let diff deal with it.
876 postout.append(' ' + lout) # Let diff deal with it.
877 if r != '': # If line failed.
877 if r != '': # If line failed.
878 warnonly = 3 # for sure not
878 warnonly = 3 # for sure not
879 elif warnonly == 1: # Is "not yet" and line is warn only.
879 elif warnonly == 1: # Is "not yet" and line is warn only.
880 warnonly = 2 # Yes do warn.
880 warnonly = 2 # Yes do warn.
881
881
882 if lcmd:
882 if lcmd:
883 # Add on last return code.
883 # Add on last return code.
884 ret = int(lcmd.split()[1])
884 ret = int(lcmd.split()[1])
885 if ret != 0:
885 if ret != 0:
886 postout.append(' [%s]\n' % ret)
886 postout.append(' [%s]\n' % ret)
887 if pos in after:
887 if pos in after:
888 # Merge in non-active test bits.
888 # Merge in non-active test bits.
889 postout += after.pop(pos)
889 postout += after.pop(pos)
890 pos = int(lcmd.split()[0])
890 pos = int(lcmd.split()[0])
891
891
892 if pos in after:
892 if pos in after:
893 postout += after.pop(pos)
893 postout += after.pop(pos)
894
894
895 if warnonly == 2:
895 if warnonly == 2:
896 exitcode = False # Set exitcode to warned.
896 exitcode = False # Set exitcode to warned.
897
897
898 return exitcode, postout
898 return exitcode, postout
899
899
900 @staticmethod
900 @staticmethod
901 def rematch(el, l):
901 def rematch(el, l):
902 try:
902 try:
903 # use \Z to ensure that the regex matches to the end of the string
903 # use \Z to ensure that the regex matches to the end of the string
904 if os.name == 'nt':
904 if os.name == 'nt':
905 return re.match(el + r'\r?\n\Z', l)
905 return re.match(el + r'\r?\n\Z', l)
906 return re.match(el + r'\n\Z', l)
906 return re.match(el + r'\n\Z', l)
907 except re.error:
907 except re.error:
908 # el is an invalid regex
908 # el is an invalid regex
909 return False
909 return False
910
910
911 @staticmethod
911 @staticmethod
912 def globmatch(el, l):
912 def globmatch(el, l):
913 # The only supported special characters are * and ? plus / which also
913 # The only supported special characters are * and ? plus / which also
914 # matches \ on windows. Escaping of these characters is supported.
914 # matches \ on windows. Escaping of these characters is supported.
915 if el + '\n' == l:
915 if el + '\n' == l:
916 if os.altsep:
916 if os.altsep:
917 # matching on "/" is not needed for this line
917 # matching on "/" is not needed for this line
918 return '-glob'
918 return '-glob'
919 return True
919 return True
920 i, n = 0, len(el)
920 i, n = 0, len(el)
921 res = ''
921 res = ''
922 while i < n:
922 while i < n:
923 c = el[i]
923 c = el[i]
924 i += 1
924 i += 1
925 if c == '\\' and el[i] in '*?\\/':
925 if c == '\\' and el[i] in '*?\\/':
926 res += el[i - 1:i + 1]
926 res += el[i - 1:i + 1]
927 i += 1
927 i += 1
928 elif c == '*':
928 elif c == '*':
929 res += '.*'
929 res += '.*'
930 elif c == '?':
930 elif c == '?':
931 res += '.'
931 res += '.'
932 elif c == '/' and os.altsep:
932 elif c == '/' and os.altsep:
933 res += '[/\\\\]'
933 res += '[/\\\\]'
934 else:
934 else:
935 res += re.escape(c)
935 res += re.escape(c)
936 return TTest.rematch(res, l)
936 return TTest.rematch(res, l)
937
937
938 @staticmethod
938 @staticmethod
939 def linematch(el, l):
939 def linematch(el, l):
940 if el == l: # perfect match (fast)
940 if el == l: # perfect match (fast)
941 return True
941 return True
942 if el:
942 if el:
943 if el.endswith(" (esc)\n"):
943 if el.endswith(" (esc)\n"):
944 el = el[:-7].decode('string-escape') + '\n'
944 el = el[:-7].decode('string-escape') + '\n'
945 if el == l or os.name == 'nt' and el[:-1] + '\r\n' == l:
945 if el == l or os.name == 'nt' and el[:-1] + '\r\n' == l:
946 return True
946 return True
947 if el.endswith(" (re)\n"):
947 if el.endswith(" (re)\n"):
948 return TTest.rematch(el[:-6], l)
948 return TTest.rematch(el[:-6], l)
949 if el.endswith(" (glob)\n"):
949 if el.endswith(" (glob)\n"):
950 return TTest.globmatch(el[:-8], l)
950 return TTest.globmatch(el[:-8], l)
951 if os.altsep and l.replace('\\', '/') == el:
951 if os.altsep and l.replace('\\', '/') == el:
952 return '+glob'
952 return '+glob'
953 return False
953 return False
954
954
955 @staticmethod
955 @staticmethod
956 def parsehghaveoutput(lines):
956 def parsehghaveoutput(lines):
957 '''Parse hghave log lines.
957 '''Parse hghave log lines.
958
958
959 Return tuple of lists (missing, failed):
959 Return tuple of lists (missing, failed):
960 * the missing/unknown features
960 * the missing/unknown features
961 * the features for which existence check failed'''
961 * the features for which existence check failed'''
962 missing = []
962 missing = []
963 failed = []
963 failed = []
964 for line in lines:
964 for line in lines:
965 if line.startswith(TTest.SKIPPED_PREFIX):
965 if line.startswith(TTest.SKIPPED_PREFIX):
966 line = line.splitlines()[0]
966 line = line.splitlines()[0]
967 missing.append(line[len(TTest.SKIPPED_PREFIX):])
967 missing.append(line[len(TTest.SKIPPED_PREFIX):])
968 elif line.startswith(TTest.FAILED_PREFIX):
968 elif line.startswith(TTest.FAILED_PREFIX):
969 line = line.splitlines()[0]
969 line = line.splitlines()[0]
970 failed.append(line[len(TTest.FAILED_PREFIX):])
970 failed.append(line[len(TTest.FAILED_PREFIX):])
971
971
972 return missing, failed
972 return missing, failed
973
973
974 @staticmethod
974 @staticmethod
975 def _escapef(m):
975 def _escapef(m):
976 return TTest.ESCAPEMAP[m.group(0)]
976 return TTest.ESCAPEMAP[m.group(0)]
977
977
978 @staticmethod
978 @staticmethod
979 def _stringescape(s):
979 def _stringescape(s):
980 return TTest.ESCAPESUB(TTest._escapef, s)
980 return TTest.ESCAPESUB(TTest._escapef, s)
981
981
982
982
983 wifexited = getattr(os, "WIFEXITED", lambda x: False)
983 wifexited = getattr(os, "WIFEXITED", lambda x: False)
984 def run(cmd, wd, replacements, env, debug=False, timeout=None):
984 def run(cmd, wd, replacements, env, debug=False, timeout=None):
985 """Run command in a sub-process, capturing the output (stdout and stderr).
985 """Run command in a sub-process, capturing the output (stdout and stderr).
986 Return a tuple (exitcode, output). output is None in debug mode."""
986 Return a tuple (exitcode, output). output is None in debug mode."""
987 if debug:
987 if debug:
988 proc = subprocess.Popen(cmd, shell=True, cwd=wd, env=env)
988 proc = subprocess.Popen(cmd, shell=True, cwd=wd, env=env)
989 ret = proc.wait()
989 ret = proc.wait()
990 return (ret, None)
990 return (ret, None)
991
991
992 proc = Popen4(cmd, wd, timeout, env)
992 proc = Popen4(cmd, wd, timeout, env)
993 def cleanup():
993 def cleanup():
994 terminate(proc)
994 terminate(proc)
995 ret = proc.wait()
995 ret = proc.wait()
996 if ret == 0:
996 if ret == 0:
997 ret = signal.SIGTERM << 8
997 ret = signal.SIGTERM << 8
998 killdaemons(env['DAEMON_PIDS'])
998 killdaemons(env['DAEMON_PIDS'])
999 return ret
999 return ret
1000
1000
1001 output = ''
1001 output = ''
1002 proc.tochild.close()
1002 proc.tochild.close()
1003
1003
1004 try:
1004 try:
1005 output = proc.fromchild.read()
1005 output = proc.fromchild.read()
1006 except KeyboardInterrupt:
1006 except KeyboardInterrupt:
1007 vlog('# Handling keyboard interrupt')
1007 vlog('# Handling keyboard interrupt')
1008 cleanup()
1008 cleanup()
1009 raise
1009 raise
1010
1010
1011 ret = proc.wait()
1011 ret = proc.wait()
1012 if wifexited(ret):
1012 if wifexited(ret):
1013 ret = os.WEXITSTATUS(ret)
1013 ret = os.WEXITSTATUS(ret)
1014
1014
1015 if proc.timeout:
1015 if proc.timeout:
1016 ret = 'timeout'
1016 ret = 'timeout'
1017
1017
1018 if ret:
1018 if ret:
1019 killdaemons(env['DAEMON_PIDS'])
1019 killdaemons(env['DAEMON_PIDS'])
1020
1020
1021 for s, r in replacements:
1021 for s, r in replacements:
1022 output = re.sub(s, r, output)
1022 output = re.sub(s, r, output)
1023 return ret, output.splitlines(True)
1023 return ret, output.splitlines(True)
1024
1024
1025 iolock = threading.Lock()
1025 iolock = threading.Lock()
1026
1026
1027 class SkipTest(Exception):
1027 class SkipTest(Exception):
1028 """Raised to indicate that a test is to be skipped."""
1028 """Raised to indicate that a test is to be skipped."""
1029
1029
1030 class IgnoreTest(Exception):
1030 class IgnoreTest(Exception):
1031 """Raised to indicate that a test is to be ignored."""
1031 """Raised to indicate that a test is to be ignored."""
1032
1032
1033 class WarnTest(Exception):
1033 class WarnTest(Exception):
1034 """Raised to indicate that a test warned."""
1034 """Raised to indicate that a test warned."""
1035
1035
1036 class TestResult(unittest._TextTestResult):
1036 class TestResult(unittest._TextTestResult):
1037 """Holds results when executing via unittest."""
1037 """Holds results when executing via unittest."""
1038 # Don't worry too much about accessing the non-public _TextTestResult.
1038 # Don't worry too much about accessing the non-public _TextTestResult.
1039 # It is relatively common in Python testing tools.
1039 # It is relatively common in Python testing tools.
1040 def __init__(self, options, *args, **kwargs):
1040 def __init__(self, options, *args, **kwargs):
1041 super(TestResult, self).__init__(*args, **kwargs)
1041 super(TestResult, self).__init__(*args, **kwargs)
1042
1042
1043 self._options = options
1043 self._options = options
1044
1044
1045 # unittest.TestResult didn't have skipped until 2.7. We need to
1045 # unittest.TestResult didn't have skipped until 2.7. We need to
1046 # polyfill it.
1046 # polyfill it.
1047 self.skipped = []
1047 self.skipped = []
1048
1048
1049 # We have a custom "ignored" result that isn't present in any Python
1049 # We have a custom "ignored" result that isn't present in any Python
1050 # unittest implementation. It is very similar to skipped. It may make
1050 # unittest implementation. It is very similar to skipped. It may make
1051 # sense to map it into skip some day.
1051 # sense to map it into skip some day.
1052 self.ignored = []
1052 self.ignored = []
1053
1053
1054 # We have a custom "warned" result that isn't present in any Python
1054 # We have a custom "warned" result that isn't present in any Python
1055 # unittest implementation. It is very similar to failed. It may make
1055 # unittest implementation. It is very similar to failed. It may make
1056 # sense to map it into fail some day.
1056 # sense to map it into fail some day.
1057 self.warned = []
1057 self.warned = []
1058
1058
1059 self.times = []
1059 self.times = []
1060 self._started = {}
1060 self._started = {}
1061
1061
1062 def addFailure(self, test, reason):
1062 def addFailure(self, test, reason):
1063 self.failures.append((test, reason))
1063 self.failures.append((test, reason))
1064
1064
1065 if self._options.first:
1065 if self._options.first:
1066 self.stop()
1066 self.stop()
1067
1067
1068 def addError(self, *args, **kwargs):
1068 def addError(self, *args, **kwargs):
1069 super(TestResult, self).addError(*args, **kwargs)
1069 super(TestResult, self).addError(*args, **kwargs)
1070
1070
1071 if self._options.first:
1071 if self._options.first:
1072 self.stop()
1072 self.stop()
1073
1073
1074 # Polyfill.
1074 # Polyfill.
1075 def addSkip(self, test, reason):
1075 def addSkip(self, test, reason):
1076 self.skipped.append((test, reason))
1076 self.skipped.append((test, reason))
1077
1077
1078 if self.showAll:
1078 if self.showAll:
1079 self.stream.writeln('skipped %s' % reason)
1079 self.stream.writeln('skipped %s' % reason)
1080 else:
1080 else:
1081 self.stream.write('s')
1081 self.stream.write('s')
1082 self.stream.flush()
1082 self.stream.flush()
1083
1083
1084 def addIgnore(self, test, reason):
1084 def addIgnore(self, test, reason):
1085 self.ignored.append((test, reason))
1085 self.ignored.append((test, reason))
1086
1086
1087 if self.showAll:
1087 if self.showAll:
1088 self.stream.writeln('ignored %s' % reason)
1088 self.stream.writeln('ignored %s' % reason)
1089 else:
1089 else:
1090 self.stream.write('i')
1090 self.stream.write('i')
1091 self.stream.flush()
1091 self.stream.flush()
1092
1092
1093 def addWarn(self, test, reason):
1093 def addWarn(self, test, reason):
1094 self.warned.append((test, reason))
1094 self.warned.append((test, reason))
1095
1095
1096 if self._options.first:
1096 if self._options.first:
1097 self.stop()
1097 self.stop()
1098
1098
1099 if self.showAll:
1099 if self.showAll:
1100 self.stream.writeln('warned %s' % reason)
1100 self.stream.writeln('warned %s' % reason)
1101 else:
1101 else:
1102 self.stream.write('~')
1102 self.stream.write('~')
1103 self.stream.flush()
1103 self.stream.flush()
1104
1104
1105 def addOutputMismatch(self, test, ret, got, expected):
1105 def addOutputMismatch(self, test, ret, got, expected):
1106 """Record a mismatch in test output for a particular test."""
1106 """Record a mismatch in test output for a particular test."""
1107
1107
1108 if self._options.nodiff:
1108 if self._options.nodiff:
1109 return
1109 return
1110
1110
1111 if self._options.view:
1111 if self._options.view:
1112 os.system("%s %s %s" % (self._view, test.refpath, test.errpath))
1112 os.system("%s %s %s" % (self._view, test.refpath, test.errpath))
1113 else:
1113 else:
1114 failed, lines = getdiff(expected, got,
1114 failed, lines = getdiff(expected, got,
1115 test.refpath, test.errpath)
1115 test.refpath, test.errpath)
1116 if failed:
1116 if failed:
1117 self.addFailure(test, 'diff generation failed')
1117 self.addFailure(test, 'diff generation failed')
1118 else:
1118 else:
1119 self.stream.write('\n')
1119 self.stream.write('\n')
1120 for line in lines:
1120 for line in lines:
1121 self.stream.write(line)
1121 self.stream.write(line)
1122 self.stream.flush()
1122 self.stream.flush()
1123
1123
1124 if ret or not self._options.interactive or \
1124 if ret or not self._options.interactive or \
1125 not os.path.exists(test.errpath):
1125 not os.path.exists(test.errpath):
1126 return
1126 return
1127
1127
1128 iolock.acquire()
1128 iolock.acquire()
1129 print 'Accept this change? [n] ',
1129 print 'Accept this change? [n] ',
1130 answer = sys.stdin.readline().strip()
1130 answer = sys.stdin.readline().strip()
1131 iolock.release()
1131 iolock.release()
1132 if answer.lower() in ('y', 'yes'):
1132 if answer.lower() in ('y', 'yes'):
1133 if test.name.endswith('.t'):
1133 if test.name.endswith('.t'):
1134 rename(test.errpath, test.path)
1134 rename(test.errpath, test.path)
1135 else:
1135 else:
1136 rename(test.errpath, '%s.out' % test.path)
1136 rename(test.errpath, '%s.out' % test.path)
1137
1137
1138 def startTest(self, test):
1138 def startTest(self, test):
1139 super(TestResult, self).startTest(test)
1139 super(TestResult, self).startTest(test)
1140
1140
1141 self._started[test.name] = time.time()
1141 self._started[test.name] = time.time()
1142
1142
1143 def stopTest(self, test, interrupted=False):
1143 def stopTest(self, test, interrupted=False):
1144 super(TestResult, self).stopTest(test)
1144 super(TestResult, self).stopTest(test)
1145
1145
1146 self.times.append((test.name, time.time() - self._started[test.name]))
1146 self.times.append((test.name, time.time() - self._started[test.name]))
1147 del self._started[test.name]
1147 del self._started[test.name]
1148
1148
1149 if interrupted:
1149 if interrupted:
1150 self.stream.writeln('INTERRUPTED: %s (after %d seconds)' % (
1150 self.stream.writeln('INTERRUPTED: %s (after %d seconds)' % (
1151 test.name, self.times[-1][1]))
1151 test.name, self.times[-1][1]))
1152
1152
1153 class TestSuite(unittest.TestSuite):
1153 class TestSuite(unittest.TestSuite):
1154 """Custom unitest TestSuite that knows how to execute Mercurial tests."""
1154 """Custom unitest TestSuite that knows how to execute Mercurial tests."""
1155
1155
1156 def __init__(self, runner, jobs=1, whitelist=None, blacklist=None,
1156 def __init__(self, runner, jobs=1, whitelist=None, blacklist=None,
1157 retest=False,
1157 *args, **kwargs):
1158 *args, **kwargs):
1158 """Create a new instance that can run tests with a configuration.
1159 """Create a new instance that can run tests with a configuration.
1159
1160
1160 jobs specifies the number of jobs to run concurrently. Each test
1161 jobs specifies the number of jobs to run concurrently. Each test
1161 executes on its own thread. Tests actually spawn new processes, so
1162 executes on its own thread. Tests actually spawn new processes, so
1162 state mutation should not be an issue.
1163 state mutation should not be an issue.
1163
1164
1164 whitelist and blacklist denote tests that have been whitelisted and
1165 whitelist and blacklist denote tests that have been whitelisted and
1165 blacklisted, respectively. These arguments don't belong in TestSuite.
1166 blacklisted, respectively. These arguments don't belong in TestSuite.
1166 Instead, whitelist and blacklist should be handled by the thing that
1167 Instead, whitelist and blacklist should be handled by the thing that
1167 populates the TestSuite with tests. They are present to preserve
1168 populates the TestSuite with tests. They are present to preserve
1168 backwards compatible behavior which reports skipped tests as part
1169 backwards compatible behavior which reports skipped tests as part
1169 of the results.
1170 of the results.
1171
1172 retest denotes whether to retest failed tests. This arguably belongs
1173 outside of TestSuite.
1170 """
1174 """
1171 super(TestSuite, self).__init__(*args, **kwargs)
1175 super(TestSuite, self).__init__(*args, **kwargs)
1172
1176
1173 self._runner = runner
1177 self._runner = runner
1174 self._jobs = jobs
1178 self._jobs = jobs
1175 self._whitelist = whitelist
1179 self._whitelist = whitelist
1176 self._blacklist = blacklist
1180 self._blacklist = blacklist
1181 self._retest = retest
1177
1182
1178 def run(self, result):
1183 def run(self, result):
1179 options = self._runner.options
1184 options = self._runner.options
1180
1185
1181 # We have a number of filters that need to be applied. We do this
1186 # We have a number of filters that need to be applied. We do this
1182 # here instead of inside Test because it makes the running logic for
1187 # here instead of inside Test because it makes the running logic for
1183 # Test simpler.
1188 # Test simpler.
1184 tests = []
1189 tests = []
1185 for test in self._tests:
1190 for test in self._tests:
1186 if not os.path.exists(test.path):
1191 if not os.path.exists(test.path):
1187 result.addSkip(test, "Doesn't exist")
1192 result.addSkip(test, "Doesn't exist")
1188 continue
1193 continue
1189
1194
1190 if not (self._whitelist and test.name in self._whitelist):
1195 if not (self._whitelist and test.name in self._whitelist):
1191 if self._blacklist and test.name in self._blacklist:
1196 if self._blacklist and test.name in self._blacklist:
1192 result.addSkip(test, 'blacklisted')
1197 result.addSkip(test, 'blacklisted')
1193 continue
1198 continue
1194
1199
1195 if options.retest and not os.path.exists(test.errpath):
1200 if self._retest and not os.path.exists(test.errpath):
1196 result.addIgnore(test, 'not retesting')
1201 result.addIgnore(test, 'not retesting')
1197 continue
1202 continue
1198
1203
1199 if options.keywords:
1204 if options.keywords:
1200 f = open(test.path)
1205 f = open(test.path)
1201 t = f.read().lower() + test.name.lower()
1206 t = f.read().lower() + test.name.lower()
1202 f.close()
1207 f.close()
1203 ignored = False
1208 ignored = False
1204 for k in options.keywords.lower().split():
1209 for k in options.keywords.lower().split():
1205 if k not in t:
1210 if k not in t:
1206 result.addIgnore(test, "doesn't match keyword")
1211 result.addIgnore(test, "doesn't match keyword")
1207 ignored = True
1212 ignored = True
1208 break
1213 break
1209
1214
1210 if ignored:
1215 if ignored:
1211 continue
1216 continue
1212
1217
1213 tests.append(test)
1218 tests.append(test)
1214
1219
1215 runtests = list(tests)
1220 runtests = list(tests)
1216 done = queue.Queue()
1221 done = queue.Queue()
1217 running = 0
1222 running = 0
1218
1223
1219 def job(test, result):
1224 def job(test, result):
1220 try:
1225 try:
1221 test(result)
1226 test(result)
1222 done.put(None)
1227 done.put(None)
1223 except KeyboardInterrupt:
1228 except KeyboardInterrupt:
1224 pass
1229 pass
1225 except: # re-raises
1230 except: # re-raises
1226 done.put(('!', test, 'run-test raised an error, see traceback'))
1231 done.put(('!', test, 'run-test raised an error, see traceback'))
1227 raise
1232 raise
1228
1233
1229 try:
1234 try:
1230 while tests or running:
1235 while tests or running:
1231 if not done.empty() or running == self._jobs or not tests:
1236 if not done.empty() or running == self._jobs or not tests:
1232 try:
1237 try:
1233 done.get(True, 1)
1238 done.get(True, 1)
1234 if result and result.shouldStop:
1239 if result and result.shouldStop:
1235 break
1240 break
1236 except queue.Empty:
1241 except queue.Empty:
1237 continue
1242 continue
1238 running -= 1
1243 running -= 1
1239 if tests and not running == self._jobs:
1244 if tests and not running == self._jobs:
1240 test = tests.pop(0)
1245 test = tests.pop(0)
1241 if self._runner.options.loop:
1246 if self._runner.options.loop:
1242 tests.append(test)
1247 tests.append(test)
1243 t = threading.Thread(target=job, name=test.name,
1248 t = threading.Thread(target=job, name=test.name,
1244 args=(test, result))
1249 args=(test, result))
1245 t.start()
1250 t.start()
1246 running += 1
1251 running += 1
1247 except KeyboardInterrupt:
1252 except KeyboardInterrupt:
1248 for test in runtests:
1253 for test in runtests:
1249 test.abort()
1254 test.abort()
1250
1255
1251 return result
1256 return result
1252
1257
1253 class TextTestRunner(unittest.TextTestRunner):
1258 class TextTestRunner(unittest.TextTestRunner):
1254 """Custom unittest test runner that uses appropriate settings."""
1259 """Custom unittest test runner that uses appropriate settings."""
1255
1260
1256 def __init__(self, runner, *args, **kwargs):
1261 def __init__(self, runner, *args, **kwargs):
1257 super(TextTestRunner, self).__init__(*args, **kwargs)
1262 super(TextTestRunner, self).__init__(*args, **kwargs)
1258
1263
1259 self._runner = runner
1264 self._runner = runner
1260
1265
1261 def run(self, test):
1266 def run(self, test):
1262 result = TestResult(self._runner.options, self.stream,
1267 result = TestResult(self._runner.options, self.stream,
1263 self.descriptions, self.verbosity)
1268 self.descriptions, self.verbosity)
1264
1269
1265 test(result)
1270 test(result)
1266
1271
1267 failed = len(result.failures)
1272 failed = len(result.failures)
1268 warned = len(result.warned)
1273 warned = len(result.warned)
1269 skipped = len(result.skipped)
1274 skipped = len(result.skipped)
1270 ignored = len(result.ignored)
1275 ignored = len(result.ignored)
1271
1276
1272 self.stream.writeln('')
1277 self.stream.writeln('')
1273
1278
1274 if not self._runner.options.noskips:
1279 if not self._runner.options.noskips:
1275 for test, msg in result.skipped:
1280 for test, msg in result.skipped:
1276 self.stream.writeln('Skipped %s: %s' % (test.name, msg))
1281 self.stream.writeln('Skipped %s: %s' % (test.name, msg))
1277 for test, msg in result.warned:
1282 for test, msg in result.warned:
1278 self.stream.writeln('Warned %s: %s' % (test.name, msg))
1283 self.stream.writeln('Warned %s: %s' % (test.name, msg))
1279 for test, msg in result.failures:
1284 for test, msg in result.failures:
1280 self.stream.writeln('Failed %s: %s' % (test.name, msg))
1285 self.stream.writeln('Failed %s: %s' % (test.name, msg))
1281 for test, msg in result.errors:
1286 for test, msg in result.errors:
1282 self.stream.writeln('Errored %s: %s' % (test.name, msg))
1287 self.stream.writeln('Errored %s: %s' % (test.name, msg))
1283
1288
1284 self._runner._checkhglib('Tested')
1289 self._runner._checkhglib('Tested')
1285
1290
1286 # This differs from unittest's default output in that we don't count
1291 # This differs from unittest's default output in that we don't count
1287 # skipped and ignored tests as part of the total test count.
1292 # skipped and ignored tests as part of the total test count.
1288 self.stream.writeln('# Ran %d tests, %d skipped, %d warned, %d failed.'
1293 self.stream.writeln('# Ran %d tests, %d skipped, %d warned, %d failed.'
1289 % (result.testsRun - skipped - ignored,
1294 % (result.testsRun - skipped - ignored,
1290 skipped + ignored, warned, failed))
1295 skipped + ignored, warned, failed))
1291 if failed:
1296 if failed:
1292 self.stream.writeln('python hash seed: %s' %
1297 self.stream.writeln('python hash seed: %s' %
1293 os.environ['PYTHONHASHSEED'])
1298 os.environ['PYTHONHASHSEED'])
1294 if self._runner.options.time:
1299 if self._runner.options.time:
1295 self.printtimes(result.times)
1300 self.printtimes(result.times)
1296
1301
1297 def printtimes(self, times):
1302 def printtimes(self, times):
1298 self.stream.writeln('# Producing time report')
1303 self.stream.writeln('# Producing time report')
1299 times.sort(key=lambda t: (t[1], t[0]), reverse=True)
1304 times.sort(key=lambda t: (t[1], t[0]), reverse=True)
1300 cols = '%7.3f %s'
1305 cols = '%7.3f %s'
1301 self.stream.writeln('%-7s %s' % ('Time', 'Test'))
1306 self.stream.writeln('%-7s %s' % ('Time', 'Test'))
1302 for test, timetaken in times:
1307 for test, timetaken in times:
1303 self.stream.writeln(cols % (timetaken, test))
1308 self.stream.writeln(cols % (timetaken, test))
1304
1309
1305 class TestRunner(object):
1310 class TestRunner(object):
1306 """Holds context for executing tests.
1311 """Holds context for executing tests.
1307
1312
1308 Tests rely on a lot of state. This object holds it for them.
1313 Tests rely on a lot of state. This object holds it for them.
1309 """
1314 """
1310
1315
1311 REQUIREDTOOLS = [
1316 REQUIREDTOOLS = [
1312 os.path.basename(sys.executable),
1317 os.path.basename(sys.executable),
1313 'diff',
1318 'diff',
1314 'grep',
1319 'grep',
1315 'unzip',
1320 'unzip',
1316 'gunzip',
1321 'gunzip',
1317 'bunzip2',
1322 'bunzip2',
1318 'sed',
1323 'sed',
1319 ]
1324 ]
1320
1325
1321 TESTTYPES = [
1326 TESTTYPES = [
1322 ('.py', PythonTest),
1327 ('.py', PythonTest),
1323 ('.t', TTest),
1328 ('.t', TTest),
1324 ]
1329 ]
1325
1330
1326 def __init__(self):
1331 def __init__(self):
1327 self.options = None
1332 self.options = None
1328 self.testdir = None
1333 self.testdir = None
1329 self.hgtmp = None
1334 self.hgtmp = None
1330 self.inst = None
1335 self.inst = None
1331 self.bindir = None
1336 self.bindir = None
1332 self.tmpbinddir = None
1337 self.tmpbinddir = None
1333 self.pythondir = None
1338 self.pythondir = None
1334 self.coveragefile = None
1339 self.coveragefile = None
1335 self._createdfiles = []
1340 self._createdfiles = []
1336 self._hgpath = None
1341 self._hgpath = None
1337
1342
1338 def run(self, args, parser=None):
1343 def run(self, args, parser=None):
1339 """Run the test suite."""
1344 """Run the test suite."""
1340 oldmask = os.umask(022)
1345 oldmask = os.umask(022)
1341 try:
1346 try:
1342 parser = parser or getparser()
1347 parser = parser or getparser()
1343 options, args = parseargs(args, parser)
1348 options, args = parseargs(args, parser)
1344 self.options = options
1349 self.options = options
1345
1350
1346 self._checktools()
1351 self._checktools()
1347 tests = self.findtests(args)
1352 tests = self.findtests(args)
1348 return self._run(tests)
1353 return self._run(tests)
1349 finally:
1354 finally:
1350 os.umask(oldmask)
1355 os.umask(oldmask)
1351
1356
1352 def _run(self, tests):
1357 def _run(self, tests):
1353 if self.options.random:
1358 if self.options.random:
1354 random.shuffle(tests)
1359 random.shuffle(tests)
1355 else:
1360 else:
1356 # keywords for slow tests
1361 # keywords for slow tests
1357 slow = 'svn gendoc check-code-hg'.split()
1362 slow = 'svn gendoc check-code-hg'.split()
1358 def sortkey(f):
1363 def sortkey(f):
1359 # run largest tests first, as they tend to take the longest
1364 # run largest tests first, as they tend to take the longest
1360 try:
1365 try:
1361 val = -os.stat(f).st_size
1366 val = -os.stat(f).st_size
1362 except OSError, e:
1367 except OSError, e:
1363 if e.errno != errno.ENOENT:
1368 if e.errno != errno.ENOENT:
1364 raise
1369 raise
1365 return -1e9 # file does not exist, tell early
1370 return -1e9 # file does not exist, tell early
1366 for kw in slow:
1371 for kw in slow:
1367 if kw in f:
1372 if kw in f:
1368 val *= 10
1373 val *= 10
1369 return val
1374 return val
1370 tests.sort(key=sortkey)
1375 tests.sort(key=sortkey)
1371
1376
1372 self.testdir = os.environ['TESTDIR'] = os.getcwd()
1377 self.testdir = os.environ['TESTDIR'] = os.getcwd()
1373
1378
1374 if 'PYTHONHASHSEED' not in os.environ:
1379 if 'PYTHONHASHSEED' not in os.environ:
1375 # use a random python hash seed all the time
1380 # use a random python hash seed all the time
1376 # we do the randomness ourself to know what seed is used
1381 # we do the randomness ourself to know what seed is used
1377 os.environ['PYTHONHASHSEED'] = str(random.getrandbits(32))
1382 os.environ['PYTHONHASHSEED'] = str(random.getrandbits(32))
1378
1383
1379 if self.options.tmpdir:
1384 if self.options.tmpdir:
1380 self.options.keep_tmpdir = True
1385 self.options.keep_tmpdir = True
1381 tmpdir = self.options.tmpdir
1386 tmpdir = self.options.tmpdir
1382 if os.path.exists(tmpdir):
1387 if os.path.exists(tmpdir):
1383 # Meaning of tmpdir has changed since 1.3: we used to create
1388 # Meaning of tmpdir has changed since 1.3: we used to create
1384 # HGTMP inside tmpdir; now HGTMP is tmpdir. So fail if
1389 # HGTMP inside tmpdir; now HGTMP is tmpdir. So fail if
1385 # tmpdir already exists.
1390 # tmpdir already exists.
1386 print "error: temp dir %r already exists" % tmpdir
1391 print "error: temp dir %r already exists" % tmpdir
1387 return 1
1392 return 1
1388
1393
1389 # Automatically removing tmpdir sounds convenient, but could
1394 # Automatically removing tmpdir sounds convenient, but could
1390 # really annoy anyone in the habit of using "--tmpdir=/tmp"
1395 # really annoy anyone in the habit of using "--tmpdir=/tmp"
1391 # or "--tmpdir=$HOME".
1396 # or "--tmpdir=$HOME".
1392 #vlog("# Removing temp dir", tmpdir)
1397 #vlog("# Removing temp dir", tmpdir)
1393 #shutil.rmtree(tmpdir)
1398 #shutil.rmtree(tmpdir)
1394 os.makedirs(tmpdir)
1399 os.makedirs(tmpdir)
1395 else:
1400 else:
1396 d = None
1401 d = None
1397 if os.name == 'nt':
1402 if os.name == 'nt':
1398 # without this, we get the default temp dir location, but
1403 # without this, we get the default temp dir location, but
1399 # in all lowercase, which causes troubles with paths (issue3490)
1404 # in all lowercase, which causes troubles with paths (issue3490)
1400 d = os.getenv('TMP')
1405 d = os.getenv('TMP')
1401 tmpdir = tempfile.mkdtemp('', 'hgtests.', d)
1406 tmpdir = tempfile.mkdtemp('', 'hgtests.', d)
1402 self.hgtmp = os.environ['HGTMP'] = os.path.realpath(tmpdir)
1407 self.hgtmp = os.environ['HGTMP'] = os.path.realpath(tmpdir)
1403
1408
1404 if self.options.with_hg:
1409 if self.options.with_hg:
1405 self.inst = None
1410 self.inst = None
1406 self.bindir = os.path.dirname(os.path.realpath(
1411 self.bindir = os.path.dirname(os.path.realpath(
1407 self.options.with_hg))
1412 self.options.with_hg))
1408 self.tmpbindir = os.path.join(self.hgtmp, 'install', 'bin')
1413 self.tmpbindir = os.path.join(self.hgtmp, 'install', 'bin')
1409 os.makedirs(self.tmpbindir)
1414 os.makedirs(self.tmpbindir)
1410
1415
1411 # This looks redundant with how Python initializes sys.path from
1416 # This looks redundant with how Python initializes sys.path from
1412 # the location of the script being executed. Needed because the
1417 # the location of the script being executed. Needed because the
1413 # "hg" specified by --with-hg is not the only Python script
1418 # "hg" specified by --with-hg is not the only Python script
1414 # executed in the test suite that needs to import 'mercurial'
1419 # executed in the test suite that needs to import 'mercurial'
1415 # ... which means it's not really redundant at all.
1420 # ... which means it's not really redundant at all.
1416 self.pythondir = self.bindir
1421 self.pythondir = self.bindir
1417 else:
1422 else:
1418 self.inst = os.path.join(self.hgtmp, "install")
1423 self.inst = os.path.join(self.hgtmp, "install")
1419 self.bindir = os.environ["BINDIR"] = os.path.join(self.inst,
1424 self.bindir = os.environ["BINDIR"] = os.path.join(self.inst,
1420 "bin")
1425 "bin")
1421 self.tmpbindir = self.bindir
1426 self.tmpbindir = self.bindir
1422 self.pythondir = os.path.join(self.inst, "lib", "python")
1427 self.pythondir = os.path.join(self.inst, "lib", "python")
1423
1428
1424 os.environ["BINDIR"] = self.bindir
1429 os.environ["BINDIR"] = self.bindir
1425 os.environ["PYTHON"] = PYTHON
1430 os.environ["PYTHON"] = PYTHON
1426
1431
1427 path = [self.bindir] + os.environ["PATH"].split(os.pathsep)
1432 path = [self.bindir] + os.environ["PATH"].split(os.pathsep)
1428 if self.tmpbindir != self.bindir:
1433 if self.tmpbindir != self.bindir:
1429 path = [self.tmpbindir] + path
1434 path = [self.tmpbindir] + path
1430 os.environ["PATH"] = os.pathsep.join(path)
1435 os.environ["PATH"] = os.pathsep.join(path)
1431
1436
1432 # Include TESTDIR in PYTHONPATH so that out-of-tree extensions
1437 # Include TESTDIR in PYTHONPATH so that out-of-tree extensions
1433 # can run .../tests/run-tests.py test-foo where test-foo
1438 # can run .../tests/run-tests.py test-foo where test-foo
1434 # adds an extension to HGRC. Also include run-test.py directory to
1439 # adds an extension to HGRC. Also include run-test.py directory to
1435 # import modules like heredoctest.
1440 # import modules like heredoctest.
1436 pypath = [self.pythondir, self.testdir,
1441 pypath = [self.pythondir, self.testdir,
1437 os.path.abspath(os.path.dirname(__file__))]
1442 os.path.abspath(os.path.dirname(__file__))]
1438 # We have to augment PYTHONPATH, rather than simply replacing
1443 # We have to augment PYTHONPATH, rather than simply replacing
1439 # it, in case external libraries are only available via current
1444 # it, in case external libraries are only available via current
1440 # PYTHONPATH. (In particular, the Subversion bindings on OS X
1445 # PYTHONPATH. (In particular, the Subversion bindings on OS X
1441 # are in /opt/subversion.)
1446 # are in /opt/subversion.)
1442 oldpypath = os.environ.get(IMPL_PATH)
1447 oldpypath = os.environ.get(IMPL_PATH)
1443 if oldpypath:
1448 if oldpypath:
1444 pypath.append(oldpypath)
1449 pypath.append(oldpypath)
1445 os.environ[IMPL_PATH] = os.pathsep.join(pypath)
1450 os.environ[IMPL_PATH] = os.pathsep.join(pypath)
1446
1451
1447 self.coveragefile = os.path.join(self.testdir, '.coverage')
1452 self.coveragefile = os.path.join(self.testdir, '.coverage')
1448
1453
1449 vlog("# Using TESTDIR", self.testdir)
1454 vlog("# Using TESTDIR", self.testdir)
1450 vlog("# Using HGTMP", self.hgtmp)
1455 vlog("# Using HGTMP", self.hgtmp)
1451 vlog("# Using PATH", os.environ["PATH"])
1456 vlog("# Using PATH", os.environ["PATH"])
1452 vlog("# Using", IMPL_PATH, os.environ[IMPL_PATH])
1457 vlog("# Using", IMPL_PATH, os.environ[IMPL_PATH])
1453
1458
1454 try:
1459 try:
1455 return self._runtests(tests) or 0
1460 return self._runtests(tests) or 0
1456 finally:
1461 finally:
1457 time.sleep(.1)
1462 time.sleep(.1)
1458 self._cleanup()
1463 self._cleanup()
1459
1464
1460 def findtests(self, args):
1465 def findtests(self, args):
1461 """Finds possible test files from arguments.
1466 """Finds possible test files from arguments.
1462
1467
1463 If you wish to inject custom tests into the test harness, this would
1468 If you wish to inject custom tests into the test harness, this would
1464 be a good function to monkeypatch or override in a derived class.
1469 be a good function to monkeypatch or override in a derived class.
1465 """
1470 """
1466 if not args:
1471 if not args:
1467 if self.options.changed:
1472 if self.options.changed:
1468 proc = Popen4('hg st --rev "%s" -man0 .' %
1473 proc = Popen4('hg st --rev "%s" -man0 .' %
1469 self.options.changed, None, 0)
1474 self.options.changed, None, 0)
1470 stdout, stderr = proc.communicate()
1475 stdout, stderr = proc.communicate()
1471 args = stdout.strip('\0').split('\0')
1476 args = stdout.strip('\0').split('\0')
1472 else:
1477 else:
1473 args = os.listdir('.')
1478 args = os.listdir('.')
1474
1479
1475 return [t for t in args
1480 return [t for t in args
1476 if os.path.basename(t).startswith('test-')
1481 if os.path.basename(t).startswith('test-')
1477 and (t.endswith('.py') or t.endswith('.t'))]
1482 and (t.endswith('.py') or t.endswith('.t'))]
1478
1483
1479 def _runtests(self, tests):
1484 def _runtests(self, tests):
1480 try:
1485 try:
1481 if self.inst:
1486 if self.inst:
1482 self._installhg()
1487 self._installhg()
1483 self._checkhglib("Testing")
1488 self._checkhglib("Testing")
1484 else:
1489 else:
1485 self._usecorrectpython()
1490 self._usecorrectpython()
1486
1491
1487 if self.options.restart:
1492 if self.options.restart:
1488 orig = list(tests)
1493 orig = list(tests)
1489 while tests:
1494 while tests:
1490 if os.path.exists(tests[0] + ".err"):
1495 if os.path.exists(tests[0] + ".err"):
1491 break
1496 break
1492 tests.pop(0)
1497 tests.pop(0)
1493 if not tests:
1498 if not tests:
1494 print "running all tests"
1499 print "running all tests"
1495 tests = orig
1500 tests = orig
1496
1501
1497 tests = [self._gettest(t, i) for i, t in enumerate(tests)]
1502 tests = [self._gettest(t, i) for i, t in enumerate(tests)]
1498
1503
1499 failed = False
1504 failed = False
1500 warned = False
1505 warned = False
1501
1506
1502 suite = TestSuite(self, jobs=self.options.jobs,
1507 suite = TestSuite(self, jobs=self.options.jobs,
1503 whitelist=self.options.whitelisted,
1508 whitelist=self.options.whitelisted,
1504 blacklist=self.options.blacklist,
1509 blacklist=self.options.blacklist,
1510 retest=self.options.retest,
1505 tests=tests)
1511 tests=tests)
1506 verbosity = 1
1512 verbosity = 1
1507 if self.options.verbose:
1513 if self.options.verbose:
1508 verbosity = 2
1514 verbosity = 2
1509 runner = TextTestRunner(self, verbosity=verbosity)
1515 runner = TextTestRunner(self, verbosity=verbosity)
1510 runner.run(suite)
1516 runner.run(suite)
1511
1517
1512 if self.options.anycoverage:
1518 if self.options.anycoverage:
1513 self._outputcoverage()
1519 self._outputcoverage()
1514 except KeyboardInterrupt:
1520 except KeyboardInterrupt:
1515 failed = True
1521 failed = True
1516 print "\ninterrupted!"
1522 print "\ninterrupted!"
1517
1523
1518 if failed:
1524 if failed:
1519 return 1
1525 return 1
1520 if warned:
1526 if warned:
1521 return 80
1527 return 80
1522
1528
1523 def _gettest(self, test, count):
1529 def _gettest(self, test, count):
1524 """Obtain a Test by looking at its filename.
1530 """Obtain a Test by looking at its filename.
1525
1531
1526 Returns a Test instance. The Test may not be runnable if it doesn't
1532 Returns a Test instance. The Test may not be runnable if it doesn't
1527 map to a known type.
1533 map to a known type.
1528 """
1534 """
1529 lctest = test.lower()
1535 lctest = test.lower()
1530 testcls = Test
1536 testcls = Test
1531
1537
1532 for ext, cls in self.TESTTYPES:
1538 for ext, cls in self.TESTTYPES:
1533 if lctest.endswith(ext):
1539 if lctest.endswith(ext):
1534 testcls = cls
1540 testcls = cls
1535 break
1541 break
1536
1542
1537 refpath = os.path.join(self.testdir, test)
1543 refpath = os.path.join(self.testdir, test)
1538 tmpdir = os.path.join(self.hgtmp, 'child%d' % count)
1544 tmpdir = os.path.join(self.hgtmp, 'child%d' % count)
1539
1545
1540 return testcls(refpath, tmpdir,
1546 return testcls(refpath, tmpdir,
1541 keeptmpdir=self.options.keep_tmpdir,
1547 keeptmpdir=self.options.keep_tmpdir,
1542 debug=self.options.debug,
1548 debug=self.options.debug,
1543 timeout=self.options.timeout,
1549 timeout=self.options.timeout,
1544 startport=self.options.port + count * 3,
1550 startport=self.options.port + count * 3,
1545 extraconfigopts=self.options.extra_config_opt,
1551 extraconfigopts=self.options.extra_config_opt,
1546 py3kwarnings=self.options.py3k_warnings,
1552 py3kwarnings=self.options.py3k_warnings,
1547 shell=self.options.shell)
1553 shell=self.options.shell)
1548
1554
1549 def _cleanup(self):
1555 def _cleanup(self):
1550 """Clean up state from this test invocation."""
1556 """Clean up state from this test invocation."""
1551
1557
1552 if self.options.keep_tmpdir:
1558 if self.options.keep_tmpdir:
1553 return
1559 return
1554
1560
1555 vlog("# Cleaning up HGTMP", self.hgtmp)
1561 vlog("# Cleaning up HGTMP", self.hgtmp)
1556 shutil.rmtree(self.hgtmp, True)
1562 shutil.rmtree(self.hgtmp, True)
1557 for f in self._createdfiles:
1563 for f in self._createdfiles:
1558 try:
1564 try:
1559 os.remove(f)
1565 os.remove(f)
1560 except OSError:
1566 except OSError:
1561 pass
1567 pass
1562
1568
1563 def _usecorrectpython(self):
1569 def _usecorrectpython(self):
1564 # Some tests run the Python interpreter. They must use the
1570 # Some tests run the Python interpreter. They must use the
1565 # same interpreter or bad things will happen.
1571 # same interpreter or bad things will happen.
1566 pyexename = sys.platform == 'win32' and 'python.exe' or 'python'
1572 pyexename = sys.platform == 'win32' and 'python.exe' or 'python'
1567 if getattr(os, 'symlink', None):
1573 if getattr(os, 'symlink', None):
1568 vlog("# Making python executable in test path a symlink to '%s'" %
1574 vlog("# Making python executable in test path a symlink to '%s'" %
1569 sys.executable)
1575 sys.executable)
1570 mypython = os.path.join(self.tmpbindir, pyexename)
1576 mypython = os.path.join(self.tmpbindir, pyexename)
1571 try:
1577 try:
1572 if os.readlink(mypython) == sys.executable:
1578 if os.readlink(mypython) == sys.executable:
1573 return
1579 return
1574 os.unlink(mypython)
1580 os.unlink(mypython)
1575 except OSError, err:
1581 except OSError, err:
1576 if err.errno != errno.ENOENT:
1582 if err.errno != errno.ENOENT:
1577 raise
1583 raise
1578 if self._findprogram(pyexename) != sys.executable:
1584 if self._findprogram(pyexename) != sys.executable:
1579 try:
1585 try:
1580 os.symlink(sys.executable, mypython)
1586 os.symlink(sys.executable, mypython)
1581 self._createdfiles.append(mypython)
1587 self._createdfiles.append(mypython)
1582 except OSError, err:
1588 except OSError, err:
1583 # child processes may race, which is harmless
1589 # child processes may race, which is harmless
1584 if err.errno != errno.EEXIST:
1590 if err.errno != errno.EEXIST:
1585 raise
1591 raise
1586 else:
1592 else:
1587 exedir, exename = os.path.split(sys.executable)
1593 exedir, exename = os.path.split(sys.executable)
1588 vlog("# Modifying search path to find %s as %s in '%s'" %
1594 vlog("# Modifying search path to find %s as %s in '%s'" %
1589 (exename, pyexename, exedir))
1595 (exename, pyexename, exedir))
1590 path = os.environ['PATH'].split(os.pathsep)
1596 path = os.environ['PATH'].split(os.pathsep)
1591 while exedir in path:
1597 while exedir in path:
1592 path.remove(exedir)
1598 path.remove(exedir)
1593 os.environ['PATH'] = os.pathsep.join([exedir] + path)
1599 os.environ['PATH'] = os.pathsep.join([exedir] + path)
1594 if not self._findprogram(pyexename):
1600 if not self._findprogram(pyexename):
1595 print "WARNING: Cannot find %s in search path" % pyexename
1601 print "WARNING: Cannot find %s in search path" % pyexename
1596
1602
1597 def _installhg(self):
1603 def _installhg(self):
1598 vlog("# Performing temporary installation of HG")
1604 vlog("# Performing temporary installation of HG")
1599 installerrs = os.path.join("tests", "install.err")
1605 installerrs = os.path.join("tests", "install.err")
1600 compiler = ''
1606 compiler = ''
1601 if self.options.compiler:
1607 if self.options.compiler:
1602 compiler = '--compiler ' + self.options.compiler
1608 compiler = '--compiler ' + self.options.compiler
1603 pure = self.options.pure and "--pure" or ""
1609 pure = self.options.pure and "--pure" or ""
1604 py3 = ''
1610 py3 = ''
1605 if sys.version_info[0] == 3:
1611 if sys.version_info[0] == 3:
1606 py3 = '--c2to3'
1612 py3 = '--c2to3'
1607
1613
1608 # Run installer in hg root
1614 # Run installer in hg root
1609 script = os.path.realpath(sys.argv[0])
1615 script = os.path.realpath(sys.argv[0])
1610 hgroot = os.path.dirname(os.path.dirname(script))
1616 hgroot = os.path.dirname(os.path.dirname(script))
1611 os.chdir(hgroot)
1617 os.chdir(hgroot)
1612 nohome = '--home=""'
1618 nohome = '--home=""'
1613 if os.name == 'nt':
1619 if os.name == 'nt':
1614 # The --home="" trick works only on OS where os.sep == '/'
1620 # The --home="" trick works only on OS where os.sep == '/'
1615 # because of a distutils convert_path() fast-path. Avoid it at
1621 # because of a distutils convert_path() fast-path. Avoid it at
1616 # least on Windows for now, deal with .pydistutils.cfg bugs
1622 # least on Windows for now, deal with .pydistutils.cfg bugs
1617 # when they happen.
1623 # when they happen.
1618 nohome = ''
1624 nohome = ''
1619 cmd = ('%(exe)s setup.py %(py3)s %(pure)s clean --all'
1625 cmd = ('%(exe)s setup.py %(py3)s %(pure)s clean --all'
1620 ' build %(compiler)s --build-base="%(base)s"'
1626 ' build %(compiler)s --build-base="%(base)s"'
1621 ' install --force --prefix="%(prefix)s"'
1627 ' install --force --prefix="%(prefix)s"'
1622 ' --install-lib="%(libdir)s"'
1628 ' --install-lib="%(libdir)s"'
1623 ' --install-scripts="%(bindir)s" %(nohome)s >%(logfile)s 2>&1'
1629 ' --install-scripts="%(bindir)s" %(nohome)s >%(logfile)s 2>&1'
1624 % {'exe': sys.executable, 'py3': py3, 'pure': pure,
1630 % {'exe': sys.executable, 'py3': py3, 'pure': pure,
1625 'compiler': compiler,
1631 'compiler': compiler,
1626 'base': os.path.join(self.hgtmp, "build"),
1632 'base': os.path.join(self.hgtmp, "build"),
1627 'prefix': self.inst, 'libdir': self.pythondir,
1633 'prefix': self.inst, 'libdir': self.pythondir,
1628 'bindir': self.bindir,
1634 'bindir': self.bindir,
1629 'nohome': nohome, 'logfile': installerrs})
1635 'nohome': nohome, 'logfile': installerrs})
1630 vlog("# Running", cmd)
1636 vlog("# Running", cmd)
1631 if os.system(cmd) == 0:
1637 if os.system(cmd) == 0:
1632 if not self.options.verbose:
1638 if not self.options.verbose:
1633 os.remove(installerrs)
1639 os.remove(installerrs)
1634 else:
1640 else:
1635 f = open(installerrs)
1641 f = open(installerrs)
1636 for line in f:
1642 for line in f:
1637 print line,
1643 print line,
1638 f.close()
1644 f.close()
1639 sys.exit(1)
1645 sys.exit(1)
1640 os.chdir(self.testdir)
1646 os.chdir(self.testdir)
1641
1647
1642 self._usecorrectpython()
1648 self._usecorrectpython()
1643
1649
1644 if self.options.py3k_warnings and not self.options.anycoverage:
1650 if self.options.py3k_warnings and not self.options.anycoverage:
1645 vlog("# Updating hg command to enable Py3k Warnings switch")
1651 vlog("# Updating hg command to enable Py3k Warnings switch")
1646 f = open(os.path.join(self.bindir, 'hg'), 'r')
1652 f = open(os.path.join(self.bindir, 'hg'), 'r')
1647 lines = [line.rstrip() for line in f]
1653 lines = [line.rstrip() for line in f]
1648 lines[0] += ' -3'
1654 lines[0] += ' -3'
1649 f.close()
1655 f.close()
1650 f = open(os.path.join(self.bindir, 'hg'), 'w')
1656 f = open(os.path.join(self.bindir, 'hg'), 'w')
1651 for line in lines:
1657 for line in lines:
1652 f.write(line + '\n')
1658 f.write(line + '\n')
1653 f.close()
1659 f.close()
1654
1660
1655 hgbat = os.path.join(self.bindir, 'hg.bat')
1661 hgbat = os.path.join(self.bindir, 'hg.bat')
1656 if os.path.isfile(hgbat):
1662 if os.path.isfile(hgbat):
1657 # hg.bat expects to be put in bin/scripts while run-tests.py
1663 # hg.bat expects to be put in bin/scripts while run-tests.py
1658 # installation layout put it in bin/ directly. Fix it
1664 # installation layout put it in bin/ directly. Fix it
1659 f = open(hgbat, 'rb')
1665 f = open(hgbat, 'rb')
1660 data = f.read()
1666 data = f.read()
1661 f.close()
1667 f.close()
1662 if '"%~dp0..\python" "%~dp0hg" %*' in data:
1668 if '"%~dp0..\python" "%~dp0hg" %*' in data:
1663 data = data.replace('"%~dp0..\python" "%~dp0hg" %*',
1669 data = data.replace('"%~dp0..\python" "%~dp0hg" %*',
1664 '"%~dp0python" "%~dp0hg" %*')
1670 '"%~dp0python" "%~dp0hg" %*')
1665 f = open(hgbat, 'wb')
1671 f = open(hgbat, 'wb')
1666 f.write(data)
1672 f.write(data)
1667 f.close()
1673 f.close()
1668 else:
1674 else:
1669 print 'WARNING: cannot fix hg.bat reference to python.exe'
1675 print 'WARNING: cannot fix hg.bat reference to python.exe'
1670
1676
1671 if self.options.anycoverage:
1677 if self.options.anycoverage:
1672 custom = os.path.join(self.testdir, 'sitecustomize.py')
1678 custom = os.path.join(self.testdir, 'sitecustomize.py')
1673 target = os.path.join(self.pythondir, 'sitecustomize.py')
1679 target = os.path.join(self.pythondir, 'sitecustomize.py')
1674 vlog('# Installing coverage trigger to %s' % target)
1680 vlog('# Installing coverage trigger to %s' % target)
1675 shutil.copyfile(custom, target)
1681 shutil.copyfile(custom, target)
1676 rc = os.path.join(self.testdir, '.coveragerc')
1682 rc = os.path.join(self.testdir, '.coveragerc')
1677 vlog('# Installing coverage rc to %s' % rc)
1683 vlog('# Installing coverage rc to %s' % rc)
1678 os.environ['COVERAGE_PROCESS_START'] = rc
1684 os.environ['COVERAGE_PROCESS_START'] = rc
1679 fn = os.path.join(self.inst, '..', '.coverage')
1685 fn = os.path.join(self.inst, '..', '.coverage')
1680 os.environ['COVERAGE_FILE'] = fn
1686 os.environ['COVERAGE_FILE'] = fn
1681
1687
1682 def _checkhglib(self, verb):
1688 def _checkhglib(self, verb):
1683 """Ensure that the 'mercurial' package imported by python is
1689 """Ensure that the 'mercurial' package imported by python is
1684 the one we expect it to be. If not, print a warning to stderr."""
1690 the one we expect it to be. If not, print a warning to stderr."""
1685 expecthg = os.path.join(self.pythondir, 'mercurial')
1691 expecthg = os.path.join(self.pythondir, 'mercurial')
1686 actualhg = self._gethgpath()
1692 actualhg = self._gethgpath()
1687 if os.path.abspath(actualhg) != os.path.abspath(expecthg):
1693 if os.path.abspath(actualhg) != os.path.abspath(expecthg):
1688 sys.stderr.write('warning: %s with unexpected mercurial lib: %s\n'
1694 sys.stderr.write('warning: %s with unexpected mercurial lib: %s\n'
1689 ' (expected %s)\n'
1695 ' (expected %s)\n'
1690 % (verb, actualhg, expecthg))
1696 % (verb, actualhg, expecthg))
1691 def _gethgpath(self):
1697 def _gethgpath(self):
1692 """Return the path to the mercurial package that is actually found by
1698 """Return the path to the mercurial package that is actually found by
1693 the current Python interpreter."""
1699 the current Python interpreter."""
1694 if self._hgpath is not None:
1700 if self._hgpath is not None:
1695 return self._hgpath
1701 return self._hgpath
1696
1702
1697 cmd = '%s -c "import mercurial; print (mercurial.__path__[0])"'
1703 cmd = '%s -c "import mercurial; print (mercurial.__path__[0])"'
1698 pipe = os.popen(cmd % PYTHON)
1704 pipe = os.popen(cmd % PYTHON)
1699 try:
1705 try:
1700 self._hgpath = pipe.read().strip()
1706 self._hgpath = pipe.read().strip()
1701 finally:
1707 finally:
1702 pipe.close()
1708 pipe.close()
1703
1709
1704 return self._hgpath
1710 return self._hgpath
1705
1711
1706 def _outputcoverage(self):
1712 def _outputcoverage(self):
1707 vlog('# Producing coverage report')
1713 vlog('# Producing coverage report')
1708 os.chdir(self.pythondir)
1714 os.chdir(self.pythondir)
1709
1715
1710 def covrun(*args):
1716 def covrun(*args):
1711 cmd = 'coverage %s' % ' '.join(args)
1717 cmd = 'coverage %s' % ' '.join(args)
1712 vlog('# Running: %s' % cmd)
1718 vlog('# Running: %s' % cmd)
1713 os.system(cmd)
1719 os.system(cmd)
1714
1720
1715 covrun('-c')
1721 covrun('-c')
1716 omit = ','.join(os.path.join(x, '*') for x in
1722 omit = ','.join(os.path.join(x, '*') for x in
1717 [self.bindir, self.testdir])
1723 [self.bindir, self.testdir])
1718 covrun('-i', '-r', '"--omit=%s"' % omit) # report
1724 covrun('-i', '-r', '"--omit=%s"' % omit) # report
1719 if self.options.htmlcov:
1725 if self.options.htmlcov:
1720 htmldir = os.path.join(self.testdir, 'htmlcov')
1726 htmldir = os.path.join(self.testdir, 'htmlcov')
1721 covrun('-i', '-b', '"--directory=%s"' % htmldir,
1727 covrun('-i', '-b', '"--directory=%s"' % htmldir,
1722 '"--omit=%s"' % omit)
1728 '"--omit=%s"' % omit)
1723 if self.options.annotate:
1729 if self.options.annotate:
1724 adir = os.path.join(self.testdir, 'annotated')
1730 adir = os.path.join(self.testdir, 'annotated')
1725 if not os.path.isdir(adir):
1731 if not os.path.isdir(adir):
1726 os.mkdir(adir)
1732 os.mkdir(adir)
1727 covrun('-i', '-a', '"--directory=%s"' % adir, '"--omit=%s"' % omit)
1733 covrun('-i', '-a', '"--directory=%s"' % adir, '"--omit=%s"' % omit)
1728
1734
1729 def _findprogram(self, program):
1735 def _findprogram(self, program):
1730 """Search PATH for a executable program"""
1736 """Search PATH for a executable program"""
1731 for p in os.environ.get('PATH', os.defpath).split(os.pathsep):
1737 for p in os.environ.get('PATH', os.defpath).split(os.pathsep):
1732 name = os.path.join(p, program)
1738 name = os.path.join(p, program)
1733 if os.name == 'nt' or os.access(name, os.X_OK):
1739 if os.name == 'nt' or os.access(name, os.X_OK):
1734 return name
1740 return name
1735 return None
1741 return None
1736
1742
1737 def _checktools(self):
1743 def _checktools(self):
1738 # Before we go any further, check for pre-requisite tools
1744 # Before we go any further, check for pre-requisite tools
1739 # stuff from coreutils (cat, rm, etc) are not tested
1745 # stuff from coreutils (cat, rm, etc) are not tested
1740 for p in self.REQUIREDTOOLS:
1746 for p in self.REQUIREDTOOLS:
1741 if os.name == 'nt' and not p.endswith('.exe'):
1747 if os.name == 'nt' and not p.endswith('.exe'):
1742 p += '.exe'
1748 p += '.exe'
1743 found = self._findprogram(p)
1749 found = self._findprogram(p)
1744 if found:
1750 if found:
1745 vlog("# Found prerequisite", p, "at", found)
1751 vlog("# Found prerequisite", p, "at", found)
1746 else:
1752 else:
1747 print "WARNING: Did not find prerequisite tool: %s " % p
1753 print "WARNING: Did not find prerequisite tool: %s " % p
1748
1754
1749 if __name__ == '__main__':
1755 if __name__ == '__main__':
1750 runner = TestRunner()
1756 runner = TestRunner()
1751 sys.exit(runner.run(sys.argv[1:]))
1757 sys.exit(runner.run(sys.argv[1:]))
General Comments 0
You need to be logged in to leave comments. Login now