PageRenderTime 60ms CodeModel.GetById 23ms RepoModel.GetById 0ms app.codeStats 0ms

/tests/run-tests.py

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