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