PageRenderTime 67ms CodeModel.GetById 28ms RepoModel.GetById 0ms app.codeStats 0ms

/tests/run-tests.py

https://bitbucket.org/mirror/mercurial/
Python | 1821 lines | 1490 code | 155 blank | 176 comment | 243 complexity | 09812a36208b08ac4f135807d6720224 MD5 | raw file
Possible License(s): GPL-2.0

Large files files are truncated, but you can click here to view the full file

  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. import unittest
  59. processlock = threading.Lock()
  60. # subprocess._cleanup can race with any Popen.wait or Popen.poll on py24
  61. # http://bugs.python.org/issue1731717 for details. We shouldn't be producing
  62. # zombies but it's pretty harmless even if we do.
  63. if sys.version_info < (2, 5):
  64. subprocess._cleanup = lambda: None
  65. closefds = os.name == 'posix'
  66. def Popen4(cmd, wd, timeout, env=None):
  67. processlock.acquire()
  68. p = subprocess.Popen(cmd, shell=True, bufsize=-1, cwd=wd, env=env,
  69. close_fds=closefds,
  70. stdin=subprocess.PIPE, stdout=subprocess.PIPE,
  71. stderr=subprocess.STDOUT)
  72. processlock.release()
  73. p.fromchild = p.stdout
  74. p.tochild = p.stdin
  75. p.childerr = p.stderr
  76. p.timeout = False
  77. if timeout:
  78. def t():
  79. start = time.time()
  80. while time.time() - start < timeout and p.returncode is None:
  81. time.sleep(.1)
  82. p.timeout = True
  83. if p.returncode is None:
  84. terminate(p)
  85. threading.Thread(target=t).start()
  86. return p
  87. PYTHON = sys.executable.replace('\\', '/')
  88. IMPL_PATH = 'PYTHONPATH'
  89. if 'java' in sys.platform:
  90. IMPL_PATH = 'JYTHONPATH'
  91. TESTDIR = HGTMP = INST = BINDIR = TMPBINDIR = PYTHONDIR = None
  92. defaults = {
  93. 'jobs': ('HGTEST_JOBS', 1),
  94. 'timeout': ('HGTEST_TIMEOUT', 180),
  95. 'port': ('HGTEST_PORT', 20059),
  96. 'shell': ('HGTEST_SHELL', 'sh'),
  97. }
  98. def parselistfiles(files, listtype, warn=True):
  99. entries = dict()
  100. for filename in files:
  101. try:
  102. path = os.path.expanduser(os.path.expandvars(filename))
  103. f = open(path, "r")
  104. except IOError, err:
  105. if err.errno != errno.ENOENT:
  106. raise
  107. if warn:
  108. print "warning: no such %s file: %s" % (listtype, filename)
  109. continue
  110. for line in f.readlines():
  111. line = line.split('#', 1)[0].strip()
  112. if line:
  113. entries[line] = filename
  114. f.close()
  115. return entries
  116. def getparser():
  117. """Obtain the OptionParser used by the CLI."""
  118. parser = optparse.OptionParser("%prog [options] [tests]")
  119. # keep these sorted
  120. parser.add_option("--blacklist", action="append",
  121. help="skip tests listed in the specified blacklist file")
  122. parser.add_option("--whitelist", action="append",
  123. help="always run tests listed in the specified whitelist file")
  124. parser.add_option("--changed", type="string",
  125. help="run tests that are changed in parent rev or working directory")
  126. parser.add_option("-C", "--annotate", action="store_true",
  127. help="output files annotated with coverage")
  128. parser.add_option("-c", "--cover", action="store_true",
  129. help="print a test coverage report")
  130. parser.add_option("-d", "--debug", action="store_true",
  131. help="debug mode: write output of test scripts to console"
  132. " rather than capturing and diffing it (disables timeout)")
  133. parser.add_option("-f", "--first", action="store_true",
  134. help="exit on the first test failure")
  135. parser.add_option("-H", "--htmlcov", action="store_true",
  136. help="create an HTML report of the coverage of the files")
  137. parser.add_option("-i", "--interactive", action="store_true",
  138. help="prompt to accept changed output")
  139. parser.add_option("-j", "--jobs", type="int",
  140. help="number of jobs to run in parallel"
  141. " (default: $%s or %d)" % defaults['jobs'])
  142. parser.add_option("--keep-tmpdir", action="store_true",
  143. help="keep temporary directory after running tests")
  144. parser.add_option("-k", "--keywords",
  145. help="run tests matching keywords")
  146. parser.add_option("-l", "--local", action="store_true",
  147. help="shortcut for --with-hg=<testdir>/../hg")
  148. parser.add_option("--loop", action="store_true",
  149. help="loop tests repeatedly")
  150. parser.add_option("-n", "--nodiff", action="store_true",
  151. help="skip showing test changes")
  152. parser.add_option("-p", "--port", type="int",
  153. help="port on which servers should listen"
  154. " (default: $%s or %d)" % defaults['port'])
  155. parser.add_option("--compiler", type="string",
  156. help="compiler to build with")
  157. parser.add_option("--pure", action="store_true",
  158. help="use pure Python code instead of C extensions")
  159. parser.add_option("-R", "--restart", action="store_true",
  160. help="restart at last error")
  161. parser.add_option("-r", "--retest", action="store_true",
  162. help="retest failed tests")
  163. parser.add_option("-S", "--noskips", action="store_true",
  164. help="don't report skip tests verbosely")
  165. parser.add_option("--shell", type="string",
  166. help="shell to use (default: $%s or %s)" % defaults['shell'])
  167. parser.add_option("-t", "--timeout", type="int",
  168. help="kill errant tests after TIMEOUT seconds"
  169. " (default: $%s or %d)" % defaults['timeout'])
  170. parser.add_option("--time", action="store_true",
  171. help="time how long each test takes")
  172. parser.add_option("--tmpdir", type="string",
  173. help="run tests in the given temporary directory"
  174. " (implies --keep-tmpdir)")
  175. parser.add_option("-v", "--verbose", action="store_true",
  176. help="output verbose messages")
  177. parser.add_option("--view", type="string",
  178. help="external diff viewer")
  179. parser.add_option("--with-hg", type="string",
  180. metavar="HG",
  181. help="test using specified hg script rather than a "
  182. "temporary installation")
  183. parser.add_option("-3", "--py3k-warnings", action="store_true",
  184. help="enable Py3k warnings on Python 2.6+")
  185. parser.add_option('--extra-config-opt', action="append",
  186. help='set the given config opt in the test hgrc')
  187. parser.add_option('--random', action="store_true",
  188. help='run tests in random order')
  189. for option, (envvar, default) in defaults.items():
  190. defaults[option] = type(default)(os.environ.get(envvar, default))
  191. parser.set_defaults(**defaults)
  192. return parser
  193. def parseargs(args, parser):
  194. """Parse arguments with our OptionParser and validate results."""
  195. (options, args) = parser.parse_args(args)
  196. # jython is always pure
  197. if 'java' in sys.platform or '__pypy__' in sys.modules:
  198. options.pure = True
  199. if options.with_hg:
  200. options.with_hg = os.path.expanduser(options.with_hg)
  201. if not (os.path.isfile(options.with_hg) and
  202. os.access(options.with_hg, os.X_OK)):
  203. parser.error('--with-hg must specify an executable hg script')
  204. if not os.path.basename(options.with_hg) == 'hg':
  205. sys.stderr.write('warning: --with-hg should specify an hg script\n')
  206. if options.local:
  207. testdir = os.path.dirname(os.path.realpath(sys.argv[0]))
  208. hgbin = os.path.join(os.path.dirname(testdir), 'hg')
  209. if os.name != 'nt' and not os.access(hgbin, os.X_OK):
  210. parser.error('--local specified, but %r not found or not executable'
  211. % hgbin)
  212. options.with_hg = hgbin
  213. options.anycoverage = options.cover or options.annotate or options.htmlcov
  214. if options.anycoverage:
  215. try:
  216. import coverage
  217. covver = version.StrictVersion(coverage.__version__).version
  218. if covver < (3, 3):
  219. parser.error('coverage options require coverage 3.3 or later')
  220. except ImportError:
  221. parser.error('coverage options now require the coverage package')
  222. if options.anycoverage and options.local:
  223. # this needs some path mangling somewhere, I guess
  224. parser.error("sorry, coverage options do not work when --local "
  225. "is specified")
  226. global verbose
  227. if options.verbose:
  228. verbose = ''
  229. if options.tmpdir:
  230. options.tmpdir = os.path.expanduser(options.tmpdir)
  231. if options.jobs < 1:
  232. parser.error('--jobs must be positive')
  233. if options.interactive and options.debug:
  234. parser.error("-i/--interactive and -d/--debug are incompatible")
  235. if options.debug:
  236. if options.timeout != defaults['timeout']:
  237. sys.stderr.write(
  238. 'warning: --timeout option ignored with --debug\n')
  239. options.timeout = 0
  240. if options.py3k_warnings:
  241. if sys.version_info[:2] < (2, 6) or sys.version_info[:2] >= (3, 0):
  242. parser.error('--py3k-warnings can only be used on Python 2.6+')
  243. if options.blacklist:
  244. options.blacklist = parselistfiles(options.blacklist, 'blacklist')
  245. if options.whitelist:
  246. options.whitelisted = parselistfiles(options.whitelist, 'whitelist')
  247. else:
  248. options.whitelisted = {}
  249. return (options, args)
  250. def rename(src, dst):
  251. """Like os.rename(), trade atomicity and opened files friendliness
  252. for existing destination support.
  253. """
  254. shutil.copy(src, dst)
  255. os.remove(src)
  256. def getdiff(expected, output, ref, err):
  257. servefail = False
  258. lines = []
  259. for line in difflib.unified_diff(expected, output, ref, err):
  260. if line.startswith('+++') or line.startswith('---'):
  261. if line.endswith(' \n'):
  262. line = line[:-2] + '\n'
  263. lines.append(line)
  264. if not servefail and line.startswith(
  265. '+ abort: child process failed to start'):
  266. servefail = True
  267. return servefail, lines
  268. verbose = False
  269. def vlog(*msg):
  270. """Log only when in verbose mode."""
  271. if verbose is False:
  272. return
  273. return log(*msg)
  274. def log(*msg):
  275. """Log something to stdout.
  276. Arguments are strings to print.
  277. """
  278. iolock.acquire()
  279. if verbose:
  280. print verbose,
  281. for m in msg:
  282. print m,
  283. print
  284. sys.stdout.flush()
  285. iolock.release()
  286. def terminate(proc):
  287. """Terminate subprocess (with fallback for Python versions < 2.6)"""
  288. vlog('# Terminating process %d' % proc.pid)
  289. try:
  290. getattr(proc, 'terminate', lambda : os.kill(proc.pid, signal.SIGTERM))()
  291. except OSError:
  292. pass
  293. def killdaemons(pidfile):
  294. return killmod.killdaemons(pidfile, tryhard=False, remove=True,
  295. logfn=vlog)
  296. class Test(unittest.TestCase):
  297. """Encapsulates a single, runnable test.
  298. While this class conforms to the unittest.TestCase API, it differs in that
  299. instances need to be instantiated manually. (Typically, unittest.TestCase
  300. classes are instantiated automatically by scanning modules.)
  301. """
  302. # Status code reserved for skipped tests (used by hghave).
  303. SKIPPED_STATUS = 80
  304. def __init__(self, path, tmpdir, keeptmpdir=False,
  305. debug=False,
  306. timeout=defaults['timeout'],
  307. startport=defaults['port'], extraconfigopts=None,
  308. py3kwarnings=False, shell=None):
  309. """Create a test from parameters.
  310. path is the full path to the file defining the test.
  311. tmpdir is the main temporary directory to use for this test.
  312. keeptmpdir determines whether to keep the test's temporary directory
  313. after execution. It defaults to removal (False).
  314. debug mode will make the test execute verbosely, with unfiltered
  315. output.
  316. timeout controls the maximum run time of the test. It is ignored when
  317. debug is True.
  318. startport controls the starting port number to use for this test. Each
  319. test will reserve 3 port numbers for execution. It is the caller's
  320. responsibility to allocate a non-overlapping port range to Test
  321. instances.
  322. extraconfigopts is an iterable of extra hgrc config options. Values
  323. must have the form "key=value" (something understood by hgrc). Values
  324. of the form "foo.key=value" will result in "[foo] key=value".
  325. py3kwarnings enables Py3k warnings.
  326. shell is the shell to execute tests in.
  327. """
  328. self.path = path
  329. self.name = os.path.basename(path)
  330. self._testdir = os.path.dirname(path)
  331. self.errpath = os.path.join(self._testdir, '%s.err' % self.name)
  332. self._threadtmp = tmpdir
  333. self._keeptmpdir = keeptmpdir
  334. self._debug = debug
  335. self._timeout = timeout
  336. self._startport = startport
  337. self._extraconfigopts = extraconfigopts or []
  338. self._py3kwarnings = py3kwarnings
  339. self._shell = shell
  340. self._aborted = False
  341. self._daemonpids = []
  342. self._finished = None
  343. self._ret = None
  344. self._out = None
  345. self._skipped = None
  346. self._testtmp = None
  347. # If we're not in --debug mode and reference output file exists,
  348. # check test output against it.
  349. if debug:
  350. self._refout = None # to match "out is None"
  351. elif os.path.exists(self.refpath):
  352. f = open(self.refpath, 'r')
  353. self._refout = f.read().splitlines(True)
  354. f.close()
  355. else:
  356. self._refout = []
  357. def __str__(self):
  358. return self.name
  359. def shortDescription(self):
  360. return self.name
  361. def setUp(self):
  362. """Tasks to perform before run()."""
  363. self._finished = False
  364. self._ret = None
  365. self._out = None
  366. self._skipped = None
  367. try:
  368. os.mkdir(self._threadtmp)
  369. except OSError, e:
  370. if e.errno != errno.EEXIST:
  371. raise
  372. self._testtmp = os.path.join(self._threadtmp,
  373. os.path.basename(self.path))
  374. os.mkdir(self._testtmp)
  375. # Remove any previous output files.
  376. if os.path.exists(self.errpath):
  377. os.remove(self.errpath)
  378. def run(self, result):
  379. """Run this test and report results against a TestResult instance."""
  380. # This function is extremely similar to unittest.TestCase.run(). Once
  381. # we require Python 2.7 (or at least its version of unittest), this
  382. # function can largely go away.
  383. self._result = result
  384. result.startTest(self)
  385. try:
  386. try:
  387. self.setUp()
  388. except (KeyboardInterrupt, SystemExit):
  389. self._aborted = True
  390. raise
  391. except Exception:
  392. result.addError(self, sys.exc_info())
  393. return
  394. success = False
  395. try:
  396. self.runTest()
  397. except KeyboardInterrupt:
  398. self._aborted = True
  399. raise
  400. except SkipTest, e:
  401. result.addSkip(self, str(e))
  402. except IgnoreTest, e:
  403. result.addIgnore(self, str(e))
  404. except WarnTest, e:
  405. result.addWarn(self, str(e))
  406. except self.failureException, e:
  407. # This differs from unittest in that we don't capture
  408. # the stack trace. This is for historical reasons and
  409. # this decision could be revisted in the future,
  410. # especially for PythonTest instances.
  411. if result.addFailure(self, str(e)):
  412. success = True
  413. except Exception:
  414. result.addError(self, sys.exc_info())
  415. else:
  416. success = True
  417. try:
  418. self.tearDown()
  419. except (KeyboardInterrupt, SystemExit):
  420. self._aborted = True
  421. raise
  422. except Exception:
  423. result.addError(self, sys.exc_info())
  424. success = False
  425. if success:
  426. result.addSuccess(self)
  427. finally:
  428. result.stopTest(self, interrupted=self._aborted)
  429. def runTest(self):
  430. """Run this test instance.
  431. This will return a tuple describing the result of the test.
  432. """
  433. replacements = self._getreplacements()
  434. env = self._getenv()
  435. self._daemonpids.append(env['DAEMON_PIDS'])
  436. self._createhgrc(env['HGRCPATH'])
  437. vlog('# Test', self.name)
  438. ret, out = self._run(replacements, env)
  439. self._finished = True
  440. self._ret = ret
  441. self._out = out
  442. def describe(ret):
  443. if ret < 0:
  444. return 'killed by signal: %d' % -ret
  445. return 'returned error code %d' % ret
  446. self._skipped = False
  447. if ret == self.SKIPPED_STATUS:
  448. if out is None: # Debug mode, nothing to parse.
  449. missing = ['unknown']
  450. failed = None
  451. else:
  452. missing, failed = TTest.parsehghaveoutput(out)
  453. if not missing:
  454. missing = ['irrelevant']
  455. if failed:
  456. self.fail('hg have failed checking for %s' % failed[-1])
  457. else:
  458. self._skipped = True
  459. raise SkipTest(missing[-1])
  460. elif ret == 'timeout':
  461. self.fail('timed out')
  462. elif ret is False:
  463. raise WarnTest('no result code from test')
  464. elif out != self._refout:
  465. # Diff generation may rely on written .err file.
  466. if (ret != 0 or out != self._refout) and not self._skipped \
  467. and not self._debug:
  468. f = open(self.errpath, 'wb')
  469. for line in out:
  470. f.write(line)
  471. f.close()
  472. # The result object handles diff calculation for us.
  473. if self._result.addOutputMismatch(self, ret, out, self._refout):
  474. # change was accepted, skip failing
  475. return
  476. if ret:
  477. msg = 'output changed and ' + describe(ret)
  478. else:
  479. msg = 'output changed'
  480. self.fail(msg)
  481. elif ret:
  482. self.fail(describe(ret))
  483. def tearDown(self):
  484. """Tasks to perform after run()."""
  485. for entry in self._daemonpids:
  486. killdaemons(entry)
  487. self._daemonpids = []
  488. if not self._keeptmpdir:
  489. shutil.rmtree(self._testtmp, True)
  490. shutil.rmtree(self._threadtmp, True)
  491. if (self._ret != 0 or self._out != self._refout) and not self._skipped \
  492. and not self._debug and self._out:
  493. f = open(self.errpath, 'wb')
  494. for line in self._out:
  495. f.write(line)
  496. f.close()
  497. vlog("# Ret was:", self._ret)
  498. def _run(self, replacements, env):
  499. # This should be implemented in child classes to run tests.
  500. raise SkipTest('unknown test type')
  501. def abort(self):
  502. """Terminate execution of this test."""
  503. self._aborted = True
  504. def _getreplacements(self):
  505. """Obtain a mapping of text replacements to apply to test output.
  506. Test output needs to be normalized so it can be compared to expected
  507. output. This function defines how some of that normalization will
  508. occur.
  509. """
  510. r = [
  511. (r':%s\b' % self._startport, ':$HGPORT'),
  512. (r':%s\b' % (self._startport + 1), ':$HGPORT1'),
  513. (r':%s\b' % (self._startport + 2), ':$HGPORT2'),
  514. ]
  515. if os.name == 'nt':
  516. r.append(
  517. (''.join(c.isalpha() and '[%s%s]' % (c.lower(), c.upper()) or
  518. c in '/\\' and r'[/\\]' or c.isdigit() and c or '\\' + c
  519. for c in self._testtmp), '$TESTTMP'))
  520. else:
  521. r.append((re.escape(self._testtmp), '$TESTTMP'))
  522. return r
  523. def _getenv(self):
  524. """Obtain environment variables to use during test execution."""
  525. env = os.environ.copy()
  526. env['TESTTMP'] = self._testtmp
  527. env['HOME'] = self._testtmp
  528. env["HGPORT"] = str(self._startport)
  529. env["HGPORT1"] = str(self._startport + 1)
  530. env["HGPORT2"] = str(self._startport + 2)
  531. env["HGRCPATH"] = os.path.join(self._threadtmp, '.hgrc')
  532. env["DAEMON_PIDS"] = os.path.join(self._threadtmp, 'daemon.pids')
  533. env["HGEDITOR"] = sys.executable + ' -c "import sys; sys.exit(0)"'
  534. env["HGMERGE"] = "internal:merge"
  535. env["HGUSER"] = "test"
  536. env["HGENCODING"] = "ascii"
  537. env["HGENCODINGMODE"] = "strict"
  538. # Reset some environment variables to well-known values so that
  539. # the tests produce repeatable output.
  540. env['LANG'] = env['LC_ALL'] = env['LANGUAGE'] = 'C'
  541. env['TZ'] = 'GMT'
  542. env["EMAIL"] = "Foo Bar <foo.bar@example.com>"
  543. env['COLUMNS'] = '80'
  544. env['TERM'] = 'xterm'
  545. for k in ('HG HGPROF CDPATH GREP_OPTIONS http_proxy no_proxy ' +
  546. 'NO_PROXY').split():
  547. if k in env:
  548. del env[k]
  549. # unset env related to hooks
  550. for k in env.keys():
  551. if k.startswith('HG_'):
  552. del env[k]
  553. return env
  554. def _createhgrc(self, path):
  555. """Create an hgrc file for this test."""
  556. hgrc = open(path, 'w')
  557. hgrc.write('[ui]\n')
  558. hgrc.write('slash = True\n')
  559. hgrc.write('interactive = False\n')
  560. hgrc.write('[defaults]\n')
  561. hgrc.write('backout = -d "0 0"\n')
  562. hgrc.write('commit = -d "0 0"\n')
  563. hgrc.write('shelve = --date "0 0"\n')
  564. hgrc.write('tag = -d "0 0"\n')
  565. for opt in self._extraconfigopts:
  566. section, key = opt.split('.', 1)
  567. assert '=' in key, ('extra config opt %s must '
  568. 'have an = for assignment' % opt)
  569. hgrc.write('[%s]\n%s\n' % (section, key))
  570. hgrc.close()
  571. def fail(self, msg):
  572. # unittest differentiates between errored and failed.
  573. # Failed is denoted by AssertionError (by default at least).
  574. raise AssertionError(msg)
  575. class PythonTest(Test):
  576. """A Python-based test."""
  577. @property
  578. def refpath(self):
  579. return os.path.join(self._testdir, '%s.out' % self.name)
  580. def _run(self, replacements, env):
  581. py3kswitch = self._py3kwarnings and ' -3' or ''
  582. cmd = '%s%s "%s"' % (PYTHON, py3kswitch, self.path)
  583. vlog("# Running", cmd)
  584. if os.name == 'nt':
  585. replacements.append((r'\r\n', '\n'))
  586. result = run(cmd, self._testtmp, replacements, env,
  587. debug=self._debug, timeout=self._timeout)
  588. if self._aborted:
  589. raise KeyboardInterrupt()
  590. return result
  591. class TTest(Test):
  592. """A "t test" is a test backed by a .t file."""
  593. SKIPPED_PREFIX = 'skipped: '
  594. FAILED_PREFIX = 'hghave check failed: '
  595. NEEDESCAPE = re.compile(r'[\x00-\x08\x0b-\x1f\x7f-\xff]').search
  596. ESCAPESUB = re.compile(r'[\x00-\x08\x0b-\x1f\\\x7f-\xff]').sub
  597. ESCAPEMAP = dict((chr(i), r'\x%02x' % i) for i in range(256))
  598. ESCAPEMAP.update({'\\': '\\\\', '\r': r'\r'})
  599. @property
  600. def refpath(self):
  601. return os.path.join(self._testdir, self.name)
  602. def _run(self, replacements, env):
  603. f = open(self.path)
  604. lines = f.readlines()
  605. f.close()
  606. salt, script, after, expected = self._parsetest(lines)
  607. # Write out the generated script.
  608. fname = '%s.sh' % self._testtmp
  609. f = open(fname, 'w')
  610. for l in script:
  611. f.write(l)
  612. f.close()
  613. cmd = '%s "%s"' % (self._shell, fname)
  614. vlog("# Running", cmd)
  615. exitcode, output = run(cmd, self._testtmp, replacements, env,
  616. debug=self._debug, timeout=self._timeout)
  617. if self._aborted:
  618. raise KeyboardInterrupt()
  619. # Do not merge output if skipped. Return hghave message instead.
  620. # Similarly, with --debug, output is None.
  621. if exitcode == self.SKIPPED_STATUS or output is None:
  622. return exitcode, output
  623. return self._processoutput(exitcode, output, salt, after, expected)
  624. def _hghave(self, reqs):
  625. # TODO do something smarter when all other uses of hghave are gone.
  626. tdir = self._testdir.replace('\\', '/')
  627. proc = Popen4('%s -c "%s/hghave %s"' %
  628. (self._shell, tdir, ' '.join(reqs)),
  629. self._testtmp, 0)
  630. stdout, stderr = proc.communicate()
  631. ret = proc.wait()
  632. if wifexited(ret):
  633. ret = os.WEXITSTATUS(ret)
  634. if ret == 2:
  635. print stdout
  636. sys.exit(1)
  637. return ret == 0
  638. def _parsetest(self, lines):
  639. # We generate a shell script which outputs unique markers to line
  640. # up script results with our source. These markers include input
  641. # line number and the last return code.
  642. salt = "SALT" + str(time.time())
  643. def addsalt(line, inpython):
  644. if inpython:
  645. script.append('%s %d 0\n' % (salt, line))
  646. else:
  647. script.append('echo %s %s $?\n' % (salt, line))
  648. script = []
  649. # After we run the shell script, we re-unify the script output
  650. # with non-active parts of the source, with synchronization by our
  651. # SALT line number markers. The after table contains the non-active
  652. # components, ordered by line number.
  653. after = {}
  654. # Expected shell script output.
  655. expected = {}
  656. pos = prepos = -1
  657. # True or False when in a true or false conditional section
  658. skipping = None
  659. # We keep track of whether or not we're in a Python block so we
  660. # can generate the surrounding doctest magic.
  661. inpython = False
  662. if self._debug:
  663. script.append('set -x\n')
  664. if os.getenv('MSYSTEM'):
  665. script.append('alias pwd="pwd -W"\n')
  666. for n, l in enumerate(lines):
  667. if not l.endswith('\n'):
  668. l += '\n'
  669. if l.startswith('#if'):
  670. lsplit = l.split()
  671. if len(lsplit) < 2 or lsplit[0] != '#if':
  672. after.setdefault(pos, []).append(' !!! invalid #if\n')
  673. if skipping is not None:
  674. after.setdefault(pos, []).append(' !!! nested #if\n')
  675. skipping = not self._hghave(lsplit[1:])
  676. after.setdefault(pos, []).append(l)
  677. elif l.startswith('#else'):
  678. if skipping is None:
  679. after.setdefault(pos, []).append(' !!! missing #if\n')
  680. skipping = not skipping
  681. after.setdefault(pos, []).append(l)
  682. elif l.startswith('#endif'):
  683. if skipping is None:
  684. after.setdefault(pos, []).append(' !!! missing #if\n')
  685. skipping = None
  686. after.setdefault(pos, []).append(l)
  687. elif skipping:
  688. after.setdefault(pos, []).append(l)
  689. elif l.startswith(' >>> '): # python inlines
  690. after.setdefault(pos, []).append(l)
  691. prepos = pos
  692. pos = n
  693. if not inpython:
  694. # We've just entered a Python block. Add the header.
  695. inpython = True
  696. addsalt(prepos, False) # Make sure we report the exit code.
  697. script.append('%s -m heredoctest <<EOF\n' % PYTHON)
  698. addsalt(n, True)
  699. script.append(l[2:])
  700. elif l.startswith(' ... '): # python inlines
  701. after.setdefault(prepos, []).append(l)
  702. script.append(l[2:])
  703. elif l.startswith(' $ '): # commands
  704. if inpython:
  705. script.append('EOF\n')
  706. inpython = False
  707. after.setdefault(pos, []).append(l)
  708. prepos = pos
  709. pos = n
  710. addsalt(n, False)
  711. cmd = l[4:].split()
  712. if len(cmd) == 2 and cmd[0] == 'cd':
  713. l = ' $ cd %s || exit 1\n' % cmd[1]
  714. script.append(l[4:])
  715. elif l.startswith(' > '): # continuations
  716. after.setdefault(prepos, []).append(l)
  717. script.append(l[4:])
  718. elif l.startswith(' '): # results
  719. # Queue up a list of expected results.
  720. expected.setdefault(pos, []).append(l[2:])
  721. else:
  722. if inpython:
  723. script.append('EOF\n')
  724. inpython = False
  725. # Non-command/result. Queue up for merged output.
  726. after.setdefault(pos, []).append(l)
  727. if inpython:
  728. script.append('EOF\n')
  729. if skipping is not None:
  730. after.setdefault(pos, []).append(' !!! missing #endif\n')
  731. addsalt(n + 1, False)
  732. return salt, script, after, expected
  733. def _processoutput(self, exitcode, output, salt, after, expected):
  734. # Merge the script output back into a unified test.
  735. warnonly = 1 # 1: not yet; 2: yes; 3: for sure not
  736. if exitcode != 0:
  737. warnonly = 3
  738. pos = -1
  739. postout = []
  740. for l in output:
  741. lout, lcmd = l, None
  742. if salt in l:
  743. lout, lcmd = l.split(salt, 1)
  744. if lout:
  745. if not lout.endswith('\n'):
  746. lout += ' (no-eol)\n'
  747. # Find the expected output at the current position.
  748. el = None
  749. if expected.get(pos, None):
  750. el = expected[pos].pop(0)
  751. r = TTest.linematch(el, lout)
  752. if isinstance(r, str):
  753. if r == '+glob':
  754. lout = el[:-1] + ' (glob)\n'
  755. r = '' # Warn only this line.
  756. elif r == '-glob':
  757. lout = ''.join(el.rsplit(' (glob)', 1))
  758. r = '' # Warn only this line.
  759. else:
  760. log('\ninfo, unknown linematch result: %r\n' % r)
  761. r = False
  762. if r:
  763. postout.append(' ' + el)
  764. else:
  765. if self.NEEDESCAPE(lout):
  766. lout = TTest._stringescape('%s (esc)\n' %
  767. lout.rstrip('\n'))
  768. postout.append(' ' + lout) # Let diff deal with it.
  769. if r != '': # If line failed.
  770. warnonly = 3 # for sure not
  771. elif warnonly == 1: # Is "not yet" and line is warn only.
  772. warnonly = 2 # Yes do warn.
  773. if lcmd:
  774. # Add on last return code.
  775. ret = int(lcmd.split()[1])
  776. if ret != 0:
  777. postout.append(' [%s]\n' % ret)
  778. if pos in after:
  779. # Merge in non-active test bits.
  780. postout += after.pop(pos)
  781. pos = int(lcmd.split()[0])
  782. if pos in after:
  783. postout += after.pop(pos)
  784. if warnonly == 2:
  785. exitcode = False # Set exitcode to warned.
  786. return exitcode, postout
  787. @staticmethod
  788. def rematch(el, l):
  789. try:
  790. # use \Z to ensure that the regex matches to the end of the string
  791. if os.name == 'nt':
  792. return re.match(el + r'\r?\n\Z', l)
  793. return re.match(el + r'\n\Z', l)
  794. except re.error:
  795. # el is an invalid regex
  796. return False
  797. @staticmethod
  798. def globmatch(el, l):
  799. # The only supported special characters are * and ? plus / which also
  800. # matches \ on windows. Escaping of these characters is supported.
  801. if el + '\n' == l:
  802. if os.altsep:
  803. # matching on "/" is not needed for this line
  804. return '-glob'
  805. return True
  806. i, n = 0, len(el)
  807. res = ''
  808. while i < n:
  809. c = el[i]
  810. i += 1
  811. if c == '\\' and el[i] in '*?\\/':
  812. res += el[i - 1:i + 1]
  813. i += 1
  814. elif c == '*':
  815. res += '.*'
  816. elif c == '?':
  817. res += '.'
  818. elif c == '/' and os.altsep:
  819. res += '[/\\\\]'
  820. else:
  821. res += re.escape(c)
  822. return TTest.rematch(res, l)
  823. @staticmethod
  824. def linematch(el, l):
  825. if el == l: # perfect match (fast)
  826. return True
  827. if el:
  828. if el.endswith(" (esc)\n"):
  829. el = el[:-7].decode('string-escape') + '\n'
  830. if el == l or os.name == 'nt' and el[:-1] + '\r\n' == l:
  831. return True
  832. if el.endswith(" (re)\n"):
  833. return TTest.rematch(el[:-6], l)
  834. if el.endswith(" (glob)\n"):
  835. return TTest.globmatch(el[:-8], l)
  836. if os.altsep and l.replace('\\', '/') == el:
  837. return '+glob'
  838. return False
  839. @staticmethod
  840. def parsehghaveoutput(lines):
  841. '''Parse hghave log lines.
  842. Return tuple of lists (missing, failed):
  843. * the missing/unknown features
  844. * the features for which existence check failed'''
  845. missing = []
  846. failed = []
  847. for line in lines:
  848. if line.startswith(TTest.SKIPPED_PREFIX):
  849. line = line.splitlines()[0]
  850. missing.append(line[len(TTest.SKIPPED_PREFIX):])
  851. elif line.startswith(TTest.FAILED_PREFIX):
  852. line = line.splitlines()[0]
  853. failed.append(line[len(TTest.FAILED_PREFIX):])
  854. return missing, failed
  855. @staticmethod
  856. def _escapef(m):
  857. return TTest.ESCAPEMAP[m.group(0)]
  858. @staticmethod
  859. def _stringescape(s):
  860. return TTest.ESCAPESUB(TTest._escapef, s)
  861. wifexited = getattr(os, "WIFEXITED", lambda x: False)
  862. def run(cmd, wd, replacements, env, debug=False, timeout=None):
  863. """Run command in a sub-process, capturing the output (stdout and stderr).
  864. Return a tuple (exitcode, output). output is None in debug mode."""
  865. if debug:
  866. proc = subprocess.Popen(cmd, shell=True, cwd=wd, env=env)
  867. ret = proc.wait()
  868. return (ret, None)
  869. proc = Popen4(cmd, wd, timeout, env)
  870. def cleanup():
  871. terminate(proc)
  872. ret = proc.wait()
  873. if ret == 0:
  874. ret = signal.SIGTERM << 8
  875. killdaemons(env['DAEMON_PIDS'])
  876. return ret
  877. output = ''
  878. proc.tochild.close()
  879. try:
  880. output = proc.fromchild.read()
  881. except KeyboardInterrupt:
  882. vlog('# Handling keyboard interrupt')
  883. cleanup()
  884. raise
  885. ret = proc.wait()
  886. if wifexited(ret):
  887. ret = os.WEXITSTATUS(ret)
  888. if proc.timeout:
  889. ret = 'timeout'
  890. if ret:
  891. killdaemons(env['DAEMON_PIDS'])
  892. for s, r in replacements:
  893. output = re.sub(s, r, output)
  894. return ret, output.splitlines(True)
  895. iolock = threading.Lock()
  896. class SkipTest(Exception):
  897. """Raised to indicate that a test is to be skipped."""
  898. class IgnoreTest(Exception):
  899. """Raised to indicate that a test is to be ignored."""
  900. class WarnTest(Exception):
  901. """Raised to indicate that a test warned."""
  902. class TestResult(unittest._TextTestResult):
  903. """Holds results when executing via unittest."""
  904. # Don't worry too much about accessing the non-public _TextTestResult.
  905. # It is relatively common in Python testing tools.
  906. def __init__(self, options, *args, **kwargs):
  907. super(TestResult, self).__init__(*args, **kwargs)
  908. self._options = options
  909. # unittest.TestResult didn't have skipped until 2.7. We need to
  910. # polyfill it.
  911. self.skipped = []
  912. # We have a custom "ignored" result that isn't present in any Python
  913. # unittest implementation. It is very similar to skipped. It may make
  914. # sense to map it into skip some day.
  915. self.ignored = []
  916. # We have a custom "warned" result that isn't present in any Python
  917. # unittest implementation. It is very similar to failed. It may make
  918. # sense to map it into fail some day.
  919. self.warned = []
  920. self.times = []
  921. self._started = {}
  922. def addFailure(self, test, reason):
  923. self.failures.append((test, reason))
  924. if self._options.first:
  925. self.stop()
  926. else:
  927. if not self._options.nodiff:
  928. self.stream.write('\nERROR: %s output changed\n' % test)
  929. self.stream.write('!')
  930. def addError(self, *args, **kwargs):
  931. super(TestResult, self).addError(*args, **kwargs)
  932. if self._options.first:
  933. self.stop()
  934. # Polyfill.
  935. def addSkip(self, test, reason):
  936. self.skipped.append((test, reason))
  937. if self.showAll:
  938. self.stream.writeln('skipped %s' % reason)
  939. else:
  940. self.stream.write('s')
  941. self.stream.flush()
  942. def addIgnore(self, test, reason):
  943. self.ignored.append((test, reason))
  944. if self.showAll:
  945. self.stream.writeln('ignored %s' % reason)
  946. else:
  947. if reason != 'not retesting':
  948. self.stream.write('i')
  949. self.stream.flush()
  950. def addWarn(self, test, reason):
  951. self.warned.append((test, reason))
  952. if self._options.first:
  953. self.stop()
  954. if self.showAll:
  955. self.stream.writeln('warned %s' % reason)
  956. else:
  957. self.stream.write('~')
  958. self.stream.flush()
  959. def addOutputMismatch(self, test, ret, got, expected):
  960. """Record a mismatch in test output for a particular test."""
  961. accepted = False
  962. iolock.acquire()
  963. if self._options.nodiff:
  964. pass
  965. elif self._options.view:
  966. os.system("%s %s %s" % (self._view, test.refpath, test.errpath))
  967. else:
  968. failed, lines = getdiff(expected, got,
  969. test.refpath, test.errpath)
  970. if failed:
  971. self.addFailure(test, 'diff generation failed')
  972. else:
  973. self.stream.write('\n')
  974. for line in lines:
  975. self.stream.write(line)
  976. self.stream.flush()
  977. # handle interactive prompt without releasing iolock
  978. if self._options.interactive:
  979. self.stream.write('Accept this change? [n] ')
  980. answer = sys.stdin.readline().strip()
  981. if answer.lower() in ('y', 'yes'):
  982. if test.name.endswith('.t'):
  983. rename(test.errpath, test.path)
  984. else:
  985. rename(test.errpath, '%s.out' % test.path)
  986. accepted = True
  987. iolock.release()
  988. return accepted
  989. def startTest(self, test):
  990. super(TestResult, self).startTest(test)
  991. self._started[test.name] = time.time()
  992. def stopTest(self, test, interrupted=False):
  993. super(TestResult, self).stopTest(test)
  994. self.times.append((test.name, time.time() - self._started[test.name]))
  995. del self._started[test.name]
  996. if interrupted:
  997. self.stream.writeln('INTERRUPTED: %s (after %d seconds)' % (
  998. test.name, self.times[-1][1]))
  999. class TestSuite(unittest.TestSuite):
  1000. """Custom unitest TestSuite that knows how to execute Mercurial tests."""
  1001. def __init__(self, testdir, jobs=1, whitelist=None, blacklist=None,
  1002. retest=False, keywords=None, loop=False,
  1003. *args, **kwargs):
  1004. """Create a new instance that can run tests with a configuration.
  1005. testdir specifies the directory where tests are executed from. This
  1006. is typically the ``tests`` directory from Mercurial's source
  1007. repository.
  1008. jobs specifies the number of jobs to run concurrently. Each test
  1009. executes on its own thread. Tests actually spawn new processes, so
  1010. state mutation should not be an issue.
  1011. whitelist and blacklist denote tests that have been whitelisted and
  1012. blacklisted, respectively. These arguments don't belong in TestSuite.
  1013. Instead, whitelist and blacklist should be handled by the thing that
  1014. populates the TestSuite with tests. They are present to preserve
  1015. backwards compatible behavior which reports skipped tests as part
  1016. of the results.
  1017. retest denotes whether to retest failed tests. This arguably belongs
  1018. outside of TestSuite.
  1019. keywords denotes key words that will be used to filter which tests
  1020. to execute. This arguably belongs outside of TestSuite.
  1021. loop denotes whether to loop over tests forever.
  1022. """
  1023. super(TestSuite, self).__init__(*args, **kwargs)
  1024. self._jobs = jobs
  1025. self._whitelist = whitelist
  1026. self._blacklist = blacklist
  1027. self._retest = retest
  1028. self._keywords = keywords
  1029. self._loop = loop
  1030. def run(self, result):
  1031. # We have a number of filters that need to be applied. We do this
  1032. # here instead of inside Test because it makes the running logic for
  1033. # Test simpler.
  1034. tests = []
  1035. for test in self._tests:
  1036. if not os.path.exists(test.path):
  1037. result.addSkip(test, "Doesn't exist")
  1038. continue
  1039. if not (self._whitelist and test.name in self._whitelist):
  1040. if self._blacklist and test.name in self._blacklist:
  1041. result.addSkip(test, 'blacklisted')
  1042. continue
  1043. if self._retest and not os.path.exists(test.errpath):
  1044. result.addIgnore(test, 'not retesting')
  1045. continue
  1046. if self._keywords:
  1047. f = open(test.path)
  1048. t = f.read().lower() + test.name.lower()
  1049. f.close()
  1050. ignored = False
  1051. for k in self._keywords.lower().split():
  1052. if k not in t:
  1053. result.addIgnore(test, "doesn't match keyword")
  1054. ignored = True
  1055. break
  1056. if ignored:
  1057. continue
  1058. tests.append(test)
  1059. runtests = list(tests)
  1060. done = queue.Queue()
  1061. running = 0
  1062. def job(test, result):
  1063. try:
  1064. test(result)
  1065. done.put(None)
  1066. except KeyboardInterrupt:
  1067. pass
  1068. except: # re-raises
  1069. done.put(('!', test, 'run-test raised an error, see traceback'))
  1070. raise
  1071. try:
  1072. while tests or running:
  1073. if not done.empty() or running == self._jobs or not tests:
  1074. try:
  1075. done.get(True, 1)
  1076. if result and result.shouldStop:
  1077. break
  1078. except queue.Empty:
  1079. continue
  1080. running -= 1
  1081. if tests and not running == self._jobs:
  1082. test = tests.pop(0)
  1083. if self._loop:
  1084. tests.append(test)
  1085. t = threading.Thread(target=job, name=test.name,
  1086. args=(test, result))
  1087. t.start()
  1088. running += 1
  1089. except KeyboardInterrupt:
  1090. for test in runtests:
  1091. test.abort()
  1092. return result
  1093. class TextTestRunner(unittest.TextTestRunner):
  1094. """Custom unittest test runner that uses appropriate settings."""
  1095. def __init__(self, runner, *args, **kwargs):
  1096. super(TextTestRunner, self).__init__(*args, **kwargs)
  1097. self._runner = runner
  1098. def run(self, test):
  1099. result = TestResult(self._runner.options, self.stream,
  1100. self.descriptions, self.verbosity)
  1101. test(result)
  1102. failed = len(result.failures)
  1103. warned = len(result.warned)
  1104. skipped = len(result.skipped)
  1105. ignored = len(result.ignored)
  1106. self.stream.writeln('')
  1107. if not self._runner.options.noskips:
  1108. for test, msg in result.skipped:
  1109. self.stream.writeln('Skipped %s: %s' % (test.name, msg))
  1110. for test, msg in result.warned:
  1111. self.stream.writeln('Warned %s: %s' % (test.name, msg))
  1112. for test, msg in result.failures:
  1113. self.stream.writeln('Failed %s: %s' % (test.name, msg))
  1114. for test, msg in result.errors:
  1115. self.stream.writeln('Errored %s: %s' % (test.name, msg))
  1116. self._runner._checkhglib('Tested')
  1117. # When '--retest' is enabled, only failure tests run. At this point
  1118. # "result.testsRun" holds the count of failure test that has run. But
  1119. # as while printing output, we have subtracted the skipped and ignored
  1120. # count from "result.testsRun". Therefore, to make the count remain
  1121. # the same, we need to add skipped and ignored count in here.
  1122. if self._runner.options.retest:
  1123. result.testsRun = result.testsRun + skipped + ignored
  1124. # This differs from unittest's default output in that we don't count
  1125. # skipped and ignored tests as part of the total test count.
  1126. self.stream.writeln('# Ran %d tests, %d skipped, %d warned, %d failed.'
  1127. % (result.testsRun - skipped - ignored,
  1128. skipped + ignored, warned, failed))
  1129. if failed:
  1130. self.stream.writeln('python hash seed: %s' %
  1131. os.environ['PYTHONHASHSEED'])
  1132. if self._runner.options.time:
  1133. self.printtimes(result.times)
  1134. return result
  1135. def printtimes(self, times):
  1136. self.stream.writeln('# Producing time report')
  1137. times.sort(key=lambda t: (t[1], t[0]), reverse=True)
  1138. cols = '%7.3f %s'
  1139. self.stream.writeln('%-7s %s' % ('Time', 'Test'))
  1140. for test, timetaken in times:
  1141. self.stream.writeln(cols % (timetaken, test))
  1142. class TestRunner(object):
  1143. """Holds context for executing tests.
  1144. Tests rely on a lot of state. This object holds it for them.
  1145. """
  1146. # Programs required to run tests.
  1147. REQUIREDTOOLS = [
  1148. os.path.basename(sys.executable),
  1149. 'diff',
  1150. 'grep',
  1151. 'unzip',
  1152. 'gunzip',
  1153. 'bunzip2',
  1154. 'sed',
  1155. ]
  1156. # Maps file extensions to test class.
  1157. TESTTYPES = [
  1158. ('.py', PythonTest),
  1159. ('.t', TTest),
  1160. ]
  1161. def __init__(self):
  1162. self.options = None
  1163. self._testdir = None
  1164. self._hgtmp = None
  1165. self._installdir = None
  1166. self._bindir = None
  1167. self._tmpbinddir = None
  1168. self._pythondir = None
  1169. self._coveragefile = None
  1170. self._createdfiles = []
  1171. self._hgpath = None
  1172. def run(self, args, parser=None):
  1173. """Run the test suite."""
  1174. oldmask = os.umask(022)
  1175. try:
  1176. parser = parser or getparser()
  1177. options, args = parseargs(args, parser)
  1178. self.options = options
  1179. self._checktools()
  1180. tests = self.findtests(args)
  1181. return self._run(tests)
  1182. finally:
  1183. os.umask(oldmask)
  1184. def _run(self, tests):
  1185. if self.options.random:
  1186. random.shuffle(tests)
  1187. else:
  1188. # keywords for slow tests
  1189. slow = 'svn gendoc check-code-hg'.split()
  1190. def sortkey(f):
  1191. # run largest tests first, as they tend to take the longest
  1192. try:
  1193. val = -os.stat(f).st_size
  1194. except OSError, e:
  1195. if e.errno != errno.ENOENT:
  1196. raise
  1197. return -1e9 # file does not exist, tell early
  1198. for kw in slow:
  1199. if kw in f:
  1200. val *= 10
  1201. return val
  1202. tests.sort(key=sortkey)
  1203. self._testdir = os.environ['TESTDā€¦

Large files files are truncated, but you can click here to view the full file