##// END OF EJS Templates
run-tests: fix --debug for .t tests...
Nicolas Dumazet -
r13002:6747d4a5 default
parent child Browse files
Show More
@@ -1,1111 +1,1112 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 re
55 import re
56
56
57 closefds = os.name == 'posix'
57 closefds = os.name == 'posix'
58 def Popen4(cmd, bufsize=-1):
58 def Popen4(cmd, bufsize=-1):
59 p = subprocess.Popen(cmd, shell=True, bufsize=bufsize,
59 p = subprocess.Popen(cmd, shell=True, bufsize=bufsize,
60 close_fds=closefds,
60 close_fds=closefds,
61 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
61 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
62 stderr=subprocess.STDOUT)
62 stderr=subprocess.STDOUT)
63 p.fromchild = p.stdout
63 p.fromchild = p.stdout
64 p.tochild = p.stdin
64 p.tochild = p.stdin
65 p.childerr = p.stderr
65 p.childerr = p.stderr
66 return p
66 return p
67
67
68 # reserved exit code to skip test (used by hghave)
68 # reserved exit code to skip test (used by hghave)
69 SKIPPED_STATUS = 80
69 SKIPPED_STATUS = 80
70 SKIPPED_PREFIX = 'skipped: '
70 SKIPPED_PREFIX = 'skipped: '
71 FAILED_PREFIX = 'hghave check failed: '
71 FAILED_PREFIX = 'hghave check failed: '
72 PYTHON = sys.executable
72 PYTHON = sys.executable
73 IMPL_PATH = 'PYTHONPATH'
73 IMPL_PATH = 'PYTHONPATH'
74 if 'java' in sys.platform:
74 if 'java' in sys.platform:
75 IMPL_PATH = 'JYTHONPATH'
75 IMPL_PATH = 'JYTHONPATH'
76
76
77 requiredtools = ["python", "diff", "grep", "unzip", "gunzip", "bunzip2", "sed"]
77 requiredtools = ["python", "diff", "grep", "unzip", "gunzip", "bunzip2", "sed"]
78
78
79 defaults = {
79 defaults = {
80 'jobs': ('HGTEST_JOBS', 1),
80 'jobs': ('HGTEST_JOBS', 1),
81 'timeout': ('HGTEST_TIMEOUT', 180),
81 'timeout': ('HGTEST_TIMEOUT', 180),
82 'port': ('HGTEST_PORT', 20059),
82 'port': ('HGTEST_PORT', 20059),
83 }
83 }
84
84
85 def parseargs():
85 def parseargs():
86 parser = optparse.OptionParser("%prog [options] [tests]")
86 parser = optparse.OptionParser("%prog [options] [tests]")
87
87
88 # keep these sorted
88 # keep these sorted
89 parser.add_option("--blacklist", action="append",
89 parser.add_option("--blacklist", action="append",
90 help="skip tests listed in the specified blacklist file")
90 help="skip tests listed in the specified blacklist file")
91 parser.add_option("-C", "--annotate", action="store_true",
91 parser.add_option("-C", "--annotate", action="store_true",
92 help="output files annotated with coverage")
92 help="output files annotated with coverage")
93 parser.add_option("--child", type="int",
93 parser.add_option("--child", type="int",
94 help="run as child process, summary to given fd")
94 help="run as child process, summary to given fd")
95 parser.add_option("-c", "--cover", action="store_true",
95 parser.add_option("-c", "--cover", action="store_true",
96 help="print a test coverage report")
96 help="print a test coverage report")
97 parser.add_option("-d", "--debug", action="store_true",
97 parser.add_option("-d", "--debug", action="store_true",
98 help="debug mode: write output of test scripts to console"
98 help="debug mode: write output of test scripts to console"
99 " rather than capturing and diff'ing it (disables timeout)")
99 " rather than capturing and diff'ing it (disables timeout)")
100 parser.add_option("-f", "--first", action="store_true",
100 parser.add_option("-f", "--first", action="store_true",
101 help="exit on the first test failure")
101 help="exit on the first test failure")
102 parser.add_option("--inotify", action="store_true",
102 parser.add_option("--inotify", action="store_true",
103 help="enable inotify extension when running tests")
103 help="enable inotify extension when running tests")
104 parser.add_option("-i", "--interactive", action="store_true",
104 parser.add_option("-i", "--interactive", action="store_true",
105 help="prompt to accept changed output")
105 help="prompt to accept changed output")
106 parser.add_option("-j", "--jobs", type="int",
106 parser.add_option("-j", "--jobs", type="int",
107 help="number of jobs to run in parallel"
107 help="number of jobs to run in parallel"
108 " (default: $%s or %d)" % defaults['jobs'])
108 " (default: $%s or %d)" % defaults['jobs'])
109 parser.add_option("--keep-tmpdir", action="store_true",
109 parser.add_option("--keep-tmpdir", action="store_true",
110 help="keep temporary directory after running tests")
110 help="keep temporary directory after running tests")
111 parser.add_option("-k", "--keywords",
111 parser.add_option("-k", "--keywords",
112 help="run tests matching keywords")
112 help="run tests matching keywords")
113 parser.add_option("-l", "--local", action="store_true",
113 parser.add_option("-l", "--local", action="store_true",
114 help="shortcut for --with-hg=<testdir>/../hg")
114 help="shortcut for --with-hg=<testdir>/../hg")
115 parser.add_option("-n", "--nodiff", action="store_true",
115 parser.add_option("-n", "--nodiff", action="store_true",
116 help="skip showing test changes")
116 help="skip showing test changes")
117 parser.add_option("-p", "--port", type="int",
117 parser.add_option("-p", "--port", type="int",
118 help="port on which servers should listen"
118 help="port on which servers should listen"
119 " (default: $%s or %d)" % defaults['port'])
119 " (default: $%s or %d)" % defaults['port'])
120 parser.add_option("--pure", action="store_true",
120 parser.add_option("--pure", action="store_true",
121 help="use pure Python code instead of C extensions")
121 help="use pure Python code instead of C extensions")
122 parser.add_option("-R", "--restart", action="store_true",
122 parser.add_option("-R", "--restart", action="store_true",
123 help="restart at last error")
123 help="restart at last error")
124 parser.add_option("-r", "--retest", action="store_true",
124 parser.add_option("-r", "--retest", action="store_true",
125 help="retest failed tests")
125 help="retest failed tests")
126 parser.add_option("-S", "--noskips", action="store_true",
126 parser.add_option("-S", "--noskips", action="store_true",
127 help="don't report skip tests verbosely")
127 help="don't report skip tests verbosely")
128 parser.add_option("-t", "--timeout", type="int",
128 parser.add_option("-t", "--timeout", type="int",
129 help="kill errant tests after TIMEOUT seconds"
129 help="kill errant tests after TIMEOUT seconds"
130 " (default: $%s or %d)" % defaults['timeout'])
130 " (default: $%s or %d)" % defaults['timeout'])
131 parser.add_option("--tmpdir", type="string",
131 parser.add_option("--tmpdir", type="string",
132 help="run tests in the given temporary directory"
132 help="run tests in the given temporary directory"
133 " (implies --keep-tmpdir)")
133 " (implies --keep-tmpdir)")
134 parser.add_option("-v", "--verbose", action="store_true",
134 parser.add_option("-v", "--verbose", action="store_true",
135 help="output verbose messages")
135 help="output verbose messages")
136 parser.add_option("--view", type="string",
136 parser.add_option("--view", type="string",
137 help="external diff viewer")
137 help="external diff viewer")
138 parser.add_option("--with-hg", type="string",
138 parser.add_option("--with-hg", type="string",
139 metavar="HG",
139 metavar="HG",
140 help="test using specified hg script rather than a "
140 help="test using specified hg script rather than a "
141 "temporary installation")
141 "temporary installation")
142 parser.add_option("-3", "--py3k-warnings", action="store_true",
142 parser.add_option("-3", "--py3k-warnings", action="store_true",
143 help="enable Py3k warnings on Python 2.6+")
143 help="enable Py3k warnings on Python 2.6+")
144
144
145 for option, default in defaults.items():
145 for option, default in defaults.items():
146 defaults[option] = int(os.environ.get(*default))
146 defaults[option] = int(os.environ.get(*default))
147 parser.set_defaults(**defaults)
147 parser.set_defaults(**defaults)
148 (options, args) = parser.parse_args()
148 (options, args) = parser.parse_args()
149
149
150 # jython is always pure
150 # jython is always pure
151 if 'java' in sys.platform or '__pypy__' in sys.modules:
151 if 'java' in sys.platform or '__pypy__' in sys.modules:
152 options.pure = True
152 options.pure = True
153
153
154 if options.with_hg:
154 if options.with_hg:
155 if not (os.path.isfile(options.with_hg) and
155 if not (os.path.isfile(options.with_hg) and
156 os.access(options.with_hg, os.X_OK)):
156 os.access(options.with_hg, os.X_OK)):
157 parser.error('--with-hg must specify an executable hg script')
157 parser.error('--with-hg must specify an executable hg script')
158 if not os.path.basename(options.with_hg) == 'hg':
158 if not os.path.basename(options.with_hg) == 'hg':
159 sys.stderr.write('warning: --with-hg should specify an hg script')
159 sys.stderr.write('warning: --with-hg should specify an hg script')
160 if options.local:
160 if options.local:
161 testdir = os.path.dirname(os.path.realpath(sys.argv[0]))
161 testdir = os.path.dirname(os.path.realpath(sys.argv[0]))
162 hgbin = os.path.join(os.path.dirname(testdir), 'hg')
162 hgbin = os.path.join(os.path.dirname(testdir), 'hg')
163 if not os.access(hgbin, os.X_OK):
163 if not os.access(hgbin, os.X_OK):
164 parser.error('--local specified, but %r not found or not executable'
164 parser.error('--local specified, but %r not found or not executable'
165 % hgbin)
165 % hgbin)
166 options.with_hg = hgbin
166 options.with_hg = hgbin
167
167
168 options.anycoverage = options.cover or options.annotate
168 options.anycoverage = options.cover or options.annotate
169 if options.anycoverage:
169 if options.anycoverage:
170 try:
170 try:
171 import coverage
171 import coverage
172 covver = version.StrictVersion(coverage.__version__).version
172 covver = version.StrictVersion(coverage.__version__).version
173 if covver < (3, 3):
173 if covver < (3, 3):
174 parser.error('coverage options require coverage 3.3 or later')
174 parser.error('coverage options require coverage 3.3 or later')
175 except ImportError:
175 except ImportError:
176 parser.error('coverage options now require the coverage package')
176 parser.error('coverage options now require the coverage package')
177
177
178 if options.anycoverage and options.local:
178 if options.anycoverage and options.local:
179 # this needs some path mangling somewhere, I guess
179 # this needs some path mangling somewhere, I guess
180 parser.error("sorry, coverage options do not work when --local "
180 parser.error("sorry, coverage options do not work when --local "
181 "is specified")
181 "is specified")
182
182
183 global vlog
183 global vlog
184 if options.verbose:
184 if options.verbose:
185 if options.jobs > 1 or options.child is not None:
185 if options.jobs > 1 or options.child is not None:
186 pid = "[%d]" % os.getpid()
186 pid = "[%d]" % os.getpid()
187 else:
187 else:
188 pid = None
188 pid = None
189 def vlog(*msg):
189 def vlog(*msg):
190 if pid:
190 if pid:
191 print pid,
191 print pid,
192 for m in msg:
192 for m in msg:
193 print m,
193 print m,
194 print
194 print
195 sys.stdout.flush()
195 sys.stdout.flush()
196 else:
196 else:
197 vlog = lambda *msg: None
197 vlog = lambda *msg: None
198
198
199 if options.tmpdir:
199 if options.tmpdir:
200 options.tmpdir = os.path.expanduser(options.tmpdir)
200 options.tmpdir = os.path.expanduser(options.tmpdir)
201
201
202 if options.jobs < 1:
202 if options.jobs < 1:
203 parser.error('--jobs must be positive')
203 parser.error('--jobs must be positive')
204 if options.interactive and options.jobs > 1:
204 if options.interactive and options.jobs > 1:
205 print '(--interactive overrides --jobs)'
205 print '(--interactive overrides --jobs)'
206 options.jobs = 1
206 options.jobs = 1
207 if options.interactive and options.debug:
207 if options.interactive and options.debug:
208 parser.error("-i/--interactive and -d/--debug are incompatible")
208 parser.error("-i/--interactive and -d/--debug are incompatible")
209 if options.debug:
209 if options.debug:
210 if options.timeout != defaults['timeout']:
210 if options.timeout != defaults['timeout']:
211 sys.stderr.write(
211 sys.stderr.write(
212 'warning: --timeout option ignored with --debug\n')
212 'warning: --timeout option ignored with --debug\n')
213 options.timeout = 0
213 options.timeout = 0
214 if options.py3k_warnings:
214 if options.py3k_warnings:
215 if sys.version_info[:2] < (2, 6) or sys.version_info[:2] >= (3, 0):
215 if sys.version_info[:2] < (2, 6) or sys.version_info[:2] >= (3, 0):
216 parser.error('--py3k-warnings can only be used on Python 2.6+')
216 parser.error('--py3k-warnings can only be used on Python 2.6+')
217 if options.blacklist:
217 if options.blacklist:
218 blacklist = dict()
218 blacklist = dict()
219 for filename in options.blacklist:
219 for filename in options.blacklist:
220 try:
220 try:
221 path = os.path.expanduser(os.path.expandvars(filename))
221 path = os.path.expanduser(os.path.expandvars(filename))
222 f = open(path, "r")
222 f = open(path, "r")
223 except IOError, err:
223 except IOError, err:
224 if err.errno != errno.ENOENT:
224 if err.errno != errno.ENOENT:
225 raise
225 raise
226 print "warning: no such blacklist file: %s" % filename
226 print "warning: no such blacklist file: %s" % filename
227 continue
227 continue
228
228
229 for line in f.readlines():
229 for line in f.readlines():
230 line = line.strip()
230 line = line.strip()
231 if line and not line.startswith('#'):
231 if line and not line.startswith('#'):
232 blacklist[line] = filename
232 blacklist[line] = filename
233
233
234 options.blacklist = blacklist
234 options.blacklist = blacklist
235
235
236 return (options, args)
236 return (options, args)
237
237
238 def rename(src, dst):
238 def rename(src, dst):
239 """Like os.rename(), trade atomicity and opened files friendliness
239 """Like os.rename(), trade atomicity and opened files friendliness
240 for existing destination support.
240 for existing destination support.
241 """
241 """
242 shutil.copy(src, dst)
242 shutil.copy(src, dst)
243 os.remove(src)
243 os.remove(src)
244
244
245 def splitnewlines(text):
245 def splitnewlines(text):
246 '''like str.splitlines, but only split on newlines.
246 '''like str.splitlines, but only split on newlines.
247 keep line endings.'''
247 keep line endings.'''
248 i = 0
248 i = 0
249 lines = []
249 lines = []
250 while True:
250 while True:
251 n = text.find('\n', i)
251 n = text.find('\n', i)
252 if n == -1:
252 if n == -1:
253 last = text[i:]
253 last = text[i:]
254 if last:
254 if last:
255 lines.append(last)
255 lines.append(last)
256 return lines
256 return lines
257 lines.append(text[i:n + 1])
257 lines.append(text[i:n + 1])
258 i = n + 1
258 i = n + 1
259
259
260 def parsehghaveoutput(lines):
260 def parsehghaveoutput(lines):
261 '''Parse hghave log lines.
261 '''Parse hghave log lines.
262 Return tuple of lists (missing, failed):
262 Return tuple of lists (missing, failed):
263 * the missing/unknown features
263 * the missing/unknown features
264 * the features for which existence check failed'''
264 * the features for which existence check failed'''
265 missing = []
265 missing = []
266 failed = []
266 failed = []
267 for line in lines:
267 for line in lines:
268 if line.startswith(SKIPPED_PREFIX):
268 if line.startswith(SKIPPED_PREFIX):
269 line = line.splitlines()[0]
269 line = line.splitlines()[0]
270 missing.append(line[len(SKIPPED_PREFIX):])
270 missing.append(line[len(SKIPPED_PREFIX):])
271 elif line.startswith(FAILED_PREFIX):
271 elif line.startswith(FAILED_PREFIX):
272 line = line.splitlines()[0]
272 line = line.splitlines()[0]
273 failed.append(line[len(FAILED_PREFIX):])
273 failed.append(line[len(FAILED_PREFIX):])
274
274
275 return missing, failed
275 return missing, failed
276
276
277 def showdiff(expected, output, ref, err):
277 def showdiff(expected, output, ref, err):
278 for line in difflib.unified_diff(expected, output, ref, err):
278 for line in difflib.unified_diff(expected, output, ref, err):
279 sys.stdout.write(line)
279 sys.stdout.write(line)
280
280
281 def findprogram(program):
281 def findprogram(program):
282 """Search PATH for a executable program"""
282 """Search PATH for a executable program"""
283 for p in os.environ.get('PATH', os.defpath).split(os.pathsep):
283 for p in os.environ.get('PATH', os.defpath).split(os.pathsep):
284 name = os.path.join(p, program)
284 name = os.path.join(p, program)
285 if os.access(name, os.X_OK):
285 if os.access(name, os.X_OK):
286 return name
286 return name
287 return None
287 return None
288
288
289 def checktools():
289 def checktools():
290 # Before we go any further, check for pre-requisite tools
290 # Before we go any further, check for pre-requisite tools
291 # stuff from coreutils (cat, rm, etc) are not tested
291 # stuff from coreutils (cat, rm, etc) are not tested
292 for p in requiredtools:
292 for p in requiredtools:
293 if os.name == 'nt':
293 if os.name == 'nt':
294 p += '.exe'
294 p += '.exe'
295 found = findprogram(p)
295 found = findprogram(p)
296 if found:
296 if found:
297 vlog("# Found prerequisite", p, "at", found)
297 vlog("# Found prerequisite", p, "at", found)
298 else:
298 else:
299 print "WARNING: Did not find prerequisite tool: "+p
299 print "WARNING: Did not find prerequisite tool: "+p
300
300
301 def killdaemons():
301 def killdaemons():
302 # Kill off any leftover daemon processes
302 # Kill off any leftover daemon processes
303 try:
303 try:
304 fp = open(DAEMON_PIDS)
304 fp = open(DAEMON_PIDS)
305 for line in fp:
305 for line in fp:
306 try:
306 try:
307 pid = int(line)
307 pid = int(line)
308 except ValueError:
308 except ValueError:
309 continue
309 continue
310 try:
310 try:
311 os.kill(pid, 0)
311 os.kill(pid, 0)
312 vlog('# Killing daemon process %d' % pid)
312 vlog('# Killing daemon process %d' % pid)
313 os.kill(pid, signal.SIGTERM)
313 os.kill(pid, signal.SIGTERM)
314 time.sleep(0.25)
314 time.sleep(0.25)
315 os.kill(pid, 0)
315 os.kill(pid, 0)
316 vlog('# Daemon process %d is stuck - really killing it' % pid)
316 vlog('# Daemon process %d is stuck - really killing it' % pid)
317 os.kill(pid, signal.SIGKILL)
317 os.kill(pid, signal.SIGKILL)
318 except OSError, err:
318 except OSError, err:
319 if err.errno != errno.ESRCH:
319 if err.errno != errno.ESRCH:
320 raise
320 raise
321 fp.close()
321 fp.close()
322 os.unlink(DAEMON_PIDS)
322 os.unlink(DAEMON_PIDS)
323 except IOError:
323 except IOError:
324 pass
324 pass
325
325
326 def cleanup(options):
326 def cleanup(options):
327 if not options.keep_tmpdir:
327 if not options.keep_tmpdir:
328 vlog("# Cleaning up HGTMP", HGTMP)
328 vlog("# Cleaning up HGTMP", HGTMP)
329 shutil.rmtree(HGTMP, True)
329 shutil.rmtree(HGTMP, True)
330
330
331 def usecorrectpython():
331 def usecorrectpython():
332 # some tests run python interpreter. they must use same
332 # some tests run python interpreter. they must use same
333 # interpreter we use or bad things will happen.
333 # interpreter we use or bad things will happen.
334 exedir, exename = os.path.split(sys.executable)
334 exedir, exename = os.path.split(sys.executable)
335 if exename == 'python':
335 if exename == 'python':
336 path = findprogram('python')
336 path = findprogram('python')
337 if os.path.dirname(path) == exedir:
337 if os.path.dirname(path) == exedir:
338 return
338 return
339 vlog('# Making python executable in test path use correct Python')
339 vlog('# Making python executable in test path use correct Python')
340 mypython = os.path.join(BINDIR, 'python')
340 mypython = os.path.join(BINDIR, 'python')
341 try:
341 try:
342 os.symlink(sys.executable, mypython)
342 os.symlink(sys.executable, mypython)
343 except AttributeError:
343 except AttributeError:
344 # windows fallback
344 # windows fallback
345 shutil.copyfile(sys.executable, mypython)
345 shutil.copyfile(sys.executable, mypython)
346 shutil.copymode(sys.executable, mypython)
346 shutil.copymode(sys.executable, mypython)
347
347
348 def installhg(options):
348 def installhg(options):
349 vlog("# Performing temporary installation of HG")
349 vlog("# Performing temporary installation of HG")
350 installerrs = os.path.join("tests", "install.err")
350 installerrs = os.path.join("tests", "install.err")
351 pure = options.pure and "--pure" or ""
351 pure = options.pure and "--pure" or ""
352
352
353 # Run installer in hg root
353 # Run installer in hg root
354 script = os.path.realpath(sys.argv[0])
354 script = os.path.realpath(sys.argv[0])
355 hgroot = os.path.dirname(os.path.dirname(script))
355 hgroot = os.path.dirname(os.path.dirname(script))
356 os.chdir(hgroot)
356 os.chdir(hgroot)
357 nohome = '--home=""'
357 nohome = '--home=""'
358 if os.name == 'nt':
358 if os.name == 'nt':
359 # The --home="" trick works only on OS where os.sep == '/'
359 # The --home="" trick works only on OS where os.sep == '/'
360 # because of a distutils convert_path() fast-path. Avoid it at
360 # because of a distutils convert_path() fast-path. Avoid it at
361 # least on Windows for now, deal with .pydistutils.cfg bugs
361 # least on Windows for now, deal with .pydistutils.cfg bugs
362 # when they happen.
362 # when they happen.
363 nohome = ''
363 nohome = ''
364 cmd = ('%s setup.py %s clean --all'
364 cmd = ('%s setup.py %s clean --all'
365 ' build --build-base="%s"'
365 ' build --build-base="%s"'
366 ' install --force --prefix="%s" --install-lib="%s"'
366 ' install --force --prefix="%s" --install-lib="%s"'
367 ' --install-scripts="%s" %s >%s 2>&1'
367 ' --install-scripts="%s" %s >%s 2>&1'
368 % (sys.executable, pure, os.path.join(HGTMP, "build"),
368 % (sys.executable, pure, os.path.join(HGTMP, "build"),
369 INST, PYTHONDIR, BINDIR, nohome, installerrs))
369 INST, PYTHONDIR, BINDIR, nohome, installerrs))
370 vlog("# Running", cmd)
370 vlog("# Running", cmd)
371 if os.system(cmd) == 0:
371 if os.system(cmd) == 0:
372 if not options.verbose:
372 if not options.verbose:
373 os.remove(installerrs)
373 os.remove(installerrs)
374 else:
374 else:
375 f = open(installerrs)
375 f = open(installerrs)
376 for line in f:
376 for line in f:
377 print line,
377 print line,
378 f.close()
378 f.close()
379 sys.exit(1)
379 sys.exit(1)
380 os.chdir(TESTDIR)
380 os.chdir(TESTDIR)
381
381
382 usecorrectpython()
382 usecorrectpython()
383
383
384 vlog("# Installing dummy diffstat")
384 vlog("# Installing dummy diffstat")
385 f = open(os.path.join(BINDIR, 'diffstat'), 'w')
385 f = open(os.path.join(BINDIR, 'diffstat'), 'w')
386 f.write('#!' + sys.executable + '\n'
386 f.write('#!' + sys.executable + '\n'
387 'import sys\n'
387 'import sys\n'
388 'files = 0\n'
388 'files = 0\n'
389 'for line in sys.stdin:\n'
389 'for line in sys.stdin:\n'
390 ' if line.startswith("diff "):\n'
390 ' if line.startswith("diff "):\n'
391 ' files += 1\n'
391 ' files += 1\n'
392 'sys.stdout.write("files patched: %d\\n" % files)\n')
392 'sys.stdout.write("files patched: %d\\n" % files)\n')
393 f.close()
393 f.close()
394 os.chmod(os.path.join(BINDIR, 'diffstat'), 0700)
394 os.chmod(os.path.join(BINDIR, 'diffstat'), 0700)
395
395
396 if options.py3k_warnings and not options.anycoverage:
396 if options.py3k_warnings and not options.anycoverage:
397 vlog("# Updating hg command to enable Py3k Warnings switch")
397 vlog("# Updating hg command to enable Py3k Warnings switch")
398 f = open(os.path.join(BINDIR, 'hg'), 'r')
398 f = open(os.path.join(BINDIR, 'hg'), 'r')
399 lines = [line.rstrip() for line in f]
399 lines = [line.rstrip() for line in f]
400 lines[0] += ' -3'
400 lines[0] += ' -3'
401 f.close()
401 f.close()
402 f = open(os.path.join(BINDIR, 'hg'), 'w')
402 f = open(os.path.join(BINDIR, 'hg'), 'w')
403 for line in lines:
403 for line in lines:
404 f.write(line + '\n')
404 f.write(line + '\n')
405 f.close()
405 f.close()
406
406
407 if options.anycoverage:
407 if options.anycoverage:
408 custom = os.path.join(TESTDIR, 'sitecustomize.py')
408 custom = os.path.join(TESTDIR, 'sitecustomize.py')
409 target = os.path.join(PYTHONDIR, 'sitecustomize.py')
409 target = os.path.join(PYTHONDIR, 'sitecustomize.py')
410 vlog('# Installing coverage trigger to %s' % target)
410 vlog('# Installing coverage trigger to %s' % target)
411 shutil.copyfile(custom, target)
411 shutil.copyfile(custom, target)
412 rc = os.path.join(TESTDIR, '.coveragerc')
412 rc = os.path.join(TESTDIR, '.coveragerc')
413 vlog('# Installing coverage rc to %s' % rc)
413 vlog('# Installing coverage rc to %s' % rc)
414 os.environ['COVERAGE_PROCESS_START'] = rc
414 os.environ['COVERAGE_PROCESS_START'] = rc
415 fn = os.path.join(INST, '..', '.coverage')
415 fn = os.path.join(INST, '..', '.coverage')
416 os.environ['COVERAGE_FILE'] = fn
416 os.environ['COVERAGE_FILE'] = fn
417
417
418 def outputcoverage(options):
418 def outputcoverage(options):
419
419
420 vlog('# Producing coverage report')
420 vlog('# Producing coverage report')
421 os.chdir(PYTHONDIR)
421 os.chdir(PYTHONDIR)
422
422
423 def covrun(*args):
423 def covrun(*args):
424 cmd = 'coverage %s' % ' '.join(args)
424 cmd = 'coverage %s' % ' '.join(args)
425 vlog('# Running: %s' % cmd)
425 vlog('# Running: %s' % cmd)
426 os.system(cmd)
426 os.system(cmd)
427
427
428 if options.child:
428 if options.child:
429 return
429 return
430
430
431 covrun('-c')
431 covrun('-c')
432 omit = ','.join([BINDIR, TESTDIR])
432 omit = ','.join([BINDIR, TESTDIR])
433 covrun('-i', '-r', '"--omit=%s"' % omit) # report
433 covrun('-i', '-r', '"--omit=%s"' % omit) # report
434 if options.annotate:
434 if options.annotate:
435 adir = os.path.join(TESTDIR, 'annotated')
435 adir = os.path.join(TESTDIR, 'annotated')
436 if not os.path.isdir(adir):
436 if not os.path.isdir(adir):
437 os.mkdir(adir)
437 os.mkdir(adir)
438 covrun('-i', '-a', '"--directory=%s"' % adir, '"--omit=%s"' % omit)
438 covrun('-i', '-a', '"--directory=%s"' % adir, '"--omit=%s"' % omit)
439
439
440 class Timeout(Exception):
440 class Timeout(Exception):
441 pass
441 pass
442
442
443 def alarmed(signum, frame):
443 def alarmed(signum, frame):
444 raise Timeout
444 raise Timeout
445
445
446 def pytest(test, options, replacements):
446 def pytest(test, options, replacements):
447 py3kswitch = options.py3k_warnings and ' -3' or ''
447 py3kswitch = options.py3k_warnings and ' -3' or ''
448 cmd = '%s%s "%s"' % (PYTHON, py3kswitch, test)
448 cmd = '%s%s "%s"' % (PYTHON, py3kswitch, test)
449 vlog("# Running", cmd)
449 vlog("# Running", cmd)
450 return run(cmd, options, replacements)
450 return run(cmd, options, replacements)
451
451
452 def shtest(test, options, replacements):
452 def shtest(test, options, replacements):
453 cmd = '"%s"' % test
453 cmd = '"%s"' % test
454 vlog("# Running", cmd)
454 vlog("# Running", cmd)
455 return run(cmd, options, replacements)
455 return run(cmd, options, replacements)
456
456
457 needescape = re.compile(r'[\x00-\x08\x0b-\x1f\x7f-\xff]').search
457 needescape = re.compile(r'[\x00-\x08\x0b-\x1f\x7f-\xff]').search
458 escapesub = re.compile(r'[\x00-\x08\x0b-\x1f\\\x7f-\xff]').sub
458 escapesub = re.compile(r'[\x00-\x08\x0b-\x1f\\\x7f-\xff]').sub
459 escapemap = dict((chr(i), r'\x%02x' % i) for i in range(256))
459 escapemap = dict((chr(i), r'\x%02x' % i) for i in range(256))
460 escapemap.update({'\\': '\\\\', '\r': r'\r'})
460 escapemap.update({'\\': '\\\\', '\r': r'\r'})
461 def escapef(m):
461 def escapef(m):
462 return escapemap[m.group(0)]
462 return escapemap[m.group(0)]
463 def stringescape(s):
463 def stringescape(s):
464 return escapesub(escapef, s)
464 return escapesub(escapef, s)
465
465
466 def tsttest(test, options, replacements):
466 def tsttest(test, options, replacements):
467 t = open(test)
467 t = open(test)
468 out = []
468 out = []
469 script = []
469 script = []
470 salt = "SALT" + str(time.time())
470 salt = "SALT" + str(time.time())
471
471
472 pos = prepos = -1
472 pos = prepos = -1
473 after = {}
473 after = {}
474 expected = {}
474 expected = {}
475 for n, l in enumerate(t):
475 for n, l in enumerate(t):
476 if not l.endswith('\n'):
476 if not l.endswith('\n'):
477 l += '\n'
477 l += '\n'
478 if l.startswith(' $ '): # commands
478 if l.startswith(' $ '): # commands
479 after.setdefault(pos, []).append(l)
479 after.setdefault(pos, []).append(l)
480 prepos = pos
480 prepos = pos
481 pos = n
481 pos = n
482 script.append('echo %s %s $?\n' % (salt, n))
482 script.append('echo %s %s $?\n' % (salt, n))
483 script.append(l[4:])
483 script.append(l[4:])
484 elif l.startswith(' > '): # continuations
484 elif l.startswith(' > '): # continuations
485 after.setdefault(prepos, []).append(l)
485 after.setdefault(prepos, []).append(l)
486 script.append(l[4:])
486 script.append(l[4:])
487 elif l.startswith(' '): # results
487 elif l.startswith(' '): # results
488 # queue up a list of expected results
488 # queue up a list of expected results
489 expected.setdefault(pos, []).append(l[2:])
489 expected.setdefault(pos, []).append(l[2:])
490 else:
490 else:
491 # non-command/result - queue up for merged output
491 # non-command/result - queue up for merged output
492 after.setdefault(pos, []).append(l)
492 after.setdefault(pos, []).append(l)
493
493
494 script.append('echo %s %s $?\n' % (salt, n + 1))
494 script.append('echo %s %s $?\n' % (salt, n + 1))
495
495
496 fd, name = tempfile.mkstemp(suffix='hg-tst')
496 fd, name = tempfile.mkstemp(suffix='hg-tst')
497
497
498 try:
498 try:
499 for l in script:
499 for l in script:
500 os.write(fd, l)
500 os.write(fd, l)
501 os.close(fd)
501 os.close(fd)
502
502
503 cmd = '/bin/sh "%s"' % name
503 cmd = '/bin/sh "%s"' % name
504 vlog("# Running", cmd)
504 vlog("# Running", cmd)
505 exitcode, output = run(cmd, options, replacements)
505 exitcode, output = run(cmd, options, replacements)
506 # do not merge output if skipped, return hghave message instead
506 # do not merge output if skipped, return hghave message instead
507 if exitcode == SKIPPED_STATUS:
507 # similarly, with --debug, output is None
508 if exitcode == SKIPPED_STATUS or output is None:
508 return exitcode, output
509 return exitcode, output
509 finally:
510 finally:
510 os.remove(name)
511 os.remove(name)
511
512
512 def rematch(el, l):
513 def rematch(el, l):
513 try:
514 try:
514 # ensure that the regex matches to the end of the string
515 # ensure that the regex matches to the end of the string
515 return re.match(el + r'\Z', l)
516 return re.match(el + r'\Z', l)
516 except re.error:
517 except re.error:
517 # el is an invalid regex
518 # el is an invalid regex
518 return False
519 return False
519
520
520 def globmatch(el, l):
521 def globmatch(el, l):
521 # The only supported special characters are * and ?. Escaping is
522 # The only supported special characters are * and ?. Escaping is
522 # supported.
523 # supported.
523 i, n = 0, len(el)
524 i, n = 0, len(el)
524 res = ''
525 res = ''
525 while i < n:
526 while i < n:
526 c = el[i]
527 c = el[i]
527 i += 1
528 i += 1
528 if c == '\\' and el[i] in '*?\\':
529 if c == '\\' and el[i] in '*?\\':
529 res += el[i - 1:i + 1]
530 res += el[i - 1:i + 1]
530 i += 1
531 i += 1
531 elif c == '*':
532 elif c == '*':
532 res += '.*'
533 res += '.*'
533 elif c == '?':
534 elif c == '?':
534 res += '.'
535 res += '.'
535 else:
536 else:
536 res += re.escape(c)
537 res += re.escape(c)
537 return rematch(res, l)
538 return rematch(res, l)
538
539
539 pos = -1
540 pos = -1
540 postout = []
541 postout = []
541 ret = 0
542 ret = 0
542 for n, l in enumerate(output):
543 for n, l in enumerate(output):
543 lout, lcmd = l, None
544 lout, lcmd = l, None
544 if salt in l:
545 if salt in l:
545 lout, lcmd = l.split(salt, 1)
546 lout, lcmd = l.split(salt, 1)
546
547
547 if lout:
548 if lout:
548 if lcmd:
549 if lcmd:
549 lout += ' (no-eol)\n'
550 lout += ' (no-eol)\n'
550
551
551 el = None
552 el = None
552 if pos in expected and expected[pos]:
553 if pos in expected and expected[pos]:
553 el = expected[pos].pop(0)
554 el = expected[pos].pop(0)
554
555
555 if el == lout: # perfect match (fast)
556 if el == lout: # perfect match (fast)
556 postout.append(" " + lout)
557 postout.append(" " + lout)
557 elif (el and
558 elif (el and
558 (el.endswith(" (re)\n") and rematch(el[:-6] + '\n', lout) or
559 (el.endswith(" (re)\n") and rematch(el[:-6] + '\n', lout) or
559 el.endswith(" (glob)\n") and globmatch(el[:-8] + '\n', lout)
560 el.endswith(" (glob)\n") and globmatch(el[:-8] + '\n', lout)
560 or el.endswith(" (esc)\n") and
561 or el.endswith(" (esc)\n") and
561 el.decode('string-escape') == l)):
562 el.decode('string-escape') == l)):
562 postout.append(" " + el) # fallback regex/glob/esc match
563 postout.append(" " + el) # fallback regex/glob/esc match
563 else:
564 else:
564 if needescape(lout):
565 if needescape(lout):
565 lout = stringescape(lout.rstrip('\n')) + " (esc)\n"
566 lout = stringescape(lout.rstrip('\n')) + " (esc)\n"
566 postout.append(" " + lout) # let diff deal with it
567 postout.append(" " + lout) # let diff deal with it
567
568
568 if lcmd:
569 if lcmd:
569 # add on last return code
570 # add on last return code
570 ret = int(lcmd.split()[1])
571 ret = int(lcmd.split()[1])
571 if ret != 0:
572 if ret != 0:
572 postout.append(" [%s]\n" % ret)
573 postout.append(" [%s]\n" % ret)
573 if pos in after:
574 if pos in after:
574 postout += after.pop(pos)
575 postout += after.pop(pos)
575 pos = int(lcmd.split()[0])
576 pos = int(lcmd.split()[0])
576
577
577 if pos in after:
578 if pos in after:
578 postout += after.pop(pos)
579 postout += after.pop(pos)
579
580
580 return exitcode, postout
581 return exitcode, postout
581
582
582 def run(cmd, options, replacements):
583 def run(cmd, options, replacements):
583 """Run command in a sub-process, capturing the output (stdout and stderr).
584 """Run command in a sub-process, capturing the output (stdout and stderr).
584 Return a tuple (exitcode, output). output is None in debug mode."""
585 Return a tuple (exitcode, output). output is None in debug mode."""
585 # TODO: Use subprocess.Popen if we're running on Python 2.4
586 # TODO: Use subprocess.Popen if we're running on Python 2.4
586 if options.debug:
587 if options.debug:
587 proc = subprocess.Popen(cmd, shell=True)
588 proc = subprocess.Popen(cmd, shell=True)
588 ret = proc.wait()
589 ret = proc.wait()
589 return (ret, None)
590 return (ret, None)
590
591
591 if os.name == 'nt' or sys.platform.startswith('java'):
592 if os.name == 'nt' or sys.platform.startswith('java'):
592 tochild, fromchild = os.popen4(cmd)
593 tochild, fromchild = os.popen4(cmd)
593 tochild.close()
594 tochild.close()
594 output = fromchild.read()
595 output = fromchild.read()
595 ret = fromchild.close()
596 ret = fromchild.close()
596 if ret == None:
597 if ret == None:
597 ret = 0
598 ret = 0
598 else:
599 else:
599 proc = Popen4(cmd)
600 proc = Popen4(cmd)
600 def cleanup():
601 def cleanup():
601 os.kill(proc.pid, signal.SIGTERM)
602 os.kill(proc.pid, signal.SIGTERM)
602 ret = proc.wait()
603 ret = proc.wait()
603 if ret == 0:
604 if ret == 0:
604 ret = signal.SIGTERM << 8
605 ret = signal.SIGTERM << 8
605 killdaemons()
606 killdaemons()
606 return ret
607 return ret
607
608
608 try:
609 try:
609 output = ''
610 output = ''
610 proc.tochild.close()
611 proc.tochild.close()
611 output = proc.fromchild.read()
612 output = proc.fromchild.read()
612 ret = proc.wait()
613 ret = proc.wait()
613 if os.WIFEXITED(ret):
614 if os.WIFEXITED(ret):
614 ret = os.WEXITSTATUS(ret)
615 ret = os.WEXITSTATUS(ret)
615 except Timeout:
616 except Timeout:
616 vlog('# Process %d timed out - killing it' % proc.pid)
617 vlog('# Process %d timed out - killing it' % proc.pid)
617 ret = cleanup()
618 ret = cleanup()
618 output += ("\n### Abort: timeout after %d seconds.\n"
619 output += ("\n### Abort: timeout after %d seconds.\n"
619 % options.timeout)
620 % options.timeout)
620 except KeyboardInterrupt:
621 except KeyboardInterrupt:
621 vlog('# Handling keyboard interrupt')
622 vlog('# Handling keyboard interrupt')
622 cleanup()
623 cleanup()
623 raise
624 raise
624
625
625 for s, r in replacements:
626 for s, r in replacements:
626 output = re.sub(s, r, output)
627 output = re.sub(s, r, output)
627 return ret, splitnewlines(output)
628 return ret, splitnewlines(output)
628
629
629 def runone(options, test, skips, fails):
630 def runone(options, test, skips, fails):
630 '''tristate output:
631 '''tristate output:
631 None -> skipped
632 None -> skipped
632 True -> passed
633 True -> passed
633 False -> failed'''
634 False -> failed'''
634
635
635 def skip(msg):
636 def skip(msg):
636 if not options.verbose:
637 if not options.verbose:
637 skips.append((test, msg))
638 skips.append((test, msg))
638 else:
639 else:
639 print "\nSkipping %s: %s" % (testpath, msg)
640 print "\nSkipping %s: %s" % (testpath, msg)
640 return None
641 return None
641
642
642 def fail(msg):
643 def fail(msg):
643 fails.append((test, msg))
644 fails.append((test, msg))
644 if not options.nodiff:
645 if not options.nodiff:
645 print "\nERROR: %s %s" % (testpath, msg)
646 print "\nERROR: %s %s" % (testpath, msg)
646 return None
647 return None
647
648
648 vlog("# Test", test)
649 vlog("# Test", test)
649
650
650 # create a fresh hgrc
651 # create a fresh hgrc
651 hgrc = open(HGRCPATH, 'w+')
652 hgrc = open(HGRCPATH, 'w+')
652 hgrc.write('[ui]\n')
653 hgrc.write('[ui]\n')
653 hgrc.write('slash = True\n')
654 hgrc.write('slash = True\n')
654 hgrc.write('[defaults]\n')
655 hgrc.write('[defaults]\n')
655 hgrc.write('backout = -d "0 0"\n')
656 hgrc.write('backout = -d "0 0"\n')
656 hgrc.write('commit = -d "0 0"\n')
657 hgrc.write('commit = -d "0 0"\n')
657 hgrc.write('tag = -d "0 0"\n')
658 hgrc.write('tag = -d "0 0"\n')
658 if options.inotify:
659 if options.inotify:
659 hgrc.write('[extensions]\n')
660 hgrc.write('[extensions]\n')
660 hgrc.write('inotify=\n')
661 hgrc.write('inotify=\n')
661 hgrc.write('[inotify]\n')
662 hgrc.write('[inotify]\n')
662 hgrc.write('pidfile=%s\n' % DAEMON_PIDS)
663 hgrc.write('pidfile=%s\n' % DAEMON_PIDS)
663 hgrc.write('appendpid=True\n')
664 hgrc.write('appendpid=True\n')
664 hgrc.close()
665 hgrc.close()
665
666
666 testpath = os.path.join(TESTDIR, test)
667 testpath = os.path.join(TESTDIR, test)
667 ref = os.path.join(TESTDIR, test+".out")
668 ref = os.path.join(TESTDIR, test+".out")
668 err = os.path.join(TESTDIR, test+".err")
669 err = os.path.join(TESTDIR, test+".err")
669 if os.path.exists(err):
670 if os.path.exists(err):
670 os.remove(err) # Remove any previous output files
671 os.remove(err) # Remove any previous output files
671 try:
672 try:
672 tf = open(testpath)
673 tf = open(testpath)
673 firstline = tf.readline().rstrip()
674 firstline = tf.readline().rstrip()
674 tf.close()
675 tf.close()
675 except:
676 except:
676 firstline = ''
677 firstline = ''
677 lctest = test.lower()
678 lctest = test.lower()
678
679
679 if lctest.endswith('.py') or firstline == '#!/usr/bin/env python':
680 if lctest.endswith('.py') or firstline == '#!/usr/bin/env python':
680 runner = pytest
681 runner = pytest
681 elif lctest.endswith('.t'):
682 elif lctest.endswith('.t'):
682 runner = tsttest
683 runner = tsttest
683 ref = testpath
684 ref = testpath
684 else:
685 else:
685 # do not try to run non-executable programs
686 # do not try to run non-executable programs
686 if not os.access(testpath, os.X_OK):
687 if not os.access(testpath, os.X_OK):
687 return skip("not executable")
688 return skip("not executable")
688 runner = shtest
689 runner = shtest
689
690
690 # Make a tmp subdirectory to work in
691 # Make a tmp subdirectory to work in
691 testtmp = os.environ["TESTTMP"] = os.path.join(HGTMP, test)
692 testtmp = os.environ["TESTTMP"] = os.path.join(HGTMP, test)
692 os.mkdir(testtmp)
693 os.mkdir(testtmp)
693 os.chdir(testtmp)
694 os.chdir(testtmp)
694
695
695 if options.timeout > 0:
696 if options.timeout > 0:
696 signal.alarm(options.timeout)
697 signal.alarm(options.timeout)
697
698
698 ret, out = runner(testpath, options, [
699 ret, out = runner(testpath, options, [
699 (re.escape(testtmp), '$TESTTMP'),
700 (re.escape(testtmp), '$TESTTMP'),
700 (r':%s\b' % options.port, ':$HGPORT'),
701 (r':%s\b' % options.port, ':$HGPORT'),
701 (r':%s\b' % (options.port + 1), ':$HGPORT1'),
702 (r':%s\b' % (options.port + 1), ':$HGPORT1'),
702 (r':%s\b' % (options.port + 2), ':$HGPORT2'),
703 (r':%s\b' % (options.port + 2), ':$HGPORT2'),
703 ])
704 ])
704 vlog("# Ret was:", ret)
705 vlog("# Ret was:", ret)
705
706
706 if options.timeout > 0:
707 if options.timeout > 0:
707 signal.alarm(0)
708 signal.alarm(0)
708
709
709 mark = '.'
710 mark = '.'
710
711
711 skipped = (ret == SKIPPED_STATUS)
712 skipped = (ret == SKIPPED_STATUS)
712
713
713 # If we're not in --debug mode and reference output file exists,
714 # If we're not in --debug mode and reference output file exists,
714 # check test output against it.
715 # check test output against it.
715 if options.debug:
716 if options.debug:
716 refout = None # to match out == None
717 refout = None # to match out == None
717 elif os.path.exists(ref):
718 elif os.path.exists(ref):
718 f = open(ref, "r")
719 f = open(ref, "r")
719 refout = splitnewlines(f.read())
720 refout = splitnewlines(f.read())
720 f.close()
721 f.close()
721 else:
722 else:
722 refout = []
723 refout = []
723
724
724 if (ret != 0 or out != refout) and not skipped and not options.debug:
725 if (ret != 0 or out != refout) and not skipped and not options.debug:
725 # Save errors to a file for diagnosis
726 # Save errors to a file for diagnosis
726 f = open(err, "wb")
727 f = open(err, "wb")
727 for line in out:
728 for line in out:
728 f.write(line)
729 f.write(line)
729 f.close()
730 f.close()
730
731
731 if skipped:
732 if skipped:
732 mark = 's'
733 mark = 's'
733 if out is None: # debug mode: nothing to parse
734 if out is None: # debug mode: nothing to parse
734 missing = ['unknown']
735 missing = ['unknown']
735 failed = None
736 failed = None
736 else:
737 else:
737 missing, failed = parsehghaveoutput(out)
738 missing, failed = parsehghaveoutput(out)
738 if not missing:
739 if not missing:
739 missing = ['irrelevant']
740 missing = ['irrelevant']
740 if failed:
741 if failed:
741 fail("hghave failed checking for %s" % failed[-1])
742 fail("hghave failed checking for %s" % failed[-1])
742 skipped = False
743 skipped = False
743 else:
744 else:
744 skip(missing[-1])
745 skip(missing[-1])
745 elif out != refout:
746 elif out != refout:
746 mark = '!'
747 mark = '!'
747 if ret:
748 if ret:
748 fail("output changed and returned error code %d" % ret)
749 fail("output changed and returned error code %d" % ret)
749 else:
750 else:
750 fail("output changed")
751 fail("output changed")
751 if not options.nodiff:
752 if not options.nodiff:
752 if options.view:
753 if options.view:
753 os.system("%s %s %s" % (options.view, ref, err))
754 os.system("%s %s %s" % (options.view, ref, err))
754 else:
755 else:
755 showdiff(refout, out, ref, err)
756 showdiff(refout, out, ref, err)
756 ret = 1
757 ret = 1
757 elif ret:
758 elif ret:
758 mark = '!'
759 mark = '!'
759 fail("returned error code %d" % ret)
760 fail("returned error code %d" % ret)
760
761
761 if not options.verbose:
762 if not options.verbose:
762 sys.stdout.write(mark)
763 sys.stdout.write(mark)
763 sys.stdout.flush()
764 sys.stdout.flush()
764
765
765 killdaemons()
766 killdaemons()
766
767
767 os.chdir(TESTDIR)
768 os.chdir(TESTDIR)
768 if not options.keep_tmpdir:
769 if not options.keep_tmpdir:
769 shutil.rmtree(testtmp, True)
770 shutil.rmtree(testtmp, True)
770 if skipped:
771 if skipped:
771 return None
772 return None
772 return ret == 0
773 return ret == 0
773
774
774 _hgpath = None
775 _hgpath = None
775
776
776 def _gethgpath():
777 def _gethgpath():
777 """Return the path to the mercurial package that is actually found by
778 """Return the path to the mercurial package that is actually found by
778 the current Python interpreter."""
779 the current Python interpreter."""
779 global _hgpath
780 global _hgpath
780 if _hgpath is not None:
781 if _hgpath is not None:
781 return _hgpath
782 return _hgpath
782
783
783 cmd = '%s -c "import mercurial; print mercurial.__path__[0]"'
784 cmd = '%s -c "import mercurial; print mercurial.__path__[0]"'
784 pipe = os.popen(cmd % PYTHON)
785 pipe = os.popen(cmd % PYTHON)
785 try:
786 try:
786 _hgpath = pipe.read().strip()
787 _hgpath = pipe.read().strip()
787 finally:
788 finally:
788 pipe.close()
789 pipe.close()
789 return _hgpath
790 return _hgpath
790
791
791 def _checkhglib(verb):
792 def _checkhglib(verb):
792 """Ensure that the 'mercurial' package imported by python is
793 """Ensure that the 'mercurial' package imported by python is
793 the one we expect it to be. If not, print a warning to stderr."""
794 the one we expect it to be. If not, print a warning to stderr."""
794 expecthg = os.path.join(PYTHONDIR, 'mercurial')
795 expecthg = os.path.join(PYTHONDIR, 'mercurial')
795 actualhg = _gethgpath()
796 actualhg = _gethgpath()
796 if actualhg != expecthg:
797 if actualhg != expecthg:
797 sys.stderr.write('warning: %s with unexpected mercurial lib: %s\n'
798 sys.stderr.write('warning: %s with unexpected mercurial lib: %s\n'
798 ' (expected %s)\n'
799 ' (expected %s)\n'
799 % (verb, actualhg, expecthg))
800 % (verb, actualhg, expecthg))
800
801
801 def runchildren(options, tests):
802 def runchildren(options, tests):
802 if INST:
803 if INST:
803 installhg(options)
804 installhg(options)
804 _checkhglib("Testing")
805 _checkhglib("Testing")
805
806
806 optcopy = dict(options.__dict__)
807 optcopy = dict(options.__dict__)
807 optcopy['jobs'] = 1
808 optcopy['jobs'] = 1
808 del optcopy['blacklist']
809 del optcopy['blacklist']
809 if optcopy['with_hg'] is None:
810 if optcopy['with_hg'] is None:
810 optcopy['with_hg'] = os.path.join(BINDIR, "hg")
811 optcopy['with_hg'] = os.path.join(BINDIR, "hg")
811 optcopy.pop('anycoverage', None)
812 optcopy.pop('anycoverage', None)
812
813
813 opts = []
814 opts = []
814 for opt, value in optcopy.iteritems():
815 for opt, value in optcopy.iteritems():
815 name = '--' + opt.replace('_', '-')
816 name = '--' + opt.replace('_', '-')
816 if value is True:
817 if value is True:
817 opts.append(name)
818 opts.append(name)
818 elif value is not None:
819 elif value is not None:
819 opts.append(name + '=' + str(value))
820 opts.append(name + '=' + str(value))
820
821
821 tests.reverse()
822 tests.reverse()
822 jobs = [[] for j in xrange(options.jobs)]
823 jobs = [[] for j in xrange(options.jobs)]
823 while tests:
824 while tests:
824 for job in jobs:
825 for job in jobs:
825 if not tests:
826 if not tests:
826 break
827 break
827 job.append(tests.pop())
828 job.append(tests.pop())
828 fps = {}
829 fps = {}
829
830
830 for j, job in enumerate(jobs):
831 for j, job in enumerate(jobs):
831 if not job:
832 if not job:
832 continue
833 continue
833 rfd, wfd = os.pipe()
834 rfd, wfd = os.pipe()
834 childopts = ['--child=%d' % wfd, '--port=%d' % (options.port + j * 3)]
835 childopts = ['--child=%d' % wfd, '--port=%d' % (options.port + j * 3)]
835 childtmp = os.path.join(HGTMP, 'child%d' % j)
836 childtmp = os.path.join(HGTMP, 'child%d' % j)
836 childopts += ['--tmpdir', childtmp]
837 childopts += ['--tmpdir', childtmp]
837 cmdline = [PYTHON, sys.argv[0]] + opts + childopts + job
838 cmdline = [PYTHON, sys.argv[0]] + opts + childopts + job
838 vlog(' '.join(cmdline))
839 vlog(' '.join(cmdline))
839 fps[os.spawnvp(os.P_NOWAIT, cmdline[0], cmdline)] = os.fdopen(rfd, 'r')
840 fps[os.spawnvp(os.P_NOWAIT, cmdline[0], cmdline)] = os.fdopen(rfd, 'r')
840 os.close(wfd)
841 os.close(wfd)
841 signal.signal(signal.SIGINT, signal.SIG_IGN)
842 signal.signal(signal.SIGINT, signal.SIG_IGN)
842 failures = 0
843 failures = 0
843 tested, skipped, failed = 0, 0, 0
844 tested, skipped, failed = 0, 0, 0
844 skips = []
845 skips = []
845 fails = []
846 fails = []
846 while fps:
847 while fps:
847 pid, status = os.wait()
848 pid, status = os.wait()
848 fp = fps.pop(pid)
849 fp = fps.pop(pid)
849 l = fp.read().splitlines()
850 l = fp.read().splitlines()
850 try:
851 try:
851 test, skip, fail = map(int, l[:3])
852 test, skip, fail = map(int, l[:3])
852 except ValueError:
853 except ValueError:
853 test, skip, fail = 0, 0, 0
854 test, skip, fail = 0, 0, 0
854 split = -fail or len(l)
855 split = -fail or len(l)
855 for s in l[3:split]:
856 for s in l[3:split]:
856 skips.append(s.split(" ", 1))
857 skips.append(s.split(" ", 1))
857 for s in l[split:]:
858 for s in l[split:]:
858 fails.append(s.split(" ", 1))
859 fails.append(s.split(" ", 1))
859 tested += test
860 tested += test
860 skipped += skip
861 skipped += skip
861 failed += fail
862 failed += fail
862 vlog('pid %d exited, status %d' % (pid, status))
863 vlog('pid %d exited, status %d' % (pid, status))
863 failures |= status
864 failures |= status
864 print
865 print
865 if not options.noskips:
866 if not options.noskips:
866 for s in skips:
867 for s in skips:
867 print "Skipped %s: %s" % (s[0], s[1])
868 print "Skipped %s: %s" % (s[0], s[1])
868 for s in fails:
869 for s in fails:
869 print "Failed %s: %s" % (s[0], s[1])
870 print "Failed %s: %s" % (s[0], s[1])
870
871
871 _checkhglib("Tested")
872 _checkhglib("Tested")
872 print "# Ran %d tests, %d skipped, %d failed." % (
873 print "# Ran %d tests, %d skipped, %d failed." % (
873 tested, skipped, failed)
874 tested, skipped, failed)
874
875
875 if options.anycoverage:
876 if options.anycoverage:
876 outputcoverage(options)
877 outputcoverage(options)
877 sys.exit(failures != 0)
878 sys.exit(failures != 0)
878
879
879 def runtests(options, tests):
880 def runtests(options, tests):
880 global DAEMON_PIDS, HGRCPATH
881 global DAEMON_PIDS, HGRCPATH
881 DAEMON_PIDS = os.environ["DAEMON_PIDS"] = os.path.join(HGTMP, 'daemon.pids')
882 DAEMON_PIDS = os.environ["DAEMON_PIDS"] = os.path.join(HGTMP, 'daemon.pids')
882 HGRCPATH = os.environ["HGRCPATH"] = os.path.join(HGTMP, '.hgrc')
883 HGRCPATH = os.environ["HGRCPATH"] = os.path.join(HGTMP, '.hgrc')
883
884
884 try:
885 try:
885 if INST:
886 if INST:
886 installhg(options)
887 installhg(options)
887 _checkhglib("Testing")
888 _checkhglib("Testing")
888
889
889 if options.timeout > 0:
890 if options.timeout > 0:
890 try:
891 try:
891 signal.signal(signal.SIGALRM, alarmed)
892 signal.signal(signal.SIGALRM, alarmed)
892 vlog('# Running each test with %d second timeout' %
893 vlog('# Running each test with %d second timeout' %
893 options.timeout)
894 options.timeout)
894 except AttributeError:
895 except AttributeError:
895 print 'WARNING: cannot run tests with timeouts'
896 print 'WARNING: cannot run tests with timeouts'
896 options.timeout = 0
897 options.timeout = 0
897
898
898 tested = 0
899 tested = 0
899 failed = 0
900 failed = 0
900 skipped = 0
901 skipped = 0
901
902
902 if options.restart:
903 if options.restart:
903 orig = list(tests)
904 orig = list(tests)
904 while tests:
905 while tests:
905 if os.path.exists(tests[0] + ".err"):
906 if os.path.exists(tests[0] + ".err"):
906 break
907 break
907 tests.pop(0)
908 tests.pop(0)
908 if not tests:
909 if not tests:
909 print "running all tests"
910 print "running all tests"
910 tests = orig
911 tests = orig
911
912
912 skips = []
913 skips = []
913 fails = []
914 fails = []
914
915
915 for test in tests:
916 for test in tests:
916 if options.blacklist:
917 if options.blacklist:
917 filename = options.blacklist.get(test)
918 filename = options.blacklist.get(test)
918 if filename is not None:
919 if filename is not None:
919 skips.append((test, "blacklisted (%s)" % filename))
920 skips.append((test, "blacklisted (%s)" % filename))
920 skipped += 1
921 skipped += 1
921 continue
922 continue
922
923
923 if options.retest and not os.path.exists(test + ".err"):
924 if options.retest and not os.path.exists(test + ".err"):
924 skipped += 1
925 skipped += 1
925 continue
926 continue
926
927
927 if options.keywords:
928 if options.keywords:
928 t = open(test).read().lower() + test.lower()
929 t = open(test).read().lower() + test.lower()
929 for k in options.keywords.lower().split():
930 for k in options.keywords.lower().split():
930 if k in t:
931 if k in t:
931 break
932 break
932 else:
933 else:
933 skipped += 1
934 skipped += 1
934 continue
935 continue
935
936
936 ret = runone(options, test, skips, fails)
937 ret = runone(options, test, skips, fails)
937 if ret is None:
938 if ret is None:
938 skipped += 1
939 skipped += 1
939 elif not ret:
940 elif not ret:
940 if options.interactive:
941 if options.interactive:
941 print "Accept this change? [n] ",
942 print "Accept this change? [n] ",
942 answer = sys.stdin.readline().strip()
943 answer = sys.stdin.readline().strip()
943 if answer.lower() in "y yes".split():
944 if answer.lower() in "y yes".split():
944 if test.endswith(".t"):
945 if test.endswith(".t"):
945 rename(test + ".err", test)
946 rename(test + ".err", test)
946 else:
947 else:
947 rename(test + ".err", test + ".out")
948 rename(test + ".err", test + ".out")
948 tested += 1
949 tested += 1
949 fails.pop()
950 fails.pop()
950 continue
951 continue
951 failed += 1
952 failed += 1
952 if options.first:
953 if options.first:
953 break
954 break
954 tested += 1
955 tested += 1
955
956
956 if options.child:
957 if options.child:
957 fp = os.fdopen(options.child, 'w')
958 fp = os.fdopen(options.child, 'w')
958 fp.write('%d\n%d\n%d\n' % (tested, skipped, failed))
959 fp.write('%d\n%d\n%d\n' % (tested, skipped, failed))
959 for s in skips:
960 for s in skips:
960 fp.write("%s %s\n" % s)
961 fp.write("%s %s\n" % s)
961 for s in fails:
962 for s in fails:
962 fp.write("%s %s\n" % s)
963 fp.write("%s %s\n" % s)
963 fp.close()
964 fp.close()
964 else:
965 else:
965 print
966 print
966 for s in skips:
967 for s in skips:
967 print "Skipped %s: %s" % s
968 print "Skipped %s: %s" % s
968 for s in fails:
969 for s in fails:
969 print "Failed %s: %s" % s
970 print "Failed %s: %s" % s
970 _checkhglib("Tested")
971 _checkhglib("Tested")
971 print "# Ran %d tests, %d skipped, %d failed." % (
972 print "# Ran %d tests, %d skipped, %d failed." % (
972 tested, skipped, failed)
973 tested, skipped, failed)
973
974
974 if options.anycoverage:
975 if options.anycoverage:
975 outputcoverage(options)
976 outputcoverage(options)
976 except KeyboardInterrupt:
977 except KeyboardInterrupt:
977 failed = True
978 failed = True
978 print "\ninterrupted!"
979 print "\ninterrupted!"
979
980
980 if failed:
981 if failed:
981 sys.exit(1)
982 sys.exit(1)
982
983
983 def main():
984 def main():
984 (options, args) = parseargs()
985 (options, args) = parseargs()
985 if not options.child:
986 if not options.child:
986 os.umask(022)
987 os.umask(022)
987
988
988 checktools()
989 checktools()
989
990
990 if len(args) == 0:
991 if len(args) == 0:
991 args = os.listdir(".")
992 args = os.listdir(".")
992 args.sort()
993 args.sort()
993
994
994 tests = []
995 tests = []
995 skipped = []
996 skipped = []
996 for test in args:
997 for test in args:
997 if (test.startswith("test-") and '~' not in test and
998 if (test.startswith("test-") and '~' not in test and
998 ('.' not in test or test.endswith('.py') or
999 ('.' not in test or test.endswith('.py') or
999 test.endswith('.bat') or test.endswith('.t'))):
1000 test.endswith('.bat') or test.endswith('.t'))):
1000 if not os.path.exists(test):
1001 if not os.path.exists(test):
1001 skipped.append(test)
1002 skipped.append(test)
1002 else:
1003 else:
1003 tests.append(test)
1004 tests.append(test)
1004 if not tests:
1005 if not tests:
1005 for test in skipped:
1006 for test in skipped:
1006 print 'Skipped %s: does not exist' % test
1007 print 'Skipped %s: does not exist' % test
1007 print "# Ran 0 tests, %d skipped, 0 failed." % len(skipped)
1008 print "# Ran 0 tests, %d skipped, 0 failed." % len(skipped)
1008 return
1009 return
1009 tests = tests + skipped
1010 tests = tests + skipped
1010
1011
1011 # Reset some environment variables to well-known values so that
1012 # Reset some environment variables to well-known values so that
1012 # the tests produce repeatable output.
1013 # the tests produce repeatable output.
1013 os.environ['LANG'] = os.environ['LC_ALL'] = os.environ['LANGUAGE'] = 'C'
1014 os.environ['LANG'] = os.environ['LC_ALL'] = os.environ['LANGUAGE'] = 'C'
1014 os.environ['TZ'] = 'GMT'
1015 os.environ['TZ'] = 'GMT'
1015 os.environ["EMAIL"] = "Foo Bar <foo.bar@example.com>"
1016 os.environ["EMAIL"] = "Foo Bar <foo.bar@example.com>"
1016 os.environ['CDPATH'] = ''
1017 os.environ['CDPATH'] = ''
1017 os.environ['COLUMNS'] = '80'
1018 os.environ['COLUMNS'] = '80'
1018 os.environ['GREP_OPTIONS'] = ''
1019 os.environ['GREP_OPTIONS'] = ''
1019 os.environ['http_proxy'] = ''
1020 os.environ['http_proxy'] = ''
1020
1021
1021 # unset env related to hooks
1022 # unset env related to hooks
1022 for k in os.environ.keys():
1023 for k in os.environ.keys():
1023 if k.startswith('HG_'):
1024 if k.startswith('HG_'):
1024 # can't remove on solaris
1025 # can't remove on solaris
1025 os.environ[k] = ''
1026 os.environ[k] = ''
1026 del os.environ[k]
1027 del os.environ[k]
1027
1028
1028 global TESTDIR, HGTMP, INST, BINDIR, PYTHONDIR, COVERAGE_FILE
1029 global TESTDIR, HGTMP, INST, BINDIR, PYTHONDIR, COVERAGE_FILE
1029 TESTDIR = os.environ["TESTDIR"] = os.getcwd()
1030 TESTDIR = os.environ["TESTDIR"] = os.getcwd()
1030 if options.tmpdir:
1031 if options.tmpdir:
1031 options.keep_tmpdir = True
1032 options.keep_tmpdir = True
1032 tmpdir = options.tmpdir
1033 tmpdir = options.tmpdir
1033 if os.path.exists(tmpdir):
1034 if os.path.exists(tmpdir):
1034 # Meaning of tmpdir has changed since 1.3: we used to create
1035 # Meaning of tmpdir has changed since 1.3: we used to create
1035 # HGTMP inside tmpdir; now HGTMP is tmpdir. So fail if
1036 # HGTMP inside tmpdir; now HGTMP is tmpdir. So fail if
1036 # tmpdir already exists.
1037 # tmpdir already exists.
1037 sys.exit("error: temp dir %r already exists" % tmpdir)
1038 sys.exit("error: temp dir %r already exists" % tmpdir)
1038
1039
1039 # Automatically removing tmpdir sounds convenient, but could
1040 # Automatically removing tmpdir sounds convenient, but could
1040 # really annoy anyone in the habit of using "--tmpdir=/tmp"
1041 # really annoy anyone in the habit of using "--tmpdir=/tmp"
1041 # or "--tmpdir=$HOME".
1042 # or "--tmpdir=$HOME".
1042 #vlog("# Removing temp dir", tmpdir)
1043 #vlog("# Removing temp dir", tmpdir)
1043 #shutil.rmtree(tmpdir)
1044 #shutil.rmtree(tmpdir)
1044 os.makedirs(tmpdir)
1045 os.makedirs(tmpdir)
1045 else:
1046 else:
1046 tmpdir = tempfile.mkdtemp('', 'hgtests.')
1047 tmpdir = tempfile.mkdtemp('', 'hgtests.')
1047 HGTMP = os.environ['HGTMP'] = os.path.realpath(tmpdir)
1048 HGTMP = os.environ['HGTMP'] = os.path.realpath(tmpdir)
1048 DAEMON_PIDS = None
1049 DAEMON_PIDS = None
1049 HGRCPATH = None
1050 HGRCPATH = None
1050
1051
1051 os.environ["HGEDITOR"] = sys.executable + ' -c "import sys; sys.exit(0)"'
1052 os.environ["HGEDITOR"] = sys.executable + ' -c "import sys; sys.exit(0)"'
1052 os.environ["HGMERGE"] = "internal:merge"
1053 os.environ["HGMERGE"] = "internal:merge"
1053 os.environ["HGUSER"] = "test"
1054 os.environ["HGUSER"] = "test"
1054 os.environ["HGENCODING"] = "ascii"
1055 os.environ["HGENCODING"] = "ascii"
1055 os.environ["HGENCODINGMODE"] = "strict"
1056 os.environ["HGENCODINGMODE"] = "strict"
1056 os.environ["HGPORT"] = str(options.port)
1057 os.environ["HGPORT"] = str(options.port)
1057 os.environ["HGPORT1"] = str(options.port + 1)
1058 os.environ["HGPORT1"] = str(options.port + 1)
1058 os.environ["HGPORT2"] = str(options.port + 2)
1059 os.environ["HGPORT2"] = str(options.port + 2)
1059
1060
1060 if options.with_hg:
1061 if options.with_hg:
1061 INST = None
1062 INST = None
1062 BINDIR = os.path.dirname(os.path.realpath(options.with_hg))
1063 BINDIR = os.path.dirname(os.path.realpath(options.with_hg))
1063
1064
1064 # This looks redundant with how Python initializes sys.path from
1065 # This looks redundant with how Python initializes sys.path from
1065 # the location of the script being executed. Needed because the
1066 # the location of the script being executed. Needed because the
1066 # "hg" specified by --with-hg is not the only Python script
1067 # "hg" specified by --with-hg is not the only Python script
1067 # executed in the test suite that needs to import 'mercurial'
1068 # executed in the test suite that needs to import 'mercurial'
1068 # ... which means it's not really redundant at all.
1069 # ... which means it's not really redundant at all.
1069 PYTHONDIR = BINDIR
1070 PYTHONDIR = BINDIR
1070 else:
1071 else:
1071 INST = os.path.join(HGTMP, "install")
1072 INST = os.path.join(HGTMP, "install")
1072 BINDIR = os.environ["BINDIR"] = os.path.join(INST, "bin")
1073 BINDIR = os.environ["BINDIR"] = os.path.join(INST, "bin")
1073 PYTHONDIR = os.path.join(INST, "lib", "python")
1074 PYTHONDIR = os.path.join(INST, "lib", "python")
1074
1075
1075 os.environ["BINDIR"] = BINDIR
1076 os.environ["BINDIR"] = BINDIR
1076 os.environ["PYTHON"] = PYTHON
1077 os.environ["PYTHON"] = PYTHON
1077
1078
1078 if not options.child:
1079 if not options.child:
1079 path = [BINDIR] + os.environ["PATH"].split(os.pathsep)
1080 path = [BINDIR] + os.environ["PATH"].split(os.pathsep)
1080 os.environ["PATH"] = os.pathsep.join(path)
1081 os.environ["PATH"] = os.pathsep.join(path)
1081
1082
1082 # Include TESTDIR in PYTHONPATH so that out-of-tree extensions
1083 # Include TESTDIR in PYTHONPATH so that out-of-tree extensions
1083 # can run .../tests/run-tests.py test-foo where test-foo
1084 # can run .../tests/run-tests.py test-foo where test-foo
1084 # adds an extension to HGRC
1085 # adds an extension to HGRC
1085 pypath = [PYTHONDIR, TESTDIR]
1086 pypath = [PYTHONDIR, TESTDIR]
1086 # We have to augment PYTHONPATH, rather than simply replacing
1087 # We have to augment PYTHONPATH, rather than simply replacing
1087 # it, in case external libraries are only available via current
1088 # it, in case external libraries are only available via current
1088 # PYTHONPATH. (In particular, the Subversion bindings on OS X
1089 # PYTHONPATH. (In particular, the Subversion bindings on OS X
1089 # are in /opt/subversion.)
1090 # are in /opt/subversion.)
1090 oldpypath = os.environ.get(IMPL_PATH)
1091 oldpypath = os.environ.get(IMPL_PATH)
1091 if oldpypath:
1092 if oldpypath:
1092 pypath.append(oldpypath)
1093 pypath.append(oldpypath)
1093 os.environ[IMPL_PATH] = os.pathsep.join(pypath)
1094 os.environ[IMPL_PATH] = os.pathsep.join(pypath)
1094
1095
1095 COVERAGE_FILE = os.path.join(TESTDIR, ".coverage")
1096 COVERAGE_FILE = os.path.join(TESTDIR, ".coverage")
1096
1097
1097 vlog("# Using TESTDIR", TESTDIR)
1098 vlog("# Using TESTDIR", TESTDIR)
1098 vlog("# Using HGTMP", HGTMP)
1099 vlog("# Using HGTMP", HGTMP)
1099 vlog("# Using PATH", os.environ["PATH"])
1100 vlog("# Using PATH", os.environ["PATH"])
1100 vlog("# Using", IMPL_PATH, os.environ[IMPL_PATH])
1101 vlog("# Using", IMPL_PATH, os.environ[IMPL_PATH])
1101
1102
1102 try:
1103 try:
1103 if len(tests) > 1 and options.jobs > 1:
1104 if len(tests) > 1 and options.jobs > 1:
1104 runchildren(options, tests)
1105 runchildren(options, tests)
1105 else:
1106 else:
1106 runtests(options, tests)
1107 runtests(options, tests)
1107 finally:
1108 finally:
1108 time.sleep(1)
1109 time.sleep(1)
1109 cleanup(options)
1110 cleanup(options)
1110
1111
1111 main()
1112 main()
General Comments 0
You need to be logged in to leave comments. Login now