##// END OF EJS Templates
tests: unset variable HG if it is set...
Simon Heimberg -
r17541:3e3dfa7e default
parent child Browse files
Show More
@@ -1,1304 +1,1308 b''
1 1 #!/usr/bin/env python
2 2 #
3 3 # run-tests.py - Run a set of tests on Mercurial
4 4 #
5 5 # Copyright 2006 Matt Mackall <mpm@selenic.com>
6 6 #
7 7 # This software may be used and distributed according to the terms of the
8 8 # GNU General Public License version 2 or any later version.
9 9
10 10 # Modifying this script is tricky because it has many modes:
11 11 # - serial (default) vs parallel (-jN, N > 1)
12 12 # - no coverage (default) vs coverage (-c, -C, -s)
13 13 # - temp install (default) vs specific hg script (--with-hg, --local)
14 14 # - tests are a mix of shell scripts and Python scripts
15 15 #
16 16 # If you change this script, it is recommended that you ensure you
17 17 # haven't broken it by running it in various modes with a representative
18 18 # sample of test scripts. For example:
19 19 #
20 20 # 1) serial, no coverage, temp install:
21 21 # ./run-tests.py test-s*
22 22 # 2) serial, no coverage, local hg:
23 23 # ./run-tests.py --local test-s*
24 24 # 3) serial, coverage, temp install:
25 25 # ./run-tests.py -c test-s*
26 26 # 4) serial, coverage, local hg:
27 27 # ./run-tests.py -c --local test-s* # unsupported
28 28 # 5) parallel, no coverage, temp install:
29 29 # ./run-tests.py -j2 test-s*
30 30 # 6) parallel, no coverage, local hg:
31 31 # ./run-tests.py -j2 --local test-s*
32 32 # 7) parallel, coverage, temp install:
33 33 # ./run-tests.py -j2 -c test-s* # currently broken
34 34 # 8) parallel, coverage, local install:
35 35 # ./run-tests.py -j2 -c --local test-s* # unsupported (and broken)
36 36 # 9) parallel, custom tmp dir:
37 37 # ./run-tests.py -j2 --tmpdir /tmp/myhgtests
38 38 #
39 39 # (You could use any subset of the tests: test-s* happens to match
40 40 # enough that it's worth doing parallel runs, few enough that it
41 41 # completes fairly quickly, includes both shell and Python scripts, and
42 42 # includes some scripts that run daemon processes.)
43 43
44 44 from distutils import version
45 45 import difflib
46 46 import errno
47 47 import optparse
48 48 import os
49 49 import shutil
50 50 import subprocess
51 51 import signal
52 52 import sys
53 53 import tempfile
54 54 import time
55 55 import re
56 56 import threading
57 57 import killdaemons as killmod
58 58
59 59 processlock = threading.Lock()
60 60
61 61 closefds = os.name == 'posix'
62 62 def Popen4(cmd, wd, timeout):
63 63 processlock.acquire()
64 64 p = subprocess.Popen(cmd, shell=True, bufsize=-1, cwd=wd,
65 65 close_fds=closefds,
66 66 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
67 67 stderr=subprocess.STDOUT)
68 68 processlock.release()
69 69
70 70 p.fromchild = p.stdout
71 71 p.tochild = p.stdin
72 72 p.childerr = p.stderr
73 73
74 74 p.timeout = False
75 75 if timeout:
76 76 def t():
77 77 start = time.time()
78 78 while time.time() - start < timeout and p.returncode is None:
79 79 time.sleep(.1)
80 80 p.timeout = True
81 81 if p.returncode is None:
82 82 terminate(p)
83 83 threading.Thread(target=t).start()
84 84
85 85 return p
86 86
87 87 # reserved exit code to skip test (used by hghave)
88 88 SKIPPED_STATUS = 80
89 89 SKIPPED_PREFIX = 'skipped: '
90 90 FAILED_PREFIX = 'hghave check failed: '
91 91 PYTHON = sys.executable.replace('\\', '/')
92 92 IMPL_PATH = 'PYTHONPATH'
93 93 if 'java' in sys.platform:
94 94 IMPL_PATH = 'JYTHONPATH'
95 95
96 96 requiredtools = ["python", "diff", "grep", "unzip", "gunzip", "bunzip2", "sed"]
97 97
98 98 defaults = {
99 99 'jobs': ('HGTEST_JOBS', 1),
100 100 'timeout': ('HGTEST_TIMEOUT', 180),
101 101 'port': ('HGTEST_PORT', 20059),
102 102 'shell': ('HGTEST_SHELL', 'sh'),
103 103 }
104 104
105 105 def parselistfiles(files, listtype, warn=True):
106 106 entries = dict()
107 107 for filename in files:
108 108 try:
109 109 path = os.path.expanduser(os.path.expandvars(filename))
110 110 f = open(path, "r")
111 111 except IOError, err:
112 112 if err.errno != errno.ENOENT:
113 113 raise
114 114 if warn:
115 115 print "warning: no such %s file: %s" % (listtype, filename)
116 116 continue
117 117
118 118 for line in f.readlines():
119 119 line = line.split('#', 1)[0].strip()
120 120 if line:
121 121 entries[line] = filename
122 122
123 123 f.close()
124 124 return entries
125 125
126 126 def parseargs():
127 127 parser = optparse.OptionParser("%prog [options] [tests]")
128 128
129 129 # keep these sorted
130 130 parser.add_option("--blacklist", action="append",
131 131 help="skip tests listed in the specified blacklist file")
132 132 parser.add_option("--whitelist", action="append",
133 133 help="always run tests listed in the specified whitelist file")
134 134 parser.add_option("-C", "--annotate", action="store_true",
135 135 help="output files annotated with coverage")
136 136 parser.add_option("--child", type="int",
137 137 help="run as child process, summary to given fd")
138 138 parser.add_option("-c", "--cover", action="store_true",
139 139 help="print a test coverage report")
140 140 parser.add_option("-d", "--debug", action="store_true",
141 141 help="debug mode: write output of test scripts to console"
142 142 " rather than capturing and diff'ing it (disables timeout)")
143 143 parser.add_option("-f", "--first", action="store_true",
144 144 help="exit on the first test failure")
145 145 parser.add_option("-H", "--htmlcov", action="store_true",
146 146 help="create an HTML report of the coverage of the files")
147 147 parser.add_option("--inotify", action="store_true",
148 148 help="enable inotify extension when running tests")
149 149 parser.add_option("-i", "--interactive", action="store_true",
150 150 help="prompt to accept changed output")
151 151 parser.add_option("-j", "--jobs", type="int",
152 152 help="number of jobs to run in parallel"
153 153 " (default: $%s or %d)" % defaults['jobs'])
154 154 parser.add_option("--keep-tmpdir", action="store_true",
155 155 help="keep temporary directory after running tests")
156 156 parser.add_option("-k", "--keywords",
157 157 help="run tests matching keywords")
158 158 parser.add_option("-l", "--local", action="store_true",
159 159 help="shortcut for --with-hg=<testdir>/../hg")
160 160 parser.add_option("-n", "--nodiff", action="store_true",
161 161 help="skip showing test changes")
162 162 parser.add_option("-p", "--port", type="int",
163 163 help="port on which servers should listen"
164 164 " (default: $%s or %d)" % defaults['port'])
165 165 parser.add_option("--pure", action="store_true",
166 166 help="use pure Python code instead of C extensions")
167 167 parser.add_option("-R", "--restart", action="store_true",
168 168 help="restart at last error")
169 169 parser.add_option("-r", "--retest", action="store_true",
170 170 help="retest failed tests")
171 171 parser.add_option("-S", "--noskips", action="store_true",
172 172 help="don't report skip tests verbosely")
173 173 parser.add_option("--shell", type="string",
174 174 help="shell to use (default: $%s or %s)" % defaults['shell'])
175 175 parser.add_option("-t", "--timeout", type="int",
176 176 help="kill errant tests after TIMEOUT seconds"
177 177 " (default: $%s or %d)" % defaults['timeout'])
178 178 parser.add_option("--tmpdir", type="string",
179 179 help="run tests in the given temporary directory"
180 180 " (implies --keep-tmpdir)")
181 181 parser.add_option("-v", "--verbose", action="store_true",
182 182 help="output verbose messages")
183 183 parser.add_option("--view", type="string",
184 184 help="external diff viewer")
185 185 parser.add_option("--with-hg", type="string",
186 186 metavar="HG",
187 187 help="test using specified hg script rather than a "
188 188 "temporary installation")
189 189 parser.add_option("-3", "--py3k-warnings", action="store_true",
190 190 help="enable Py3k warnings on Python 2.6+")
191 191 parser.add_option('--extra-config-opt', action="append",
192 192 help='set the given config opt in the test hgrc')
193 193
194 194 for option, (envvar, default) in defaults.items():
195 195 defaults[option] = type(default)(os.environ.get(envvar, default))
196 196 parser.set_defaults(**defaults)
197 197 (options, args) = parser.parse_args()
198 198
199 199 # jython is always pure
200 200 if 'java' in sys.platform or '__pypy__' in sys.modules:
201 201 options.pure = True
202 202
203 203 if options.with_hg:
204 204 options.with_hg = os.path.expanduser(options.with_hg)
205 205 if not (os.path.isfile(options.with_hg) and
206 206 os.access(options.with_hg, os.X_OK)):
207 207 parser.error('--with-hg must specify an executable hg script')
208 208 if not os.path.basename(options.with_hg) == 'hg':
209 209 sys.stderr.write('warning: --with-hg should specify an hg script\n')
210 210 if options.local:
211 211 testdir = os.path.dirname(os.path.realpath(sys.argv[0]))
212 212 hgbin = os.path.join(os.path.dirname(testdir), 'hg')
213 213 if os.name != 'nt' and not os.access(hgbin, os.X_OK):
214 214 parser.error('--local specified, but %r not found or not executable'
215 215 % hgbin)
216 216 options.with_hg = hgbin
217 217
218 218 options.anycoverage = options.cover or options.annotate or options.htmlcov
219 219 if options.anycoverage:
220 220 try:
221 221 import coverage
222 222 covver = version.StrictVersion(coverage.__version__).version
223 223 if covver < (3, 3):
224 224 parser.error('coverage options require coverage 3.3 or later')
225 225 except ImportError:
226 226 parser.error('coverage options now require the coverage package')
227 227
228 228 if options.anycoverage and options.local:
229 229 # this needs some path mangling somewhere, I guess
230 230 parser.error("sorry, coverage options do not work when --local "
231 231 "is specified")
232 232
233 233 global vlog
234 234 if options.verbose:
235 235 if options.jobs > 1 or options.child is not None:
236 236 pid = "[%d]" % os.getpid()
237 237 else:
238 238 pid = None
239 239 def vlog(*msg):
240 240 iolock.acquire()
241 241 if pid:
242 242 print pid,
243 243 for m in msg:
244 244 print m,
245 245 print
246 246 sys.stdout.flush()
247 247 iolock.release()
248 248 else:
249 249 vlog = lambda *msg: None
250 250
251 251 if options.tmpdir:
252 252 options.tmpdir = os.path.expanduser(options.tmpdir)
253 253
254 254 if options.jobs < 1:
255 255 parser.error('--jobs must be positive')
256 256 if options.interactive and options.jobs > 1:
257 257 print '(--interactive overrides --jobs)'
258 258 options.jobs = 1
259 259 if options.interactive and options.debug:
260 260 parser.error("-i/--interactive and -d/--debug are incompatible")
261 261 if options.debug:
262 262 if options.timeout != defaults['timeout']:
263 263 sys.stderr.write(
264 264 'warning: --timeout option ignored with --debug\n')
265 265 options.timeout = 0
266 266 if options.py3k_warnings:
267 267 if sys.version_info[:2] < (2, 6) or sys.version_info[:2] >= (3, 0):
268 268 parser.error('--py3k-warnings can only be used on Python 2.6+')
269 269 if options.blacklist:
270 270 options.blacklist = parselistfiles(options.blacklist, 'blacklist')
271 271 if options.whitelist:
272 272 options.whitelisted = parselistfiles(options.whitelist, 'whitelist',
273 273 warn=options.child is None)
274 274 else:
275 275 options.whitelisted = {}
276 276
277 277 return (options, args)
278 278
279 279 def rename(src, dst):
280 280 """Like os.rename(), trade atomicity and opened files friendliness
281 281 for existing destination support.
282 282 """
283 283 shutil.copy(src, dst)
284 284 os.remove(src)
285 285
286 286 def splitnewlines(text):
287 287 '''like str.splitlines, but only split on newlines.
288 288 keep line endings.'''
289 289 i = 0
290 290 lines = []
291 291 while True:
292 292 n = text.find('\n', i)
293 293 if n == -1:
294 294 last = text[i:]
295 295 if last:
296 296 lines.append(last)
297 297 return lines
298 298 lines.append(text[i:n + 1])
299 299 i = n + 1
300 300
301 301 def parsehghaveoutput(lines):
302 302 '''Parse hghave log lines.
303 303 Return tuple of lists (missing, failed):
304 304 * the missing/unknown features
305 305 * the features for which existence check failed'''
306 306 missing = []
307 307 failed = []
308 308 for line in lines:
309 309 if line.startswith(SKIPPED_PREFIX):
310 310 line = line.splitlines()[0]
311 311 missing.append(line[len(SKIPPED_PREFIX):])
312 312 elif line.startswith(FAILED_PREFIX):
313 313 line = line.splitlines()[0]
314 314 failed.append(line[len(FAILED_PREFIX):])
315 315
316 316 return missing, failed
317 317
318 318 def showdiff(expected, output, ref, err):
319 319 print
320 320 for line in difflib.unified_diff(expected, output, ref, err):
321 321 sys.stdout.write(line)
322 322
323 323 def findprogram(program):
324 324 """Search PATH for a executable program"""
325 325 for p in os.environ.get('PATH', os.defpath).split(os.pathsep):
326 326 name = os.path.join(p, program)
327 327 if os.name == 'nt' or os.access(name, os.X_OK):
328 328 return name
329 329 return None
330 330
331 331 def checktools():
332 332 # Before we go any further, check for pre-requisite tools
333 333 # stuff from coreutils (cat, rm, etc) are not tested
334 334 for p in requiredtools:
335 335 if os.name == 'nt':
336 336 p += '.exe'
337 337 found = findprogram(p)
338 338 if found:
339 339 vlog("# Found prerequisite", p, "at", found)
340 340 else:
341 341 print "WARNING: Did not find prerequisite tool: "+p
342 342
343 343 def terminate(proc):
344 344 """Terminate subprocess (with fallback for Python versions < 2.6)"""
345 345 vlog('# Terminating process %d' % proc.pid)
346 346 try:
347 347 getattr(proc, 'terminate', lambda : os.kill(proc.pid, signal.SIGTERM))()
348 348 except OSError:
349 349 pass
350 350
351 351 def killdaemons():
352 352 return killmod.killdaemons(DAEMON_PIDS, tryhard=False, remove=True,
353 353 logfn=vlog)
354 354
355 355 def cleanup(options):
356 356 if not options.keep_tmpdir:
357 357 vlog("# Cleaning up HGTMP", HGTMP)
358 358 shutil.rmtree(HGTMP, True)
359 359
360 360 def usecorrectpython():
361 361 # some tests run python interpreter. they must use same
362 362 # interpreter we use or bad things will happen.
363 363 exedir, exename = os.path.split(sys.executable)
364 364 if exename in ('python', 'python.exe'):
365 365 path = findprogram(exename)
366 366 if os.path.dirname(path) == exedir:
367 367 return
368 368 else:
369 369 exename = 'python'
370 370 vlog('# Making python executable in test path use correct Python')
371 371 mypython = os.path.join(BINDIR, exename)
372 372 try:
373 373 os.symlink(sys.executable, mypython)
374 374 except AttributeError:
375 375 # windows fallback
376 376 shutil.copyfile(sys.executable, mypython)
377 377 shutil.copymode(sys.executable, mypython)
378 378
379 379 def installhg(options):
380 380 vlog("# Performing temporary installation of HG")
381 381 installerrs = os.path.join("tests", "install.err")
382 382 pure = options.pure and "--pure" or ""
383 383
384 384 # Run installer in hg root
385 385 script = os.path.realpath(sys.argv[0])
386 386 hgroot = os.path.dirname(os.path.dirname(script))
387 387 os.chdir(hgroot)
388 388 nohome = '--home=""'
389 389 if os.name == 'nt':
390 390 # The --home="" trick works only on OS where os.sep == '/'
391 391 # because of a distutils convert_path() fast-path. Avoid it at
392 392 # least on Windows for now, deal with .pydistutils.cfg bugs
393 393 # when they happen.
394 394 nohome = ''
395 395 cmd = ('%s setup.py %s clean --all'
396 396 ' build --build-base="%s"'
397 397 ' install --force --prefix="%s" --install-lib="%s"'
398 398 ' --install-scripts="%s" %s >%s 2>&1'
399 399 % (sys.executable, pure, os.path.join(HGTMP, "build"),
400 400 INST, PYTHONDIR, BINDIR, nohome, installerrs))
401 401 vlog("# Running", cmd)
402 402 if os.system(cmd) == 0:
403 403 if not options.verbose:
404 404 os.remove(installerrs)
405 405 else:
406 406 f = open(installerrs)
407 407 for line in f:
408 408 print line,
409 409 f.close()
410 410 sys.exit(1)
411 411 os.chdir(TESTDIR)
412 412
413 413 usecorrectpython()
414 414
415 415 vlog("# Installing dummy diffstat")
416 416 f = open(os.path.join(BINDIR, 'diffstat'), 'w')
417 417 f.write('#!' + sys.executable + '\n'
418 418 'import sys\n'
419 419 'files = 0\n'
420 420 'for line in sys.stdin:\n'
421 421 ' if line.startswith("diff "):\n'
422 422 ' files += 1\n'
423 423 'sys.stdout.write("files patched: %d\\n" % files)\n')
424 424 f.close()
425 425 os.chmod(os.path.join(BINDIR, 'diffstat'), 0700)
426 426
427 427 if options.py3k_warnings and not options.anycoverage:
428 428 vlog("# Updating hg command to enable Py3k Warnings switch")
429 429 f = open(os.path.join(BINDIR, 'hg'), 'r')
430 430 lines = [line.rstrip() for line in f]
431 431 lines[0] += ' -3'
432 432 f.close()
433 433 f = open(os.path.join(BINDIR, 'hg'), 'w')
434 434 for line in lines:
435 435 f.write(line + '\n')
436 436 f.close()
437 437
438 438 hgbat = os.path.join(BINDIR, 'hg.bat')
439 439 if os.path.isfile(hgbat):
440 440 # hg.bat expects to be put in bin/scripts while run-tests.py
441 441 # installation layout put it in bin/ directly. Fix it
442 442 f = open(hgbat, 'rb')
443 443 data = f.read()
444 444 f.close()
445 445 if '"%~dp0..\python" "%~dp0hg" %*' in data:
446 446 data = data.replace('"%~dp0..\python" "%~dp0hg" %*',
447 447 '"%~dp0python" "%~dp0hg" %*')
448 448 f = open(hgbat, 'wb')
449 449 f.write(data)
450 450 f.close()
451 451 else:
452 452 print 'WARNING: cannot fix hg.bat reference to python.exe'
453 453
454 454 if options.anycoverage:
455 455 custom = os.path.join(TESTDIR, 'sitecustomize.py')
456 456 target = os.path.join(PYTHONDIR, 'sitecustomize.py')
457 457 vlog('# Installing coverage trigger to %s' % target)
458 458 shutil.copyfile(custom, target)
459 459 rc = os.path.join(TESTDIR, '.coveragerc')
460 460 vlog('# Installing coverage rc to %s' % rc)
461 461 os.environ['COVERAGE_PROCESS_START'] = rc
462 462 fn = os.path.join(INST, '..', '.coverage')
463 463 os.environ['COVERAGE_FILE'] = fn
464 464
465 465 def outputcoverage(options):
466 466
467 467 vlog('# Producing coverage report')
468 468 os.chdir(PYTHONDIR)
469 469
470 470 def covrun(*args):
471 471 cmd = 'coverage %s' % ' '.join(args)
472 472 vlog('# Running: %s' % cmd)
473 473 os.system(cmd)
474 474
475 475 if options.child:
476 476 return
477 477
478 478 covrun('-c')
479 479 omit = ','.join(os.path.join(x, '*') for x in [BINDIR, TESTDIR])
480 480 covrun('-i', '-r', '"--omit=%s"' % omit) # report
481 481 if options.htmlcov:
482 482 htmldir = os.path.join(TESTDIR, 'htmlcov')
483 483 covrun('-i', '-b', '"--directory=%s"' % htmldir, '"--omit=%s"' % omit)
484 484 if options.annotate:
485 485 adir = os.path.join(TESTDIR, 'annotated')
486 486 if not os.path.isdir(adir):
487 487 os.mkdir(adir)
488 488 covrun('-i', '-a', '"--directory=%s"' % adir, '"--omit=%s"' % omit)
489 489
490 490 def pytest(test, wd, options, replacements):
491 491 py3kswitch = options.py3k_warnings and ' -3' or ''
492 492 cmd = '%s%s "%s"' % (PYTHON, py3kswitch, test)
493 493 vlog("# Running", cmd)
494 494 return run(cmd, wd, options, replacements)
495 495
496 496 def shtest(test, wd, options, replacements):
497 497 cmd = '%s "%s"' % (options.shell, test)
498 498 vlog("# Running", cmd)
499 499 return run(cmd, wd, options, replacements)
500 500
501 501 needescape = re.compile(r'[\x00-\x08\x0b-\x1f\x7f-\xff]').search
502 502 escapesub = re.compile(r'[\x00-\x08\x0b-\x1f\\\x7f-\xff]').sub
503 503 escapemap = dict((chr(i), r'\x%02x' % i) for i in range(256))
504 504 escapemap.update({'\\': '\\\\', '\r': r'\r'})
505 505 def escapef(m):
506 506 return escapemap[m.group(0)]
507 507 def stringescape(s):
508 508 return escapesub(escapef, s)
509 509
510 510 def rematch(el, l):
511 511 try:
512 512 # ensure that the regex matches to the end of the string
513 513 return re.match(el + r'\Z', l)
514 514 except re.error:
515 515 # el is an invalid regex
516 516 return False
517 517
518 518 def globmatch(el, l):
519 519 # The only supported special characters are * and ? plus / which also
520 520 # matches \ on windows. Escaping of these caracters is supported.
521 521 i, n = 0, len(el)
522 522 res = ''
523 523 while i < n:
524 524 c = el[i]
525 525 i += 1
526 526 if c == '\\' and el[i] in '*?\\/':
527 527 res += el[i - 1:i + 1]
528 528 i += 1
529 529 elif c == '*':
530 530 res += '.*'
531 531 elif c == '?':
532 532 res += '.'
533 533 elif c == '/' and os.name == 'nt':
534 534 res += '[/\\\\]'
535 535 else:
536 536 res += re.escape(c)
537 537 return rematch(res, l)
538 538
539 539 def linematch(el, l):
540 540 if el == l: # perfect match (fast)
541 541 return True
542 542 if (el and
543 543 (el.endswith(" (re)\n") and rematch(el[:-6] + '\n', l) or
544 544 el.endswith(" (glob)\n") and globmatch(el[:-8] + '\n', l) or
545 545 el.endswith(" (esc)\n") and
546 546 (el[:-7].decode('string-escape') + '\n' == l or
547 547 el[:-7].decode('string-escape').replace('\r', '') +
548 548 '\n' == l and os.name == 'nt'))):
549 549 return True
550 550 return False
551 551
552 552 def tsttest(test, wd, options, replacements):
553 553 # We generate a shell script which outputs unique markers to line
554 554 # up script results with our source. These markers include input
555 555 # line number and the last return code
556 556 salt = "SALT" + str(time.time())
557 557 def addsalt(line, inpython):
558 558 if inpython:
559 559 script.append('%s %d 0\n' % (salt, line))
560 560 else:
561 561 script.append('echo %s %s $?\n' % (salt, line))
562 562
563 563 # After we run the shell script, we re-unify the script output
564 564 # with non-active parts of the source, with synchronization by our
565 565 # SALT line number markers. The after table contains the
566 566 # non-active components, ordered by line number
567 567 after = {}
568 568 pos = prepos = -1
569 569
570 570 # Expected shellscript output
571 571 expected = {}
572 572
573 573 # We keep track of whether or not we're in a Python block so we
574 574 # can generate the surrounding doctest magic
575 575 inpython = False
576 576
577 577 # True or False when in a true or false conditional section
578 578 skipping = None
579 579
580 580 def hghave(reqs):
581 581 # TODO: do something smarter when all other uses of hghave is gone
582 582 tdir = TESTDIR.replace('\\', '/')
583 583 proc = Popen4('%s -c "%s/hghave %s"' %
584 584 (options.shell, tdir, ' '.join(reqs)), wd, 0)
585 585 proc.communicate()
586 586 ret = proc.wait()
587 587 if wifexited(ret):
588 588 ret = os.WEXITSTATUS(ret)
589 589 return ret == 0
590 590
591 591 f = open(test)
592 592 t = f.readlines()
593 593 f.close()
594 594
595 595 script = []
596 596 if options.debug:
597 597 script.append('set -x\n')
598 598 if os.getenv('MSYSTEM'):
599 599 script.append('alias pwd="pwd -W"\n')
600 600 for n, l in enumerate(t):
601 601 if not l.endswith('\n'):
602 602 l += '\n'
603 603 if l.startswith('#if'):
604 604 if skipping is not None:
605 605 after.setdefault(pos, []).append(' !!! nested #if\n')
606 606 skipping = not hghave(l.split()[1:])
607 607 after.setdefault(pos, []).append(l)
608 608 elif l.startswith('#else'):
609 609 if skipping is None:
610 610 after.setdefault(pos, []).append(' !!! missing #if\n')
611 611 skipping = not skipping
612 612 after.setdefault(pos, []).append(l)
613 613 elif l.startswith('#endif'):
614 614 if skipping is None:
615 615 after.setdefault(pos, []).append(' !!! missing #if\n')
616 616 skipping = None
617 617 after.setdefault(pos, []).append(l)
618 618 elif skipping:
619 619 after.setdefault(pos, []).append(l)
620 620 elif l.startswith(' >>> '): # python inlines
621 621 after.setdefault(pos, []).append(l)
622 622 prepos = pos
623 623 pos = n
624 624 if not inpython:
625 625 # we've just entered a Python block, add the header
626 626 inpython = True
627 627 addsalt(prepos, False) # make sure we report the exit code
628 628 script.append('%s -m heredoctest <<EOF\n' % PYTHON)
629 629 addsalt(n, True)
630 630 script.append(l[2:])
631 631 elif l.startswith(' ... '): # python inlines
632 632 after.setdefault(prepos, []).append(l)
633 633 script.append(l[2:])
634 634 elif l.startswith(' $ '): # commands
635 635 if inpython:
636 636 script.append("EOF\n")
637 637 inpython = False
638 638 after.setdefault(pos, []).append(l)
639 639 prepos = pos
640 640 pos = n
641 641 addsalt(n, False)
642 642 cmd = l[4:].split()
643 643 if len(cmd) == 2 and cmd[0] == 'cd':
644 644 l = ' $ cd %s || exit 1\n' % cmd[1]
645 645 script.append(l[4:])
646 646 elif l.startswith(' > '): # continuations
647 647 after.setdefault(prepos, []).append(l)
648 648 script.append(l[4:])
649 649 elif l.startswith(' '): # results
650 650 # queue up a list of expected results
651 651 expected.setdefault(pos, []).append(l[2:])
652 652 else:
653 653 if inpython:
654 654 script.append("EOF\n")
655 655 inpython = False
656 656 # non-command/result - queue up for merged output
657 657 after.setdefault(pos, []).append(l)
658 658
659 659 if inpython:
660 660 script.append("EOF\n")
661 661 if skipping is not None:
662 662 after.setdefault(pos, []).append(' !!! missing #endif\n')
663 663 addsalt(n + 1, False)
664 664
665 665 # Write out the script and execute it
666 666 fd, name = tempfile.mkstemp(suffix='hg-tst')
667 667 try:
668 668 for l in script:
669 669 os.write(fd, l)
670 670 os.close(fd)
671 671
672 672 cmd = '%s "%s"' % (options.shell, name)
673 673 vlog("# Running", cmd)
674 674 exitcode, output = run(cmd, wd, options, replacements)
675 675 # do not merge output if skipped, return hghave message instead
676 676 # similarly, with --debug, output is None
677 677 if exitcode == SKIPPED_STATUS or output is None:
678 678 return exitcode, output
679 679 finally:
680 680 os.remove(name)
681 681
682 682 # Merge the script output back into a unified test
683 683
684 684 pos = -1
685 685 postout = []
686 686 ret = 0
687 687 for n, l in enumerate(output):
688 688 lout, lcmd = l, None
689 689 if salt in l:
690 690 lout, lcmd = l.split(salt, 1)
691 691
692 692 if lout:
693 693 if lcmd:
694 694 # output block had no trailing newline, clean up
695 695 lout += ' (no-eol)\n'
696 696
697 697 # find the expected output at the current position
698 698 el = None
699 699 if pos in expected and expected[pos]:
700 700 el = expected[pos].pop(0)
701 701
702 702 if linematch(el, lout):
703 703 postout.append(" " + el)
704 704 else:
705 705 if needescape(lout):
706 706 lout = stringescape(lout.rstrip('\n')) + " (esc)\n"
707 707 postout.append(" " + lout) # let diff deal with it
708 708
709 709 if lcmd:
710 710 # add on last return code
711 711 ret = int(lcmd.split()[1])
712 712 if ret != 0:
713 713 postout.append(" [%s]\n" % ret)
714 714 if pos in after:
715 715 # merge in non-active test bits
716 716 postout += after.pop(pos)
717 717 pos = int(lcmd.split()[0])
718 718
719 719 if pos in after:
720 720 postout += after.pop(pos)
721 721
722 722 return exitcode, postout
723 723
724 724 wifexited = getattr(os, "WIFEXITED", lambda x: False)
725 725 def run(cmd, wd, options, replacements):
726 726 """Run command in a sub-process, capturing the output (stdout and stderr).
727 727 Return a tuple (exitcode, output). output is None in debug mode."""
728 728 # TODO: Use subprocess.Popen if we're running on Python 2.4
729 729 if options.debug:
730 730 proc = subprocess.Popen(cmd, shell=True, cwd=wd)
731 731 ret = proc.wait()
732 732 return (ret, None)
733 733
734 734 proc = Popen4(cmd, wd, options.timeout)
735 735 def cleanup():
736 736 terminate(proc)
737 737 ret = proc.wait()
738 738 if ret == 0:
739 739 ret = signal.SIGTERM << 8
740 740 killdaemons()
741 741 return ret
742 742
743 743 output = ''
744 744 proc.tochild.close()
745 745
746 746 try:
747 747 output = proc.fromchild.read()
748 748 except KeyboardInterrupt:
749 749 vlog('# Handling keyboard interrupt')
750 750 cleanup()
751 751 raise
752 752
753 753 ret = proc.wait()
754 754 if wifexited(ret):
755 755 ret = os.WEXITSTATUS(ret)
756 756
757 757 if proc.timeout:
758 758 ret = 'timeout'
759 759
760 760 if ret:
761 761 killdaemons()
762 762
763 763 for s, r in replacements:
764 764 output = re.sub(s, r, output)
765 765 return ret, splitnewlines(output)
766 766
767 767 def runone(options, test):
768 768 '''tristate output:
769 769 None -> skipped
770 770 True -> passed
771 771 False -> failed'''
772 772
773 773 global results, resultslock, iolock
774 774
775 775 testpath = os.path.join(TESTDIR, test)
776 776
777 777 def result(l, e):
778 778 resultslock.acquire()
779 779 results[l].append(e)
780 780 resultslock.release()
781 781
782 782 def skip(msg):
783 783 if not options.verbose:
784 784 result('s', (test, msg))
785 785 else:
786 786 iolock.acquire()
787 787 print "\nSkipping %s: %s" % (testpath, msg)
788 788 iolock.release()
789 789 return None
790 790
791 791 def fail(msg, ret):
792 792 if not options.nodiff:
793 793 iolock.acquire()
794 794 print "\nERROR: %s %s" % (testpath, msg)
795 795 iolock.release()
796 796 if (not ret and options.interactive
797 797 and os.path.exists(testpath + ".err")):
798 798 iolock.acquire()
799 799 print "Accept this change? [n] ",
800 800 answer = sys.stdin.readline().strip()
801 801 iolock.release()
802 802 if answer.lower() in "y yes".split():
803 803 if test.endswith(".t"):
804 804 rename(testpath + ".err", testpath)
805 805 else:
806 806 rename(testpath + ".err", testpath + ".out")
807 807 result('p', test)
808 808 return
809 809 result('f', (test, msg))
810 810
811 811 def success():
812 812 result('p', test)
813 813
814 814 def ignore(msg):
815 815 result('i', (test, msg))
816 816
817 817 if (os.path.basename(test).startswith("test-") and '~' not in test and
818 818 ('.' not in test or test.endswith('.py') or
819 819 test.endswith('.bat') or test.endswith('.t'))):
820 820 if not os.path.exists(test):
821 821 skip("doesn't exist")
822 822 return None
823 823 else:
824 824 vlog('# Test file', test, 'not supported, ignoring')
825 825 return None # not a supported test, don't record
826 826
827 827 if not (options.whitelisted and test in options.whitelisted):
828 828 if options.blacklist and test in options.blacklist:
829 829 skip("blacklisted")
830 830 return None
831 831
832 832 if options.retest and not os.path.exists(test + ".err"):
833 833 ignore("not retesting")
834 834 return None
835 835
836 836 if options.keywords:
837 837 fp = open(test)
838 838 t = fp.read().lower() + test.lower()
839 839 fp.close()
840 840 for k in options.keywords.lower().split():
841 841 if k in t:
842 842 break
843 843 else:
844 844 ignore("doesn't match keyword")
845 845 return None
846 846
847 847 vlog("# Test", test)
848 848
849 849 # create a fresh hgrc
850 850 hgrc = open(HGRCPATH, 'w+')
851 851 hgrc.write('[ui]\n')
852 852 hgrc.write('slash = True\n')
853 853 hgrc.write('[defaults]\n')
854 854 hgrc.write('backout = -d "0 0"\n')
855 855 hgrc.write('commit = -d "0 0"\n')
856 856 hgrc.write('tag = -d "0 0"\n')
857 857 if options.inotify:
858 858 hgrc.write('[extensions]\n')
859 859 hgrc.write('inotify=\n')
860 860 hgrc.write('[inotify]\n')
861 861 hgrc.write('pidfile=%s\n' % DAEMON_PIDS)
862 862 hgrc.write('appendpid=True\n')
863 863 if options.extra_config_opt:
864 864 for opt in options.extra_config_opt:
865 865 section, key = opt.split('.', 1)
866 866 assert '=' in key, ('extra config opt %s must '
867 867 'have an = for assignment' % opt)
868 868 hgrc.write('[%s]\n%s\n' % (section, key))
869 869 hgrc.close()
870 870
871 871 ref = os.path.join(TESTDIR, test+".out")
872 872 err = os.path.join(TESTDIR, test+".err")
873 873 if os.path.exists(err):
874 874 os.remove(err) # Remove any previous output files
875 875 try:
876 876 tf = open(testpath)
877 877 firstline = tf.readline().rstrip()
878 878 tf.close()
879 879 except IOError:
880 880 firstline = ''
881 881 lctest = test.lower()
882 882
883 883 if lctest.endswith('.py') or firstline == '#!/usr/bin/env python':
884 884 runner = pytest
885 885 elif lctest.endswith('.t'):
886 886 runner = tsttest
887 887 ref = testpath
888 888 else:
889 889 # do not try to run non-executable programs
890 890 if not os.access(testpath, os.X_OK):
891 891 return skip("not executable")
892 892 runner = shtest
893 893
894 894 # Make a tmp subdirectory to work in
895 895 testtmp = os.environ["TESTTMP"] = os.environ["HOME"] = \
896 896 os.path.join(HGTMP, os.path.basename(test))
897 897
898 898 replacements = [
899 899 (r':%s\b' % options.port, ':$HGPORT'),
900 900 (r':%s\b' % (options.port + 1), ':$HGPORT1'),
901 901 (r':%s\b' % (options.port + 2), ':$HGPORT2'),
902 902 ]
903 903 if os.name == 'nt':
904 904 replacements.append((r'\r\n', '\n'))
905 905 replacements.append(
906 906 (''.join(c.isalpha() and '[%s%s]' % (c.lower(), c.upper()) or
907 907 c in '/\\' and r'[/\\]' or
908 908 c.isdigit() and c or
909 909 '\\' + c
910 910 for c in testtmp), '$TESTTMP'))
911 911 else:
912 912 replacements.append((re.escape(testtmp), '$TESTTMP'))
913 913
914 914 os.mkdir(testtmp)
915 915 ret, out = runner(testpath, testtmp, options, replacements)
916 916 vlog("# Ret was:", ret)
917 917
918 918 mark = '.'
919 919
920 920 skipped = (ret == SKIPPED_STATUS)
921 921
922 922 # If we're not in --debug mode and reference output file exists,
923 923 # check test output against it.
924 924 if options.debug:
925 925 refout = None # to match "out is None"
926 926 elif os.path.exists(ref):
927 927 f = open(ref, "r")
928 928 refout = list(splitnewlines(f.read()))
929 929 f.close()
930 930 else:
931 931 refout = []
932 932
933 933 if (ret != 0 or out != refout) and not skipped and not options.debug:
934 934 # Save errors to a file for diagnosis
935 935 f = open(err, "wb")
936 936 for line in out:
937 937 f.write(line)
938 938 f.close()
939 939
940 940 if skipped:
941 941 mark = 's'
942 942 if out is None: # debug mode: nothing to parse
943 943 missing = ['unknown']
944 944 failed = None
945 945 else:
946 946 missing, failed = parsehghaveoutput(out)
947 947 if not missing:
948 948 missing = ['irrelevant']
949 949 if failed:
950 950 fail("hghave failed checking for %s" % failed[-1], ret)
951 951 skipped = False
952 952 else:
953 953 skip(missing[-1])
954 954 elif ret == 'timeout':
955 955 mark = 't'
956 956 fail("timed out", ret)
957 957 elif out != refout:
958 958 mark = '!'
959 959 if not options.nodiff:
960 960 iolock.acquire()
961 961 if options.view:
962 962 os.system("%s %s %s" % (options.view, ref, err))
963 963 else:
964 964 showdiff(refout, out, ref, err)
965 965 iolock.release()
966 966 if ret:
967 967 fail("output changed and returned error code %d" % ret, ret)
968 968 else:
969 969 fail("output changed", ret)
970 970 ret = 1
971 971 elif ret:
972 972 mark = '!'
973 973 fail("returned error code %d" % ret, ret)
974 974 else:
975 975 success()
976 976
977 977 if not options.verbose:
978 978 iolock.acquire()
979 979 sys.stdout.write(mark)
980 980 sys.stdout.flush()
981 981 iolock.release()
982 982
983 983 killdaemons()
984 984
985 985 if not options.keep_tmpdir:
986 986 shutil.rmtree(testtmp, True)
987 987 if skipped:
988 988 return None
989 989 return ret == 0
990 990
991 991 _hgpath = None
992 992
993 993 def _gethgpath():
994 994 """Return the path to the mercurial package that is actually found by
995 995 the current Python interpreter."""
996 996 global _hgpath
997 997 if _hgpath is not None:
998 998 return _hgpath
999 999
1000 1000 cmd = '%s -c "import mercurial; print mercurial.__path__[0]"'
1001 1001 pipe = os.popen(cmd % PYTHON)
1002 1002 try:
1003 1003 _hgpath = pipe.read().strip()
1004 1004 finally:
1005 1005 pipe.close()
1006 1006 return _hgpath
1007 1007
1008 1008 def _checkhglib(verb):
1009 1009 """Ensure that the 'mercurial' package imported by python is
1010 1010 the one we expect it to be. If not, print a warning to stderr."""
1011 1011 expecthg = os.path.join(PYTHONDIR, 'mercurial')
1012 1012 actualhg = _gethgpath()
1013 1013 if os.path.abspath(actualhg) != os.path.abspath(expecthg):
1014 1014 sys.stderr.write('warning: %s with unexpected mercurial lib: %s\n'
1015 1015 ' (expected %s)\n'
1016 1016 % (verb, actualhg, expecthg))
1017 1017
1018 1018 def runchildren(options, tests):
1019 1019 if INST:
1020 1020 installhg(options)
1021 1021 _checkhglib("Testing")
1022 1022
1023 1023 optcopy = dict(options.__dict__)
1024 1024 optcopy['jobs'] = 1
1025 1025
1026 1026 # Because whitelist has to override keyword matches, we have to
1027 1027 # actually load the whitelist in the children as well, so we allow
1028 1028 # the list of whitelist files to pass through and be parsed in the
1029 1029 # children, but not the dict of whitelisted tests resulting from
1030 1030 # the parse, used here to override blacklisted tests.
1031 1031 whitelist = optcopy['whitelisted'] or []
1032 1032 del optcopy['whitelisted']
1033 1033
1034 1034 blacklist = optcopy['blacklist'] or []
1035 1035 del optcopy['blacklist']
1036 1036 blacklisted = []
1037 1037
1038 1038 if optcopy['with_hg'] is None:
1039 1039 optcopy['with_hg'] = os.path.join(BINDIR, "hg")
1040 1040 optcopy.pop('anycoverage', None)
1041 1041
1042 1042 opts = []
1043 1043 for opt, value in optcopy.iteritems():
1044 1044 name = '--' + opt.replace('_', '-')
1045 1045 if value is True:
1046 1046 opts.append(name)
1047 1047 elif isinstance(value, list):
1048 1048 for v in value:
1049 1049 opts.append(name + '=' + str(v))
1050 1050 elif value is not None:
1051 1051 opts.append(name + '=' + str(value))
1052 1052
1053 1053 tests.reverse()
1054 1054 jobs = [[] for j in xrange(options.jobs)]
1055 1055 while tests:
1056 1056 for job in jobs:
1057 1057 if not tests:
1058 1058 break
1059 1059 test = tests.pop()
1060 1060 if test not in whitelist and test in blacklist:
1061 1061 blacklisted.append(test)
1062 1062 else:
1063 1063 job.append(test)
1064 1064 fps = {}
1065 1065
1066 1066 for j, job in enumerate(jobs):
1067 1067 if not job:
1068 1068 continue
1069 1069 rfd, wfd = os.pipe()
1070 1070 childopts = ['--child=%d' % wfd, '--port=%d' % (options.port + j * 3)]
1071 1071 childtmp = os.path.join(HGTMP, 'child%d' % j)
1072 1072 childopts += ['--tmpdir', childtmp]
1073 1073 cmdline = [PYTHON, sys.argv[0]] + opts + childopts + job
1074 1074 vlog(' '.join(cmdline))
1075 1075 fps[os.spawnvp(os.P_NOWAIT, cmdline[0], cmdline)] = os.fdopen(rfd, 'r')
1076 1076 os.close(wfd)
1077 1077 signal.signal(signal.SIGINT, signal.SIG_IGN)
1078 1078 failures = 0
1079 1079 tested, skipped, failed = 0, 0, 0
1080 1080 skips = []
1081 1081 fails = []
1082 1082 while fps:
1083 1083 pid, status = os.wait()
1084 1084 fp = fps.pop(pid)
1085 1085 l = fp.read().splitlines()
1086 1086 try:
1087 1087 test, skip, fail = map(int, l[:3])
1088 1088 except ValueError:
1089 1089 test, skip, fail = 0, 0, 0
1090 1090 split = -fail or len(l)
1091 1091 for s in l[3:split]:
1092 1092 skips.append(s.split(" ", 1))
1093 1093 for s in l[split:]:
1094 1094 fails.append(s.split(" ", 1))
1095 1095 tested += test
1096 1096 skipped += skip
1097 1097 failed += fail
1098 1098 vlog('pid %d exited, status %d' % (pid, status))
1099 1099 failures |= status
1100 1100 print
1101 1101 skipped += len(blacklisted)
1102 1102 if not options.noskips:
1103 1103 for s in skips:
1104 1104 print "Skipped %s: %s" % (s[0], s[1])
1105 1105 for s in blacklisted:
1106 1106 print "Skipped %s: blacklisted" % s
1107 1107 for s in fails:
1108 1108 print "Failed %s: %s" % (s[0], s[1])
1109 1109
1110 1110 _checkhglib("Tested")
1111 1111 print "# Ran %d tests, %d skipped, %d failed." % (
1112 1112 tested, skipped, failed)
1113 1113
1114 1114 if options.anycoverage:
1115 1115 outputcoverage(options)
1116 1116 sys.exit(failures != 0)
1117 1117
1118 1118 results = dict(p=[], f=[], s=[], i=[])
1119 1119 resultslock = threading.Lock()
1120 1120 iolock = threading.Lock()
1121 1121
1122 1122 def runqueue(options, tests, results):
1123 1123 for test in tests:
1124 1124 ret = runone(options, test)
1125 1125 if options.first and ret is not None and not ret:
1126 1126 break
1127 1127
1128 1128 def runtests(options, tests):
1129 1129 global DAEMON_PIDS, HGRCPATH
1130 1130 DAEMON_PIDS = os.environ["DAEMON_PIDS"] = os.path.join(HGTMP, 'daemon.pids')
1131 1131 HGRCPATH = os.environ["HGRCPATH"] = os.path.join(HGTMP, '.hgrc')
1132 1132
1133 1133 try:
1134 1134 if INST:
1135 1135 installhg(options)
1136 1136 _checkhglib("Testing")
1137 1137
1138 1138 if options.restart:
1139 1139 orig = list(tests)
1140 1140 while tests:
1141 1141 if os.path.exists(tests[0] + ".err"):
1142 1142 break
1143 1143 tests.pop(0)
1144 1144 if not tests:
1145 1145 print "running all tests"
1146 1146 tests = orig
1147 1147
1148 1148 runqueue(options, tests, results)
1149 1149
1150 1150 failed = len(results['f'])
1151 1151 tested = len(results['p']) + failed
1152 1152 skipped = len(results['s'])
1153 1153 ignored = len(results['i'])
1154 1154
1155 1155 if options.child:
1156 1156 fp = os.fdopen(options.child, 'w')
1157 1157 fp.write('%d\n%d\n%d\n' % (tested, skipped, failed))
1158 1158 for s in results['s']:
1159 1159 fp.write("%s %s\n" % s)
1160 1160 for s in results['f']:
1161 1161 fp.write("%s %s\n" % s)
1162 1162 fp.close()
1163 1163 else:
1164 1164 print
1165 1165 for s in results['s']:
1166 1166 print "Skipped %s: %s" % s
1167 1167 for s in results['f']:
1168 1168 print "Failed %s: %s" % s
1169 1169 _checkhglib("Tested")
1170 1170 print "# Ran %d tests, %d skipped, %d failed." % (
1171 1171 tested, skipped + ignored, failed)
1172 1172
1173 1173 if options.anycoverage:
1174 1174 outputcoverage(options)
1175 1175 except KeyboardInterrupt:
1176 1176 failed = True
1177 1177 print "\ninterrupted!"
1178 1178
1179 1179 if failed:
1180 1180 sys.exit(1)
1181 1181
1182 1182 def main():
1183 1183 (options, args) = parseargs()
1184 1184 if not options.child:
1185 1185 os.umask(022)
1186 1186
1187 1187 checktools()
1188 1188
1189 1189 if len(args) == 0:
1190 1190 args = os.listdir(".")
1191 1191 args.sort()
1192 1192
1193 1193 tests = args
1194 1194
1195 1195 # Reset some environment variables to well-known values so that
1196 1196 # the tests produce repeatable output.
1197 1197 os.environ['LANG'] = os.environ['LC_ALL'] = os.environ['LANGUAGE'] = 'C'
1198 1198 os.environ['TZ'] = 'GMT'
1199 1199 os.environ["EMAIL"] = "Foo Bar <foo.bar@example.com>"
1200 1200 os.environ['CDPATH'] = ''
1201 1201 os.environ['COLUMNS'] = '80'
1202 1202 os.environ['GREP_OPTIONS'] = ''
1203 1203 os.environ['http_proxy'] = ''
1204 1204 os.environ['no_proxy'] = ''
1205 1205 os.environ['NO_PROXY'] = ''
1206 1206 os.environ['TERM'] = 'xterm'
1207 1207
1208 1208 # unset env related to hooks
1209 1209 for k in os.environ.keys():
1210 1210 if k.startswith('HG_'):
1211 1211 # can't remove on solaris
1212 1212 os.environ[k] = ''
1213 1213 del os.environ[k]
1214 if 'HG' in os.environ:
1215 # can't remove on solaris
1216 os.environ['HG'] = ''
1217 del os.environ['HG']
1214 1218
1215 1219 global TESTDIR, HGTMP, INST, BINDIR, PYTHONDIR, COVERAGE_FILE
1216 1220 TESTDIR = os.environ["TESTDIR"] = os.getcwd()
1217 1221 if options.tmpdir:
1218 1222 options.keep_tmpdir = True
1219 1223 tmpdir = options.tmpdir
1220 1224 if os.path.exists(tmpdir):
1221 1225 # Meaning of tmpdir has changed since 1.3: we used to create
1222 1226 # HGTMP inside tmpdir; now HGTMP is tmpdir. So fail if
1223 1227 # tmpdir already exists.
1224 1228 sys.exit("error: temp dir %r already exists" % tmpdir)
1225 1229
1226 1230 # Automatically removing tmpdir sounds convenient, but could
1227 1231 # really annoy anyone in the habit of using "--tmpdir=/tmp"
1228 1232 # or "--tmpdir=$HOME".
1229 1233 #vlog("# Removing temp dir", tmpdir)
1230 1234 #shutil.rmtree(tmpdir)
1231 1235 os.makedirs(tmpdir)
1232 1236 else:
1233 1237 d = None
1234 1238 if os.name == 'nt':
1235 1239 # without this, we get the default temp dir location, but
1236 1240 # in all lowercase, which causes troubles with paths (issue3490)
1237 1241 d = os.getenv('TMP')
1238 1242 tmpdir = tempfile.mkdtemp('', 'hgtests.', d)
1239 1243 HGTMP = os.environ['HGTMP'] = os.path.realpath(tmpdir)
1240 1244 DAEMON_PIDS = None
1241 1245 HGRCPATH = None
1242 1246
1243 1247 os.environ["HGEDITOR"] = sys.executable + ' -c "import sys; sys.exit(0)"'
1244 1248 os.environ["HGMERGE"] = "internal:merge"
1245 1249 os.environ["HGUSER"] = "test"
1246 1250 os.environ["HGENCODING"] = "ascii"
1247 1251 os.environ["HGENCODINGMODE"] = "strict"
1248 1252 os.environ["HGPORT"] = str(options.port)
1249 1253 os.environ["HGPORT1"] = str(options.port + 1)
1250 1254 os.environ["HGPORT2"] = str(options.port + 2)
1251 1255
1252 1256 if options.with_hg:
1253 1257 INST = None
1254 1258 BINDIR = os.path.dirname(os.path.realpath(options.with_hg))
1255 1259
1256 1260 # This looks redundant with how Python initializes sys.path from
1257 1261 # the location of the script being executed. Needed because the
1258 1262 # "hg" specified by --with-hg is not the only Python script
1259 1263 # executed in the test suite that needs to import 'mercurial'
1260 1264 # ... which means it's not really redundant at all.
1261 1265 PYTHONDIR = BINDIR
1262 1266 else:
1263 1267 INST = os.path.join(HGTMP, "install")
1264 1268 BINDIR = os.environ["BINDIR"] = os.path.join(INST, "bin")
1265 1269 PYTHONDIR = os.path.join(INST, "lib", "python")
1266 1270
1267 1271 os.environ["BINDIR"] = BINDIR
1268 1272 os.environ["PYTHON"] = PYTHON
1269 1273
1270 1274 if not options.child:
1271 1275 path = [BINDIR] + os.environ["PATH"].split(os.pathsep)
1272 1276 os.environ["PATH"] = os.pathsep.join(path)
1273 1277
1274 1278 # Include TESTDIR in PYTHONPATH so that out-of-tree extensions
1275 1279 # can run .../tests/run-tests.py test-foo where test-foo
1276 1280 # adds an extension to HGRC
1277 1281 pypath = [PYTHONDIR, TESTDIR]
1278 1282 # We have to augment PYTHONPATH, rather than simply replacing
1279 1283 # it, in case external libraries are only available via current
1280 1284 # PYTHONPATH. (In particular, the Subversion bindings on OS X
1281 1285 # are in /opt/subversion.)
1282 1286 oldpypath = os.environ.get(IMPL_PATH)
1283 1287 if oldpypath:
1284 1288 pypath.append(oldpypath)
1285 1289 os.environ[IMPL_PATH] = os.pathsep.join(pypath)
1286 1290
1287 1291 COVERAGE_FILE = os.path.join(TESTDIR, ".coverage")
1288 1292
1289 1293 vlog("# Using TESTDIR", TESTDIR)
1290 1294 vlog("# Using HGTMP", HGTMP)
1291 1295 vlog("# Using PATH", os.environ["PATH"])
1292 1296 vlog("# Using", IMPL_PATH, os.environ[IMPL_PATH])
1293 1297
1294 1298 try:
1295 1299 if len(tests) > 1 and options.jobs > 1:
1296 1300 runchildren(options, tests)
1297 1301 else:
1298 1302 runtests(options, tests)
1299 1303 finally:
1300 1304 time.sleep(.1)
1301 1305 cleanup(options)
1302 1306
1303 1307 if __name__ == '__main__':
1304 1308 main()
General Comments 0
You need to be logged in to leave comments. Login now