test.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616
  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 externaly
  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. try:
  68. set
  69. except NameError:
  70. from sets import Set as set
  71. try:
  72. # Python >=2.7 and >=3.2
  73. from unittest.runner import _TextTestResult
  74. except ImportError:
  75. from unittest import _TextTestResult
  76. __metaclass__ = type
  77. def stderr(text):
  78. sys.stderr.write(text)
  79. sys.stderr.write("\n")
  80. class Options:
  81. """Configurable properties of the test runner."""
  82. # test location
  83. basedir = '' # base directory for tests (defaults to
  84. # basedir of argv[0] + 'src'), must be absolute
  85. follow_symlinks = True # should symlinks to subdirectories be
  86. # followed? (hardcoded, may cause loops)
  87. # which tests to run
  88. unit_tests = False # unit tests (default if both are false)
  89. functional_tests = False # functional tests
  90. # test filtering
  91. level = 1 # run only tests at this or lower level
  92. # (if None, runs all tests)
  93. pathname_regex = '' # regexp for filtering filenames
  94. test_regex = '' # regexp for filtering test cases
  95. # actions to take
  96. list_files = False # --list-files
  97. list_tests = False # --list-tests
  98. list_hooks = False # --list-hooks
  99. run_tests = True # run tests (disabled by --list-foo)
  100. # output verbosity
  101. verbosity = 0 # verbosity level (-v)
  102. quiet = 0 # do not print anything on success (-q)
  103. warn_omitted = False # produce warnings when a test case is
  104. # not included in a test suite (-w)
  105. progress = False # show running progress (-p)
  106. coverage = False # produce coverage reports (--coverage)
  107. coverdir = 'coverage' # where to put them (currently hardcoded)
  108. immediate_errors = False # show tracebacks twice (currently hardcoded)
  109. screen_width = 80 # screen width (autodetected)
  110. def compile_matcher(regex):
  111. """Returns a function that takes one argument and returns True or False.
  112. Regex is a regular expression. Empty regex matches everything. There
  113. is one expression: if the regex starts with "!", the meaning of it is
  114. reversed.
  115. """
  116. if not regex:
  117. return lambda x: True
  118. elif regex == '!':
  119. return lambda x: False
  120. elif regex.startswith('!'):
  121. rx = re.compile(regex[1:])
  122. return lambda x: rx.search(x) is None
  123. else:
  124. rx = re.compile(regex)
  125. return lambda x: rx.search(x) is not None
  126. def walk_with_symlinks(top, func, arg):
  127. """Like os.path.walk, but follows symlinks on POSIX systems.
  128. If the symlinks create a loop, this function will never finish.
  129. """
  130. try:
  131. names = os.listdir(top)
  132. except os.error:
  133. return
  134. func(arg, top, names)
  135. exceptions = ('.', '..')
  136. for name in names:
  137. if name not in exceptions:
  138. name = os.path.join(top, name)
  139. if os.path.isdir(name):
  140. walk_with_symlinks(name, func, arg)
  141. def get_test_files(cfg):
  142. """Returns a list of test module filenames."""
  143. matcher = compile_matcher(cfg.pathname_regex)
  144. results = []
  145. test_names = []
  146. if cfg.unit_tests:
  147. test_names.append('tests')
  148. if cfg.functional_tests:
  149. test_names.append('ftests')
  150. baselen = len(cfg.basedir) + 1
  151. def visit(ignored, dir, files):
  152. if os.path.basename(dir) not in test_names:
  153. for name in test_names:
  154. if name + '.py' in files:
  155. path = os.path.join(dir, name + '.py')
  156. if matcher(path[baselen:]):
  157. results.append(path)
  158. return
  159. if '__init__.py' not in files:
  160. stderr("%s is not a package" % dir)
  161. return
  162. for file in files:
  163. if file.startswith('test') and file.endswith('.py'):
  164. path = os.path.join(dir, file)
  165. if matcher(path[baselen:]):
  166. results.append(path)
  167. if cfg.follow_symlinks:
  168. walker = walk_with_symlinks
  169. else:
  170. walker = os.path.walk
  171. walker(cfg.basedir, visit, None)
  172. results.sort()
  173. return results
  174. def import_module(filename, cfg, tracer=None):
  175. """Imports and returns a module."""
  176. filename = os.path.splitext(filename)[0]
  177. modname = filename[len(cfg.basedir):].replace(os.path.sep, '.')
  178. if modname.startswith('.'):
  179. modname = modname[1:]
  180. if tracer is not None:
  181. mod = tracer.runfunc(__import__, modname)
  182. else:
  183. mod = __import__(modname)
  184. components = modname.split('.')
  185. for comp in components[1:]:
  186. mod = getattr(mod, comp)
  187. return mod
  188. def filter_testsuite(suite, matcher, level=None):
  189. """Returns a flattened list of test cases that match the given matcher."""
  190. if not isinstance(suite, unittest.TestSuite):
  191. raise TypeError('not a TestSuite', suite)
  192. results = []
  193. for test in suite._tests:
  194. if level is not None and getattr(test, 'level', 0) > level:
  195. continue
  196. if isinstance(test, unittest.TestCase):
  197. testname = test.id() # package.module.class.method
  198. if matcher(testname):
  199. results.append(test)
  200. else:
  201. filtered = filter_testsuite(test, matcher, level)
  202. results.extend(filtered)
  203. return results
  204. def get_all_test_cases(module):
  205. """Returns a list of all test case classes defined in a given module."""
  206. results = []
  207. for name in dir(module):
  208. if not name.startswith('Test'):
  209. continue
  210. item = getattr(module, name)
  211. if (isinstance(item, (type, types.ClassType)) and
  212. issubclass(item, unittest.TestCase)):
  213. results.append(item)
  214. return results
  215. def get_test_classes_from_testsuite(suite):
  216. """Returns a set of test case classes used in a test suite."""
  217. if not isinstance(suite, unittest.TestSuite):
  218. raise TypeError('not a TestSuite', suite)
  219. results = set()
  220. for test in suite._tests:
  221. if isinstance(test, unittest.TestCase):
  222. results.add(test.__class__)
  223. else:
  224. classes = get_test_classes_from_testsuite(test)
  225. results.update(classes)
  226. return results
  227. def get_test_cases(test_files, cfg, tracer=None):
  228. """Returns a list of test cases from a given list of test modules."""
  229. matcher = compile_matcher(cfg.test_regex)
  230. results = []
  231. for file in test_files:
  232. module = import_module(file, cfg, tracer=tracer)
  233. if tracer is not None:
  234. test_suite = tracer.runfunc(module.test_suite)
  235. else:
  236. test_suite = module.test_suite()
  237. if test_suite is None:
  238. continue
  239. if cfg.warn_omitted:
  240. all_classes = set(get_all_test_cases(module))
  241. classes_in_suite = get_test_classes_from_testsuite(test_suite)
  242. difference = all_classes - classes_in_suite
  243. for test_class in difference:
  244. # surround the warning with blank lines, otherwise it tends
  245. # to get lost in the noise
  246. stderr("\n%s: WARNING: %s not in test suite\n"
  247. % (file, test_class.__name__))
  248. if (cfg.level is not None and
  249. getattr(test_suite, 'level', 0) > cfg.level):
  250. continue
  251. filtered = filter_testsuite(test_suite, matcher, cfg.level)
  252. results.extend(filtered)
  253. return results
  254. def get_test_hooks(test_files, cfg, tracer=None):
  255. """Returns a list of test hooks from a given list of test modules."""
  256. results = []
  257. dirs = set(map(os.path.dirname, test_files))
  258. for dir in list(dirs):
  259. if os.path.basename(dir) == 'ftests':
  260. dirs.add(os.path.join(os.path.dirname(dir), 'tests'))
  261. dirs = list(dirs)
  262. dirs.sort()
  263. for dir in dirs:
  264. filename = os.path.join(dir, 'checks.py')
  265. if os.path.exists(filename):
  266. module = import_module(filename, cfg, tracer=tracer)
  267. if tracer is not None:
  268. hooks = tracer.runfunc(module.test_hooks)
  269. else:
  270. hooks = module.test_hooks()
  271. results.extend(hooks)
  272. return results
  273. class CustomTestResult(_TextTestResult):
  274. """Customised TestResult.
  275. It can show a progress bar, and displays tracebacks for errors and failures
  276. as soon as they happen, in addition to listing them all at the end.
  277. """
  278. __super = _TextTestResult
  279. __super_init = __super.__init__
  280. __super_startTest = __super.startTest
  281. __super_stopTest = __super.stopTest
  282. __super_printErrors = __super.printErrors
  283. def __init__(self, stream, descriptions, verbosity, count, cfg, hooks):
  284. self.__super_init(stream, descriptions, verbosity)
  285. self.count = count
  286. self.cfg = cfg
  287. self.hooks = hooks
  288. if cfg.progress:
  289. self.dots = False
  290. self._lastWidth = 0
  291. self._maxWidth = cfg.screen_width - len("xxxx/xxxx (xxx.x%): ") - 1
  292. def startTest(self, test):
  293. if self.cfg.progress:
  294. # verbosity == 0: 'xxxx/xxxx (xxx.x%)'
  295. # verbosity == 1: 'xxxx/xxxx (xxx.x%): test name'
  296. # verbosity >= 2: 'xxxx/xxxx (xxx.x%): test name ... ok'
  297. n = self.testsRun + 1
  298. self.stream.write("\r%4d" % n)
  299. if self.count:
  300. self.stream.write("/%d (%5.1f%%)"
  301. % (self.count, n * 100.0 / self.count))
  302. if self.showAll: # self.cfg.verbosity == 1
  303. self.stream.write(": ")
  304. elif self.cfg.verbosity:
  305. name = self.getShortDescription(test)
  306. width = len(name)
  307. if width < self._lastWidth:
  308. name += " " * (self._lastWidth - width)
  309. self.stream.write(": %s" % name)
  310. self._lastWidth = width
  311. self.stream.flush()
  312. self.__super_startTest(test)
  313. for hook in self.hooks:
  314. hook.startTest(test)
  315. def stopTest(self, test):
  316. for hook in self.hooks:
  317. hook.stopTest(test)
  318. self.__super_stopTest(test)
  319. def getShortDescription(self, test):
  320. s = self.getDescription(test)
  321. if len(s) > self._maxWidth:
  322. # s is 'testname (package.module.class)'
  323. # try to shorten it to 'testname (...age.module.class)'
  324. # if it is still too long, shorten it to 'testnam...'
  325. # limit case is 'testname (...)'
  326. pos = s.find(" (")
  327. if pos + len(" (...)") > self._maxWidth:
  328. s = s[:self._maxWidth - 3] + "..."
  329. else:
  330. s = "%s...%s" % (s[:pos + 2], s[pos + 5 - self._maxWidth:])
  331. return s
  332. def printErrors(self):
  333. if self.cfg.progress and not (self.dots or self.showAll):
  334. self.stream.writeln()
  335. self.__super_printErrors()
  336. def formatError(self, err):
  337. return "".join(traceback.format_exception(*err))
  338. def printTraceback(self, kind, test, err):
  339. self.stream.writeln()
  340. self.stream.writeln()
  341. self.stream.writeln("%s: %s" % (kind, test))
  342. self.stream.writeln(self.formatError(err))
  343. self.stream.writeln()
  344. def addFailure(self, test, err):
  345. if self.cfg.immediate_errors:
  346. self.printTraceback("FAIL", test, err)
  347. self.failures.append((test, self.formatError(err)))
  348. def addError(self, test, err):
  349. if self.cfg.immediate_errors:
  350. self.printTraceback("ERROR", test, err)
  351. self.errors.append((test, self.formatError(err)))
  352. class CustomTestRunner(unittest.TextTestRunner):
  353. """Customised TestRunner.
  354. See CustomisedTextResult for a list of extensions.
  355. """
  356. __super = unittest.TextTestRunner
  357. __super_init = __super.__init__
  358. __super_run = __super.run
  359. def __init__(self, cfg, hooks=None):
  360. self.__super_init(verbosity=cfg.verbosity)
  361. self.cfg = cfg
  362. if hooks is not None:
  363. self.hooks = hooks
  364. else:
  365. self.hooks = []
  366. def run(self, test):
  367. """Run the given test case or test suite."""
  368. self.count = test.countTestCases()
  369. result = self._makeResult()
  370. startTime = time.time()
  371. test(result)
  372. stopTime = time.time()
  373. timeTaken = float(stopTime - startTime)
  374. result.printErrors()
  375. run = result.testsRun
  376. if not self.cfg.quiet:
  377. self.stream.writeln(result.separator2)
  378. self.stream.writeln("Ran %d test%s in %.3fs" %
  379. (run, run != 1 and "s" or "", timeTaken))
  380. self.stream.writeln()
  381. if not result.wasSuccessful():
  382. self.stream.write("FAILED (")
  383. failed, errored = list(map(len, (result.failures, result.errors)))
  384. if failed:
  385. self.stream.write("failures=%d" % failed)
  386. if errored:
  387. if failed: self.stream.write(", ")
  388. self.stream.write("errors=%d" % errored)
  389. self.stream.writeln(")")
  390. elif not self.cfg.quiet:
  391. self.stream.writeln("OK")
  392. return result
  393. def _makeResult(self):
  394. return CustomTestResult(self.stream, self.descriptions, self.verbosity,
  395. cfg=self.cfg, count=self.count,
  396. hooks=self.hooks)
  397. def main(argv):
  398. """Main program."""
  399. # Environment
  400. if sys.version_info < (2, 3):
  401. stderr('%s: need Python 2.3 or later' % argv[0])
  402. stderr('your python is %s' % sys.version)
  403. return 1
  404. # Defaults
  405. cfg = Options()
  406. cfg.basedir = os.path.join(os.path.dirname(argv[0]), 'src')
  407. cfg.basedir = os.path.abspath(cfg.basedir)
  408. # Figure out terminal size
  409. try:
  410. import curses
  411. except ImportError:
  412. pass
  413. else:
  414. try:
  415. curses.setupterm()
  416. cols = curses.tigetnum('cols')
  417. if cols > 0:
  418. cfg.screen_width = cols
  419. except curses.error:
  420. pass
  421. # Option processing
  422. opts, args = getopt.gnu_getopt(argv[1:], 'hvpqufw',
  423. ['list-files', 'list-tests', 'list-hooks',
  424. 'level=', 'all-levels', 'coverage'])
  425. for k, v in opts:
  426. if k == '-h':
  427. print(__doc__)
  428. return 0
  429. elif k == '-v':
  430. cfg.verbosity += 1
  431. cfg.quiet = False
  432. elif k == '-p':
  433. cfg.progress = True
  434. cfg.quiet = False
  435. elif k == '-q':
  436. cfg.verbosity = 0
  437. cfg.progress = False
  438. cfg.quiet = True
  439. elif k == '-u':
  440. cfg.unit_tests = True
  441. elif k == '-f':
  442. cfg.functional_tests = True
  443. elif k == '-w':
  444. cfg.warn_omitted = True
  445. elif k == '--list-files':
  446. cfg.list_files = True
  447. cfg.run_tests = False
  448. elif k == '--list-tests':
  449. cfg.list_tests = True
  450. cfg.run_tests = False
  451. elif k == '--list-hooks':
  452. cfg.list_hooks = True
  453. cfg.run_tests = False
  454. elif k == '--coverage':
  455. cfg.coverage = True
  456. elif k == '--level':
  457. try:
  458. cfg.level = int(v)
  459. except ValueError:
  460. stderr('%s: invalid level: %s' % (argv[0], v))
  461. stderr('run %s -h for help')
  462. return 1
  463. elif k == '--all-levels':
  464. cfg.level = None
  465. else:
  466. stderr('%s: invalid option: %s' % (argv[0], k))
  467. stderr('run %s -h for help')
  468. return 1
  469. if args:
  470. cfg.pathname_regex = args[0]
  471. if len(args) > 1:
  472. cfg.test_regex = args[1]
  473. if len(args) > 2:
  474. stderr('%s: too many arguments: %s' % (argv[0], args[2]))
  475. stderr('run %s -h for help')
  476. return 1
  477. if not cfg.unit_tests and not cfg.functional_tests:
  478. cfg.unit_tests = True
  479. # Set up the python path
  480. sys.path[0] = cfg.basedir
  481. # Set up tracing before we start importing things
  482. tracer = None
  483. if cfg.run_tests and cfg.coverage:
  484. import trace
  485. # trace.py in Python 2.3.1 is buggy:
  486. # 1) Despite sys.prefix being in ignoredirs, a lot of system-wide
  487. # modules are included in the coverage reports
  488. # 2) Some module file names do not have the first two characters,
  489. # and in general the prefix used seems to be arbitrary
  490. # These bugs are fixed in src/trace.py which should be in PYTHONPATH
  491. # before the official one.
  492. ignoremods = ['test']
  493. ignoredirs = [sys.prefix, sys.exec_prefix]
  494. tracer = trace.Trace(count=True, trace=False,
  495. ignoremods=ignoremods, ignoredirs=ignoredirs)
  496. # Finding and importing
  497. test_files = get_test_files(cfg)
  498. if sys.version_info[:2] < (2,5):
  499. # exclude tests that require the 'with' statement
  500. test_files = [
  501. test_file for test_file in test_files
  502. if 'test_incremental_xmlfile.py' not in test_file]
  503. if sys.version_info[:2] < (2,6):
  504. # exclude tests that require recent Python features
  505. test_files = [
  506. test_file for test_file in test_files
  507. if 'test_http_io.py' not in test_file]
  508. if cfg.list_tests or cfg.run_tests:
  509. test_cases = get_test_cases(test_files, cfg, tracer=tracer)
  510. if cfg.list_hooks or cfg.run_tests:
  511. test_hooks = get_test_hooks(test_files, cfg, tracer=tracer)
  512. # Configure the logging module
  513. import logging
  514. logging.basicConfig()
  515. logging.root.setLevel(logging.CRITICAL)
  516. # Running
  517. success = True
  518. if cfg.list_files:
  519. baselen = len(cfg.basedir) + 1
  520. print("\n".join([fn[baselen:] for fn in test_files]))
  521. if cfg.list_tests:
  522. print("\n".join([test.id() for test in test_cases]))
  523. if cfg.list_hooks:
  524. print("\n".join([str(hook) for hook in test_hooks]))
  525. if cfg.run_tests:
  526. runner = CustomTestRunner(cfg, test_hooks)
  527. suite = unittest.TestSuite()
  528. suite.addTests(test_cases)
  529. if tracer is not None:
  530. success = tracer.runfunc(runner.run, suite).wasSuccessful()
  531. results = tracer.results()
  532. results.write_results(show_missing=True, coverdir=cfg.coverdir)
  533. else:
  534. success = runner.run(suite).wasSuccessful()
  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)