test.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617
  1. #!/usr/bin/env python
  2. #
  3. # SchoolTool - common information systems platform for school administration
  4. # Copyright (c) 2003 Shuttleworth Foundation
  5. #
  6. # This program is free software; you can redistribute it and/or modify
  7. # it under the terms of the GNU General Public License as published by
  8. # the Free Software Foundation; either version 2 of the License, or
  9. # (at your option) any later version.
  10. #
  11. # This program is distributed in the hope that it will be useful,
  12. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. # GNU General Public License for more details.
  15. #
  16. # You should have received a copy of the GNU General Public License
  17. # along with this program; if not, write to the Free Software
  18. # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
  19. #
  20. """
  21. SchoolTool test runner.
  22. Syntax: test.py [options] [pathname-regexp [test-regexp]]
  23. There are two kinds of tests:
  24. - unit tests (or programmer tests) test the internal workings of various
  25. components of the system
  26. - functional tests (acceptance tests, customer tests) test only externally
  27. visible system behaviour
  28. You can choose to run unit tests (this is the default mode), functional tests
  29. (by giving a -f option to test.py) or both (by giving both -u and -f options).
  30. Test cases are located in the directory tree starting at the location of this
  31. script, in subdirectories named 'tests' for unit tests and 'ftests' for
  32. functional tests, in Python modules named 'test*.py'. They are then filtered
  33. according to pathname and test regexes. Alternatively, packages may just have
  34. 'tests.py' and 'ftests.py' instead of subpackages 'tests' and 'ftests'
  35. respectively.
  36. A leading "!" in a regexp is stripped and negates the regexp. Pathname
  37. regexp is applied to the whole path (package/package/module.py). Test regexp
  38. is applied to a full test id (package.package.module.class.test_method).
  39. Options:
  40. -h print this help message
  41. -v verbose (print dots for each test run)
  42. -vv very verbose (print test names)
  43. -q quiet (do not print anything on success)
  44. -w enable warnings about omitted test cases
  45. -p show progress bar (can be combined with -v or -vv)
  46. -u select unit tests (default)
  47. -f select functional tests
  48. --level n select only tests at level n or lower
  49. --all-levels select all tests
  50. --list-files list all selected test files
  51. --list-tests list all selected test cases
  52. --list-hooks list all loaded test hooks
  53. --coverage create code coverage reports
  54. """
  55. #
  56. # This script borrows ideas from Zope 3's test runner heavily. It is smaller
  57. # and cleaner though, at the expense of more limited functionality.
  58. #
  59. import re
  60. import os
  61. import sys
  62. import time
  63. import types
  64. import getopt
  65. import unittest
  66. import traceback
  67. from unittest import TextTestResult
  68. __metaclass__ = type
  69. def stderr(text):
  70. sys.stderr.write(text)
  71. sys.stderr.write("\n")
  72. class Options:
  73. """Configurable properties of the test runner."""
  74. # test location
  75. basedir = '' # base directory for tests (defaults to
  76. # basedir of argv[0] + 'src'), must be absolute
  77. follow_symlinks = True # should symlinks to subdirectories be
  78. # followed? (hardcoded, may cause loops)
  79. # which tests to run
  80. unit_tests = False # unit tests (default if both are false)
  81. functional_tests = False # functional tests
  82. # test filtering
  83. level = 1 # run only tests at this or lower level
  84. # (if None, runs all tests)
  85. pathname_regex = '' # regexp for filtering filenames
  86. test_regex = '' # regexp for filtering test cases
  87. # actions to take
  88. list_files = False # --list-files
  89. list_tests = False # --list-tests
  90. list_hooks = False # --list-hooks
  91. run_tests = True # run tests (disabled by --list-foo)
  92. # output verbosity
  93. verbosity = 0 # verbosity level (-v)
  94. quiet = 0 # do not print anything on success (-q)
  95. warn_omitted = False # produce warnings when a test case is
  96. # not included in a test suite (-w)
  97. progress = False # show running progress (-p)
  98. coverage = False # produce coverage reports (--coverage)
  99. coverdir = 'coverage' # where to put them (currently hardcoded)
  100. immediate_errors = False # show tracebacks twice (currently hardcoded)
  101. screen_width = 80 # screen width (autodetected)
  102. def compile_matcher(regex):
  103. """Returns a function that takes one argument and returns True or False.
  104. Regex is a regular expression. Empty regex matches everything. There
  105. is one expression: if the regex starts with "!", the meaning of it is
  106. reversed.
  107. """
  108. if not regex:
  109. return lambda x: True
  110. elif regex == '!':
  111. return lambda x: False
  112. elif regex.startswith('!'):
  113. rx = re.compile(regex[1:])
  114. return lambda x: rx.search(x) is None
  115. else:
  116. rx = re.compile(regex)
  117. return lambda x: rx.search(x) is not None
  118. def walk_with_symlinks(top, func, arg):
  119. """Like os.path.walk, but follows symlinks on POSIX systems.
  120. If the symlinks create a loop, this function will never finish.
  121. """
  122. try:
  123. names = os.listdir(top)
  124. except os.error:
  125. return
  126. func(arg, top, names)
  127. exceptions = ('.', '..')
  128. for name in names:
  129. if name not in exceptions:
  130. name = os.path.join(top, name)
  131. if os.path.isdir(name):
  132. walk_with_symlinks(name, func, arg)
  133. def get_test_files(cfg):
  134. """Returns a list of test module filenames."""
  135. matcher = compile_matcher(cfg.pathname_regex)
  136. results = []
  137. test_names = []
  138. if cfg.unit_tests:
  139. test_names.append('tests')
  140. if cfg.functional_tests:
  141. test_names.append('ftests')
  142. baselen = len(cfg.basedir) + 1
  143. def visit(ignored, dir, files):
  144. if os.path.basename(dir) not in test_names:
  145. for name in test_names:
  146. if name + '.py' in files:
  147. path = os.path.join(dir, name + '.py')
  148. if matcher(path[baselen:]):
  149. results.append(path)
  150. return
  151. if '__init__.py' not in files:
  152. stderr("%s is not a package" % dir)
  153. return
  154. for file in files:
  155. if file.startswith('test') and file.endswith('.py'):
  156. path = os.path.join(dir, file)
  157. if matcher(path[baselen:]):
  158. results.append(path)
  159. if cfg.follow_symlinks:
  160. walker = walk_with_symlinks
  161. else:
  162. walker = os.path.walk
  163. walker(cfg.basedir, visit, None)
  164. results.sort()
  165. return results
  166. def import_module(filename, cfg, cov=None):
  167. """Imports and returns a module."""
  168. filename = os.path.splitext(filename)[0]
  169. modname = filename[len(cfg.basedir):].replace(os.path.sep, '.')
  170. if modname.startswith('.'):
  171. modname = modname[1:]
  172. if cov is not None:
  173. cov.start()
  174. mod = __import__(modname)
  175. if cov is not None:
  176. cov.stop()
  177. components = modname.split('.')
  178. for comp in components[1:]:
  179. mod = getattr(mod, comp)
  180. return mod
  181. def filter_testsuite(suite, matcher, level=None):
  182. """Returns a flattened list of test cases that match the given matcher."""
  183. if not isinstance(suite, unittest.TestSuite):
  184. raise TypeError('not a TestSuite', suite)
  185. results = []
  186. for test in suite._tests:
  187. if level is not None and getattr(test, 'level', 0) > level:
  188. continue
  189. if isinstance(test, unittest.TestCase):
  190. testname = test.id() # package.module.class.method
  191. if matcher(testname):
  192. results.append(test)
  193. else:
  194. filtered = filter_testsuite(test, matcher, level)
  195. results.extend(filtered)
  196. return results
  197. def get_all_test_cases(module):
  198. """Returns a list of all test case classes defined in a given module."""
  199. results = []
  200. for name in dir(module):
  201. if not name.startswith('Test'):
  202. continue
  203. item = getattr(module, name)
  204. if (isinstance(item, (type, types.ClassType)) and
  205. issubclass(item, unittest.TestCase)):
  206. results.append(item)
  207. return results
  208. def get_test_classes_from_testsuite(suite):
  209. """Returns a set of test case classes used in a test suite."""
  210. if not isinstance(suite, unittest.TestSuite):
  211. raise TypeError('not a TestSuite', suite)
  212. results = set()
  213. for test in suite._tests:
  214. if isinstance(test, unittest.TestCase):
  215. results.add(test.__class__)
  216. else:
  217. classes = get_test_classes_from_testsuite(test)
  218. results.update(classes)
  219. return results
  220. def get_test_cases(test_files, cfg, cov=None):
  221. """Returns a list of test cases from a given list of test modules."""
  222. matcher = compile_matcher(cfg.test_regex)
  223. results = []
  224. for file in test_files:
  225. module = import_module(file, cfg, cov=cov)
  226. if cov is not None:
  227. cov.start()
  228. test_suite = module.test_suite()
  229. if cov is not None:
  230. cov.stop()
  231. if test_suite is None:
  232. continue
  233. if cfg.warn_omitted:
  234. all_classes = set(get_all_test_cases(module))
  235. classes_in_suite = get_test_classes_from_testsuite(test_suite)
  236. difference = all_classes - classes_in_suite
  237. for test_class in difference:
  238. # surround the warning with blank lines, otherwise it tends
  239. # to get lost in the noise
  240. stderr("\n%s: WARNING: %s not in test suite\n"
  241. % (file, test_class.__name__))
  242. if (cfg.level is not None and
  243. getattr(test_suite, 'level', 0) > cfg.level):
  244. continue
  245. filtered = filter_testsuite(test_suite, matcher, cfg.level)
  246. results.extend(filtered)
  247. return results
  248. def get_test_hooks(test_files, cfg, cov=None):
  249. """Returns a list of test hooks from a given list of test modules."""
  250. results = []
  251. dirs = set(map(os.path.dirname, test_files))
  252. for dir in list(dirs):
  253. if os.path.basename(dir) == 'ftests':
  254. dirs.add(os.path.join(os.path.dirname(dir), 'tests'))
  255. dirs = list(dirs)
  256. dirs.sort()
  257. for dir in dirs:
  258. filename = os.path.join(dir, 'checks.py')
  259. if os.path.exists(filename):
  260. module = import_module(filename, cfg, tracer=tracer)
  261. if cov is not None:
  262. cov.start()
  263. hooks = module.test_hooks()
  264. if cov is not None:
  265. cov.stop()
  266. results.extend(hooks)
  267. return results
  268. class CustomTestResult(TextTestResult):
  269. """Customised TestResult.
  270. It can show a progress bar, and displays tracebacks for errors and failures
  271. as soon as they happen, in addition to listing them all at the end.
  272. """
  273. __super = TextTestResult
  274. __super_init = __super.__init__
  275. __super_startTest = __super.startTest
  276. __super_stopTest = __super.stopTest
  277. __super_printErrors = __super.printErrors
  278. def __init__(self, stream, descriptions, verbosity, count, cfg, hooks):
  279. self.__super_init(stream, descriptions, verbosity)
  280. self.count = count
  281. self.cfg = cfg
  282. self.hooks = hooks
  283. if cfg.progress:
  284. self.dots = False
  285. self._lastWidth = 0
  286. self._maxWidth = cfg.screen_width - len("xxxx/xxxx (xxx.x%): ") - 1
  287. def startTest(self, test):
  288. if self.cfg.progress:
  289. # verbosity == 0: 'xxxx/xxxx (xxx.x%)'
  290. # verbosity == 1: 'xxxx/xxxx (xxx.x%): test name'
  291. # verbosity >= 2: 'xxxx/xxxx (xxx.x%): test name ... ok'
  292. n = self.testsRun + 1
  293. self.stream.write("\r%4d" % n)
  294. if self.count:
  295. self.stream.write("/%d (%5.1f%%)"
  296. % (self.count, n * 100.0 / self.count))
  297. if self.showAll: # self.cfg.verbosity == 1
  298. self.stream.write(": ")
  299. elif self.cfg.verbosity:
  300. name = self.getShortDescription(test)
  301. width = len(name)
  302. if width < self._lastWidth:
  303. name += " " * (self._lastWidth - width)
  304. self.stream.write(": %s" % name)
  305. self._lastWidth = width
  306. self.stream.flush()
  307. self.__super_startTest(test)
  308. for hook in self.hooks:
  309. hook.startTest(test)
  310. def stopTest(self, test):
  311. for hook in self.hooks:
  312. hook.stopTest(test)
  313. self.__super_stopTest(test)
  314. def getShortDescription(self, test):
  315. s = self.getDescription(test)
  316. if len(s) > self._maxWidth:
  317. # s is 'testname (package.module.class)'
  318. # try to shorten it to 'testname (...age.module.class)'
  319. # if it is still too long, shorten it to 'testnam...'
  320. # limit case is 'testname (...)'
  321. pos = s.find(" (")
  322. if pos + len(" (...)") > self._maxWidth:
  323. s = s[:self._maxWidth - 3] + "..."
  324. else:
  325. s = "%s...%s" % (s[:pos + 2], s[pos + 5 - self._maxWidth:])
  326. return s
  327. def printErrors(self):
  328. if self.cfg.progress and not (self.dots or self.showAll):
  329. self.stream.writeln()
  330. self.__super_printErrors()
  331. def formatError(self, err):
  332. return "".join(traceback.format_exception(*err))
  333. def printTraceback(self, kind, test, err):
  334. self.stream.writeln()
  335. self.stream.writeln()
  336. self.stream.writeln("%s: %s" % (kind, test))
  337. self.stream.writeln(self.formatError(err))
  338. self.stream.writeln()
  339. def addFailure(self, test, err):
  340. if self.cfg.immediate_errors:
  341. self.printTraceback("FAIL", test, err)
  342. self.failures.append((test, self.formatError(err)))
  343. def addError(self, test, err):
  344. if self.cfg.immediate_errors:
  345. self.printTraceback("ERROR", test, err)
  346. self.errors.append((test, self.formatError(err)))
  347. class CustomTestRunner(unittest.TextTestRunner):
  348. """Customised TestRunner.
  349. See CustomisedTextResult for a list of extensions.
  350. """
  351. __super = unittest.TextTestRunner
  352. __super_init = __super.__init__
  353. __super_run = __super.run
  354. def __init__(self, cfg, hooks=None):
  355. self.__super_init(verbosity=cfg.verbosity)
  356. self.cfg = cfg
  357. if hooks is not None:
  358. self.hooks = hooks
  359. else:
  360. self.hooks = []
  361. def run(self, test):
  362. """Run the given test case or test suite."""
  363. self.count = test.countTestCases()
  364. result = self._makeResult()
  365. startTime = time.time()
  366. test(result)
  367. stopTime = time.time()
  368. timeTaken = float(stopTime - startTime)
  369. result.printErrors()
  370. run = result.testsRun
  371. if not self.cfg.quiet:
  372. self.stream.writeln(result.separator2)
  373. self.stream.writeln("Ran %d test%s in %.3fs" %
  374. (run, run != 1 and "s" or "", timeTaken))
  375. self.stream.writeln()
  376. if not result.wasSuccessful():
  377. self.stream.write("FAILED (")
  378. failed, errored = list(map(len, (result.failures, result.errors)))
  379. if failed:
  380. self.stream.write("failures=%d" % failed)
  381. if errored:
  382. if failed: self.stream.write(", ")
  383. self.stream.write("errors=%d" % errored)
  384. self.stream.writeln(")")
  385. elif not self.cfg.quiet:
  386. self.stream.writeln("OK")
  387. return result
  388. def _makeResult(self):
  389. return CustomTestResult(self.stream, self.descriptions, self.verbosity,
  390. cfg=self.cfg, count=self.count,
  391. hooks=self.hooks)
  392. def main(argv):
  393. """Main program."""
  394. # Environment
  395. if sys.version_info < (2, 7):
  396. stderr('%s: need Python 2.7 or later' % argv[0])
  397. stderr('your python is %s' % sys.version)
  398. return 1
  399. # Defaults
  400. cfg = Options()
  401. cfg.basedir = os.path.join(os.path.dirname(argv[0]), 'src')
  402. cfg.basedir = os.path.abspath(cfg.basedir)
  403. # Figure out terminal size
  404. try:
  405. import curses
  406. except ImportError:
  407. pass
  408. else:
  409. try:
  410. curses.setupterm()
  411. cols = curses.tigetnum('cols')
  412. if cols > 0:
  413. cfg.screen_width = cols
  414. except (curses.error, TypeError):
  415. # tigetnum() is broken in PyPy3 and raises TypeError
  416. pass
  417. # Option processing
  418. opts, args = getopt.gnu_getopt(argv[1:], 'hvpqufw',
  419. ['list-files', 'list-tests', 'list-hooks',
  420. 'level=', 'all-levels', 'coverage'])
  421. for k, v in opts:
  422. if k == '-h':
  423. print(__doc__)
  424. return 0
  425. elif k == '-v':
  426. cfg.verbosity += 1
  427. cfg.quiet = False
  428. elif k == '-p':
  429. cfg.progress = True
  430. cfg.quiet = False
  431. elif k == '-q':
  432. cfg.verbosity = 0
  433. cfg.progress = False
  434. cfg.quiet = True
  435. elif k == '-u':
  436. cfg.unit_tests = True
  437. elif k == '-f':
  438. cfg.functional_tests = True
  439. elif k == '-w':
  440. cfg.warn_omitted = True
  441. elif k == '--list-files':
  442. cfg.list_files = True
  443. cfg.run_tests = False
  444. elif k == '--list-tests':
  445. cfg.list_tests = True
  446. cfg.run_tests = False
  447. elif k == '--list-hooks':
  448. cfg.list_hooks = True
  449. cfg.run_tests = False
  450. elif k == '--coverage':
  451. cfg.coverage = True
  452. elif k == '--level':
  453. try:
  454. cfg.level = int(v)
  455. except ValueError:
  456. stderr('%s: invalid level: %s' % (argv[0], v))
  457. stderr('run %s -h for help')
  458. return 1
  459. elif k == '--all-levels':
  460. cfg.level = None
  461. else:
  462. stderr('%s: invalid option: %s' % (argv[0], k))
  463. stderr('run %s -h for help')
  464. return 1
  465. if args:
  466. cfg.pathname_regex = args[0]
  467. if len(args) > 1:
  468. cfg.test_regex = args[1]
  469. if len(args) > 2:
  470. stderr('%s: too many arguments: %s' % (argv[0], args[2]))
  471. stderr('run %s -h for help')
  472. return 1
  473. if not cfg.unit_tests and not cfg.functional_tests:
  474. cfg.unit_tests = True
  475. # Set up the python path
  476. sys.path[0] = cfg.basedir
  477. # Set up tracing before we start importing things
  478. cov = None
  479. if cfg.run_tests and cfg.coverage:
  480. from coverage import Coverage
  481. cov = Coverage(omit=['test.py'])
  482. # Finding and importing
  483. test_files = get_test_files(cfg)
  484. if cov is not None:
  485. cov.start()
  486. if cfg.list_tests or cfg.run_tests:
  487. test_cases = get_test_cases(test_files, cfg, cov=cov)
  488. if cfg.list_hooks or cfg.run_tests:
  489. test_hooks = get_test_hooks(test_files, cfg, cov=cov)
  490. # Configure the logging module
  491. import logging
  492. logging.basicConfig()
  493. logging.root.setLevel(logging.CRITICAL)
  494. # Running
  495. success = True
  496. if cfg.list_files:
  497. baselen = len(cfg.basedir) + 1
  498. print("\n".join([fn[baselen:] for fn in test_files]))
  499. if cfg.list_tests:
  500. print("\n".join([test.id() for test in test_cases]))
  501. if cfg.list_hooks:
  502. print("\n".join([str(hook) for hook in test_hooks]))
  503. if cfg.run_tests:
  504. runner = CustomTestRunner(cfg, test_hooks)
  505. suite = unittest.TestSuite()
  506. suite.addTests(test_cases)
  507. if cov is not None:
  508. cov.start()
  509. run_result = runner.run(suite)
  510. if cov is not None:
  511. cov.stop()
  512. success = run_result.wasSuccessful()
  513. del run_result
  514. if cov is not None:
  515. traced_file_types = ('.py', '.pyx', '.pxi', '.pxd')
  516. modules = []
  517. def add_file(_, path, files):
  518. if 'tests' in os.path.relpath(path, cfg.basedir).split(os.sep):
  519. return
  520. for filename in files:
  521. if filename.endswith(traced_file_types):
  522. modules.append(os.path.join(path, filename))
  523. if cfg.follow_symlinks:
  524. walker = walk_with_symlinks
  525. else:
  526. walker = os.path.walk
  527. walker(os.path.abspath(cfg.basedir), add_file, None)
  528. try:
  529. cov.xml_report(modules, outfile='coverage.xml')
  530. if cfg.coverdir:
  531. cov.html_report(modules, directory=cfg.coverdir)
  532. finally:
  533. # test runs can take a while, so at least try to print something
  534. cov.report()
  535. # That's all
  536. if success:
  537. return 0
  538. else:
  539. return 1
  540. if __name__ == '__main__':
  541. exitcode = main(sys.argv)
  542. sys.exit(exitcode)