PageRenderTime 64ms CodeModel.GetById 21ms RepoModel.GetById 1ms 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
  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['TESTDIR'] = os.getcwd()
  1204. if 'PYTHONHASHSEED' not in os.environ:
  1205. # use a random python hash seed all the time
  1206. # we do the randomness ourself to know what seed is used
  1207. os.environ['PYTHONHASHSEED'] = str(random.getrandbits(32))
  1208. if self.options.tmpdir:
  1209. self.options.keep_tmpdir = True
  1210. tmpdir = self.options.tmpdir
  1211. if os.path.exists(tmpdir):
  1212. # Meaning of tmpdir has changed since 1.3: we used to create
  1213. # HGTMP inside tmpdir; now HGTMP is tmpdir. So fail if
  1214. # tmpdir already exists.
  1215. print "error: temp dir %r already exists" % tmpdir
  1216. return 1
  1217. # Automatically removing tmpdir sounds convenient, but could
  1218. # really annoy anyone in the habit of using "--tmpdir=/tmp"
  1219. # or "--tmpdir=$HOME".
  1220. #vlog("# Removing temp dir", tmpdir)
  1221. #shutil.rmtree(tmpdir)
  1222. os.makedirs(tmpdir)
  1223. else:
  1224. d = None
  1225. if os.name == 'nt':
  1226. # without this, we get the default temp dir location, but
  1227. # in all lowercase, which causes troubles with paths (issue3490)
  1228. d = os.getenv('TMP')
  1229. tmpdir = tempfile.mkdtemp('', 'hgtests.', d)
  1230. self._hgtmp = os.environ['HGTMP'] = os.path.realpath(tmpdir)
  1231. if self.options.with_hg:
  1232. self._installdir = None
  1233. self._bindir = os.path.dirname(os.path.realpath(
  1234. self.options.with_hg))
  1235. self._tmpbindir = os.path.join(self._hgtmp, 'install', 'bin')
  1236. os.makedirs(self._tmpbindir)
  1237. # This looks redundant with how Python initializes sys.path from
  1238. # the location of the script being executed. Needed because the
  1239. # "hg" specified by --with-hg is not the only Python script
  1240. # executed in the test suite that needs to import 'mercurial'
  1241. # ... which means it's not really redundant at all.
  1242. self._pythondir = self._bindir
  1243. else:
  1244. self._installdir = os.path.join(self._hgtmp, "install")
  1245. self._bindir = os.environ["BINDIR"] = \
  1246. os.path.join(self._installdir, "bin")
  1247. self._tmpbindir = self._bindir
  1248. self._pythondir = os.path.join(self._installdir, "lib", "python")
  1249. os.environ["BINDIR"] = self._bindir
  1250. os.environ["PYTHON"] = PYTHON
  1251. path = [self._bindir] + os.environ["PATH"].split(os.pathsep)
  1252. if self._tmpbindir != self._bindir:
  1253. path = [self._tmpbindir] + path
  1254. os.environ["PATH"] = os.pathsep.join(path)
  1255. # Include TESTDIR in PYTHONPATH so that out-of-tree extensions
  1256. # can run .../tests/run-tests.py test-foo where test-foo
  1257. # adds an extension to HGRC. Also include run-test.py directory to
  1258. # import modules like heredoctest.
  1259. pypath = [self._pythondir, self._testdir,
  1260. os.path.abspath(os.path.dirname(__file__))]
  1261. # We have to augment PYTHONPATH, rather than simply replacing
  1262. # it, in case external libraries are only available via current
  1263. # PYTHONPATH. (In particular, the Subversion bindings on OS X
  1264. # are in /opt/subversion.)
  1265. oldpypath = os.environ.get(IMPL_PATH)
  1266. if oldpypath:
  1267. pypath.append(oldpypath)
  1268. os.environ[IMPL_PATH] = os.pathsep.join(pypath)
  1269. self._coveragefile = os.path.join(self._testdir, '.coverage')
  1270. vlog("# Using TESTDIR", self._testdir)
  1271. vlog("# Using HGTMP", self._hgtmp)
  1272. vlog("# Using PATH", os.environ["PATH"])
  1273. vlog("# Using", IMPL_PATH, os.environ[IMPL_PATH])
  1274. try:
  1275. return self._runtests(tests) or 0
  1276. finally:
  1277. time.sleep(.1)
  1278. self._cleanup()
  1279. def findtests(self, args):
  1280. """Finds possible test files from arguments.
  1281. If you wish to inject custom tests into the test harness, this would
  1282. be a good function to monkeypatch or override in a derived class.
  1283. """
  1284. if not args:
  1285. if self.options.changed:
  1286. proc = Popen4('hg st --rev "%s" -man0 .' %
  1287. self.options.changed, None, 0)
  1288. stdout, stderr = proc.communicate()
  1289. args = stdout.strip('\0').split('\0')
  1290. else:
  1291. args = os.listdir('.')
  1292. return [t for t in args
  1293. if os.path.basename(t).startswith('test-')
  1294. and (t.endswith('.py') or t.endswith('.t'))]
  1295. def _runtests(self, tests):
  1296. try:
  1297. if self._installdir:
  1298. self._installhg()
  1299. self._checkhglib("Testing")
  1300. else:
  1301. self._usecorrectpython()
  1302. if self.options.restart:
  1303. orig = list(tests)
  1304. while tests:
  1305. if os.path.exists(tests[0] + ".err"):
  1306. break
  1307. tests.pop(0)
  1308. if not tests:
  1309. print "running all tests"
  1310. tests = orig
  1311. tests = [self._gettest(t, i) for i, t in enumerate(tests)]
  1312. failed = False
  1313. warned = False
  1314. suite = TestSuite(self._testdir,
  1315. jobs=self.options.jobs,
  1316. whitelist=self.options.whitelisted,
  1317. blacklist=self.options.blacklist,
  1318. retest=self.options.retest,
  1319. keywords=self.options.keywords,
  1320. loop=self.options.loop,
  1321. tests=tests)
  1322. verbosity = 1
  1323. if self.options.verbose:
  1324. verbosity = 2
  1325. runner = TextTestRunner(self, verbosity=verbosity)
  1326. result = runner.run(suite)
  1327. if result.failures:
  1328. failed = True
  1329. if result.warned:
  1330. warned = True
  1331. if self.options.anycoverage:
  1332. self._outputcoverage()
  1333. except KeyboardInterrupt:
  1334. failed = True
  1335. print "\ninterrupted!"
  1336. if failed:
  1337. return 1
  1338. if warned:
  1339. return 80
  1340. def _gettest(self, test, count):
  1341. """Obtain a Test by looking at its filename.
  1342. Returns a Test instance. The Test may not be runnable if it doesn't
  1343. map to a known type.
  1344. """
  1345. lctest = test.lower()
  1346. testcls = Test
  1347. for ext, cls in self.TESTTYPES:
  1348. if lctest.endswith(ext):
  1349. testcls = cls
  1350. break
  1351. refpath = os.path.join(self._testdir, test)
  1352. tmpdir = os.path.join(self._hgtmp, 'child%d' % count)
  1353. return testcls(refpath, tmpdir,
  1354. keeptmpdir=self.options.keep_tmpdir,
  1355. debug=self.options.debug,
  1356. timeout=self.options.timeout,
  1357. startport=self.options.port + count * 3,
  1358. extraconfigopts=self.options.extra_config_opt,
  1359. py3kwarnings=self.options.py3k_warnings,
  1360. shell=self.options.shell)
  1361. def _cleanup(self):
  1362. """Clean up state from this test invocation."""
  1363. if self.options.keep_tmpdir:
  1364. return
  1365. vlog("# Cleaning up HGTMP", self._hgtmp)
  1366. shutil.rmtree(self._hgtmp, True)
  1367. for f in self._createdfiles:
  1368. try:
  1369. os.remove(f)
  1370. except OSError:
  1371. pass
  1372. def _usecorrectpython(self):
  1373. """Configure the environment to use the appropriate Python in tests."""
  1374. # Tests must use the same interpreter as us or bad things will happen.
  1375. pyexename = sys.platform == 'win32' and 'python.exe' or 'python'
  1376. if getattr(os, 'symlink', None):
  1377. vlog("# Making python executable in test path a symlink to '%s'" %
  1378. sys.executable)
  1379. mypython = os.path.join(self._tmpbindir, pyexename)
  1380. try:
  1381. if os.readlink(mypython) == sys.executable:
  1382. return
  1383. os.unlink(mypython)
  1384. except OSError, err:
  1385. if err.errno != errno.ENOENT:
  1386. raise
  1387. if self._findprogram(pyexename) != sys.executable:
  1388. try:
  1389. os.symlink(sys.executable, mypython)
  1390. self._createdfiles.append(mypython)
  1391. except OSError, err:
  1392. # child processes may race, which is harmless
  1393. if err.errno != errno.EEXIST:
  1394. raise
  1395. else:
  1396. exedir, exename = os.path.split(sys.executable)
  1397. vlog("# Modifying search path to find %s as %s in '%s'" %
  1398. (exename, pyexename, exedir))
  1399. path = os.environ['PATH'].split(os.pathsep)
  1400. while exedir in path:
  1401. path.remove(exedir)
  1402. os.environ['PATH'] = os.pathsep.join([exedir] + path)
  1403. if not self._findprogram(pyexename):
  1404. print "WARNING: Cannot find %s in search path" % pyexename
  1405. def _installhg(self):
  1406. """Install hg into the test environment.
  1407. This will also configure hg with the appropriate testing settings.
  1408. """
  1409. vlog("# Performing temporary installation of HG")
  1410. installerrs = os.path.join("tests", "install.err")
  1411. compiler = ''
  1412. if self.options.compiler:
  1413. compiler = '--compiler ' + self.options.compiler
  1414. pure = self.options.pure and "--pure" or ""
  1415. py3 = ''
  1416. if sys.version_info[0] == 3:
  1417. py3 = '--c2to3'
  1418. # Run installer in hg root
  1419. script = os.path.realpath(sys.argv[0])
  1420. hgroot = os.path.dirname(os.path.dirname(script))
  1421. os.chdir(hgroot)
  1422. nohome = '--home=""'
  1423. if os.name == 'nt':
  1424. # The --home="" trick works only on OS where os.sep == '/'
  1425. # because of a distutils convert_path() fast-path. Avoid it at
  1426. # least on Windows for now, deal with .pydistutils.cfg bugs
  1427. # when they happen.
  1428. nohome = ''
  1429. cmd = ('%(exe)s setup.py %(py3)s %(pure)s clean --all'
  1430. ' build %(compiler)s --build-base="%(base)s"'
  1431. ' install --force --prefix="%(prefix)s"'
  1432. ' --install-lib="%(libdir)s"'
  1433. ' --install-scripts="%(bindir)s" %(nohome)s >%(logfile)s 2>&1'
  1434. % {'exe': sys.executable, 'py3': py3, 'pure': pure,
  1435. 'compiler': compiler,
  1436. 'base': os.path.join(self._hgtmp, "build"),
  1437. 'prefix': self._installdir, 'libdir': self._pythondir,
  1438. 'bindir': self._bindir,
  1439. 'nohome': nohome, 'logfile': installerrs})
  1440. vlog("# Running", cmd)
  1441. if os.system(cmd) == 0:
  1442. if not self.options.verbose:
  1443. os.remove(installerrs)
  1444. else:
  1445. f = open(installerrs)
  1446. for line in f:
  1447. print line,
  1448. f.close()
  1449. sys.exit(1)
  1450. os.chdir(self._testdir)
  1451. self._usecorrectpython()
  1452. if self.options.py3k_warnings and not self.options.anycoverage:
  1453. vlog("# Updating hg command to enable Py3k Warnings switch")
  1454. f = open(os.path.join(self._bindir, 'hg'), 'r')
  1455. lines = [line.rstrip() for line in f]
  1456. lines[0] += ' -3'
  1457. f.close()
  1458. f = open(os.path.join(self._bindir, 'hg'), 'w')
  1459. for line in lines:
  1460. f.write(line + '\n')
  1461. f.close()
  1462. hgbat = os.path.join(self._bindir, 'hg.bat')
  1463. if os.path.isfile(hgbat):
  1464. # hg.bat expects to be put in bin/scripts while run-tests.py
  1465. # installation layout put it in bin/ directly. Fix it
  1466. f = open(hgbat, 'rb')
  1467. data = f.read()
  1468. f.close()
  1469. if '"%~dp0..\python" "%~dp0hg" %*' in data:
  1470. data = data.replace('"%~dp0..\python" "%~dp0hg" %*',
  1471. '"%~dp0python" "%~dp0hg" %*')
  1472. f = open(hgbat, 'wb')
  1473. f.write(data)
  1474. f.close()
  1475. else:
  1476. print 'WARNING: cannot fix hg.bat reference to python.exe'
  1477. if self.options.anycoverage:
  1478. custom = os.path.join(self._testdir, 'sitecustomize.py')
  1479. target = os.path.join(self._pythondir, 'sitecustomize.py')
  1480. vlog('# Installing coverage trigger to %s' % target)
  1481. shutil.copyfile(custom, target)
  1482. rc = os.path.join(self._testdir, '.coveragerc')
  1483. vlog('# Installing coverage rc to %s' % rc)
  1484. os.environ['COVERAGE_PROCESS_START'] = rc
  1485. fn = os.path.join(self._installdir, '..', '.coverage')
  1486. os.environ['COVERAGE_FILE'] = fn
  1487. def _checkhglib(self, verb):
  1488. """Ensure that the 'mercurial' package imported by python is
  1489. the one we expect it to be. If not, print a warning to stderr."""
  1490. if ((self._bindir == self._pythondir) and
  1491. (self._bindir != self._tmpbindir)):
  1492. # The pythondir has been infered from --with-hg flag.
  1493. # We cannot expect anything sensible here
  1494. return
  1495. expecthg = os.path.join(self._pythondir, 'mercurial')
  1496. actualhg = self._gethgpath()
  1497. if os.path.abspath(actualhg) != os.path.abspath(expecthg):
  1498. sys.stderr.write('warning: %s with unexpected mercurial lib: %s\n'
  1499. ' (expected %s)\n'
  1500. % (verb, actualhg, expecthg))
  1501. def _gethgpath(self):
  1502. """Return the path to the mercurial package that is actually found by
  1503. the current Python interpreter."""
  1504. if self._hgpath is not None:
  1505. return self._hgpath
  1506. cmd = '%s -c "import mercurial; print (mercurial.__path__[0])"'
  1507. pipe = os.popen(cmd % PYTHON)
  1508. try:
  1509. self._hgpath = pipe.read().strip()
  1510. finally:
  1511. pipe.close()
  1512. return self._hgpath
  1513. def _outputcoverage(self):
  1514. """Produce code coverage output."""
  1515. vlog('# Producing coverage report')
  1516. os.chdir(self._pythondir)
  1517. def covrun(*args):
  1518. cmd = 'coverage %s' % ' '.join(args)
  1519. vlog('# Running: %s' % cmd)
  1520. os.system(cmd)
  1521. covrun('-c')
  1522. omit = ','.join(os.path.join(x, '*') for x in
  1523. [self._bindir, self._testdir])
  1524. covrun('-i', '-r', '"--omit=%s"' % omit) # report
  1525. if self.options.htmlcov:
  1526. htmldir = os.path.join(self._testdir, 'htmlcov')
  1527. covrun('-i', '-b', '"--directory=%s"' % htmldir,
  1528. '"--omit=%s"' % omit)
  1529. if self.options.annotate:
  1530. adir = os.path.join(self._testdir, 'annotated')
  1531. if not os.path.isdir(adir):
  1532. os.mkdir(adir)
  1533. covrun('-i', '-a', '"--directory=%s"' % adir, '"--omit=%s"' % omit)
  1534. def _findprogram(self, program):
  1535. """Search PATH for a executable program"""
  1536. for p in os.environ.get('PATH', os.defpath).split(os.pathsep):
  1537. name = os.path.join(p, program)
  1538. if os.name == 'nt' or os.access(name, os.X_OK):
  1539. return name
  1540. return None
  1541. def _checktools(self):
  1542. """Ensure tools required to run tests are present."""
  1543. for p in self.REQUIREDTOOLS:
  1544. if os.name == 'nt' and not p.endswith('.exe'):
  1545. p += '.exe'
  1546. found = self._findprogram(p)
  1547. if found:
  1548. vlog("# Found prerequisite", p, "at", found)
  1549. else:
  1550. print "WARNING: Did not find prerequisite tool: %s " % p
  1551. if __name__ == '__main__':
  1552. runner = TestRunner()
  1553. sys.exit(runner.run(sys.argv[1:]))