test.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596
  1. #!/usr/bin/env python2.3
  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. __metaclass__ = type
  72. def stderr(text):
  73. sys.stderr.write(text)
  74. sys.stderr.write("\n")
  75. class Options:
  76. """Configurable properties of the test runner."""
  77. # test location
  78. basedir = '' # base directory for tests (defaults to
  79. # basedir of argv[0] + 'src'), must be absolute
  80. follow_symlinks = True # should symlinks to subdirectories be
  81. # followed? (hardcoded, may cause loops)
  82. # which tests to run
  83. unit_tests = False # unit tests (default if both are false)
  84. functional_tests = False # functional tests
  85. # test filtering
  86. level = 1 # run only tests at this or lower level
  87. # (if None, runs all tests)
  88. pathname_regex = '' # regexp for filtering filenames
  89. test_regex = '' # regexp for filtering test cases
  90. # actions to take
  91. list_files = False # --list-files
  92. list_tests = False # --list-tests
  93. list_hooks = False # --list-hooks
  94. run_tests = True # run tests (disabled by --list-foo)
  95. # output verbosity
  96. verbosity = 0 # verbosity level (-v)
  97. quiet = 0 # do not print anything on success (-q)
  98. warn_omitted = False # produce warnings when a test case is
  99. # not included in a test suite (-w)
  100. progress = False # show running progress (-p)
  101. coverage = False # produce coverage reports (--coverage)
  102. coverdir = 'coverage' # where to put them (currently hardcoded)
  103. immediate_errors = False # show tracebacks twice (currently hardcoded)
  104. screen_width = 80 # screen width (autodetected)
  105. def compile_matcher(regex):
  106. """Returns a function that takes one argument and returns True or False.
  107. Regex is a regular expression. Empty regex matches everything. There
  108. is one expression: if the regex starts with "!", the meaning of it is
  109. reversed.
  110. """
  111. if not regex:
  112. return lambda x: True
  113. elif regex == '!':
  114. return lambda x: False
  115. elif regex.startswith('!'):
  116. rx = re.compile(regex[1:])
  117. return lambda x: rx.search(x) is None
  118. else:
  119. rx = re.compile(regex)
  120. return lambda x: rx.search(x) is not None
  121. def walk_with_symlinks(top, func, arg):
  122. """Like os.path.walk, but follows symlinks on POSIX systems.
  123. If the symlinks create a loop, this function will never finish.
  124. """
  125. try:
  126. names = os.listdir(top)
  127. except os.error:
  128. return
  129. func(arg, top, names)
  130. exceptions = ('.', '..')
  131. for name in names:
  132. if name not in exceptions:
  133. name = os.path.join(top, name)
  134. if os.path.isdir(name):
  135. walk_with_symlinks(name, func, arg)
  136. def get_test_files(cfg):
  137. """Returns a list of test module filenames."""
  138. matcher = compile_matcher(cfg.pathname_regex)
  139. results = []
  140. test_names = []
  141. if cfg.unit_tests:
  142. test_names.append('tests')
  143. if cfg.functional_tests:
  144. test_names.append('ftests')
  145. baselen = len(cfg.basedir) + 1
  146. def visit(ignored, dir, files):
  147. if os.path.basename(dir) not in test_names:
  148. for name in test_names:
  149. if name + '.py' in files:
  150. path = os.path.join(dir, name + '.py')
  151. if matcher(path[baselen:]):
  152. results.append(path)
  153. return
  154. if '__init__.py' not in files:
  155. stderr("%s is not a package" % dir)
  156. return
  157. for file in files:
  158. if file.startswith('test') and file.endswith('.py'):
  159. path = os.path.join(dir, file)
  160. if matcher(path[baselen:]):
  161. results.append(path)
  162. if cfg.follow_symlinks:
  163. walker = walk_with_symlinks
  164. else:
  165. walker = os.path.walk
  166. walker(cfg.basedir, visit, None)
  167. results.sort()
  168. return results
  169. def import_module(filename, cfg, tracer=None):
  170. """Imports and returns a module."""
  171. filename = os.path.splitext(filename)[0]
  172. modname = filename[len(cfg.basedir):].replace(os.path.sep, '.')
  173. if modname.startswith('.'):
  174. modname = modname[1:]
  175. if tracer is not None:
  176. mod = tracer.runfunc(__import__, modname)
  177. else:
  178. mod = __import__(modname)
  179. components = modname.split('.')
  180. for comp in components[1:]:
  181. mod = getattr(mod, comp)
  182. return mod
  183. def filter_testsuite(suite, matcher, level=None):
  184. """Returns a flattened list of test cases that match the given matcher."""
  185. if not isinstance(suite, unittest.TestSuite):
  186. raise TypeError('not a TestSuite', suite)
  187. results = []
  188. for test in suite._tests:
  189. if level is not None and getattr(test, 'level', 0) > level:
  190. continue
  191. if isinstance(test, unittest.TestCase):
  192. testname = test.id() # package.module.class.method
  193. if matcher(testname):
  194. results.append(test)
  195. else:
  196. filtered = filter_testsuite(test, matcher, level)
  197. results.extend(filtered)
  198. return results
  199. def get_all_test_cases(module):
  200. """Returns a list of all test case classes defined in a given module."""
  201. results = []
  202. for name in dir(module):
  203. if not name.startswith('Test'):
  204. continue
  205. item = getattr(module, name)
  206. if (isinstance(item, (type, types.ClassType)) and
  207. issubclass(item, unittest.TestCase)):
  208. results.append(item)
  209. return results
  210. def get_test_classes_from_testsuite(suite):
  211. """Returns a set of test case classes used in a test suite."""
  212. if not isinstance(suite, unittest.TestSuite):
  213. raise TypeError('not a TestSuite', suite)
  214. results = set()
  215. for test in suite._tests:
  216. if isinstance(test, unittest.TestCase):
  217. results.add(test.__class__)
  218. else:
  219. classes = get_test_classes_from_testsuite(test)
  220. results.update(classes)
  221. return results
  222. def get_test_cases(test_files, cfg, tracer=None):
  223. """Returns a list of test cases from a given list of test modules."""
  224. matcher = compile_matcher(cfg.test_regex)
  225. results = []
  226. for file in test_files:
  227. module = import_module(file, cfg, tracer=tracer)
  228. if tracer is not None:
  229. test_suite = tracer.runfunc(module.test_suite)
  230. else:
  231. test_suite = module.test_suite()
  232. if test_suite is None:
  233. continue
  234. if cfg.warn_omitted:
  235. all_classes = set(get_all_test_cases(module))
  236. classes_in_suite = get_test_classes_from_testsuite(test_suite)
  237. difference = all_classes - classes_in_suite
  238. for test_class in difference:
  239. # surround the warning with blank lines, otherwise it tends
  240. # to get lost in the noise
  241. stderr("\n%s: WARNING: %s not in test suite\n"
  242. % (file, test_class.__name__))
  243. if (cfg.level is not None and
  244. getattr(test_suite, 'level', 0) > cfg.level):
  245. continue
  246. filtered = filter_testsuite(test_suite, matcher, cfg.level)
  247. results.extend(filtered)
  248. return results
  249. def get_test_hooks(test_files, cfg, tracer=None):
  250. """Returns a list of test hooks from a given list of test modules."""
  251. results = []
  252. dirs = set(map(os.path.dirname, test_files))
  253. for dir in list(dirs):
  254. if os.path.basename(dir) == 'ftests':
  255. dirs.add(os.path.join(os.path.dirname(dir), 'tests'))
  256. dirs = list(dirs)
  257. dirs.sort()
  258. for dir in dirs:
  259. filename = os.path.join(dir, 'checks.py')
  260. if os.path.exists(filename):
  261. module = import_module(filename, cfg, tracer=tracer)
  262. if tracer is not None:
  263. hooks = tracer.runfunc(module.test_hooks)
  264. else:
  265. hooks = module.test_hooks()
  266. results.extend(hooks)
  267. return results
  268. class CustomTestResult(unittest._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 = unittest._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, 3):
  396. stderr('%s: need Python 2.3 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:
  415. pass
  416. # Option processing
  417. opts, args = getopt.gnu_getopt(argv[1:], 'hvpqufw',
  418. ['list-files', 'list-tests', 'list-hooks',
  419. 'level=', 'all-levels', 'coverage'])
  420. for k, v in opts:
  421. if k == '-h':
  422. print(__doc__)
  423. return 0
  424. elif k == '-v':
  425. cfg.verbosity += 1
  426. cfg.quiet = False
  427. elif k == '-p':
  428. cfg.progress = True
  429. cfg.quiet = False
  430. elif k == '-q':
  431. cfg.verbosity = 0
  432. cfg.progress = False
  433. cfg.quiet = True
  434. elif k == '-u':
  435. cfg.unit_tests = True
  436. elif k == '-f':
  437. cfg.functional_tests = True
  438. elif k == '-w':
  439. cfg.warn_omitted = True
  440. elif k == '--list-files':
  441. cfg.list_files = True
  442. cfg.run_tests = False
  443. elif k == '--list-tests':
  444. cfg.list_tests = True
  445. cfg.run_tests = False
  446. elif k == '--list-hooks':
  447. cfg.list_hooks = True
  448. cfg.run_tests = False
  449. elif k == '--coverage':
  450. cfg.coverage = True
  451. elif k == '--level':
  452. try:
  453. cfg.level = int(v)
  454. except ValueError:
  455. stderr('%s: invalid level: %s' % (argv[0], v))
  456. stderr('run %s -h for help')
  457. return 1
  458. elif k == '--all-levels':
  459. cfg.level = None
  460. else:
  461. stderr('%s: invalid option: %s' % (argv[0], k))
  462. stderr('run %s -h for help')
  463. return 1
  464. if args:
  465. cfg.pathname_regex = args[0]
  466. if len(args) > 1:
  467. cfg.test_regex = args[1]
  468. if len(args) > 2:
  469. stderr('%s: too many arguments: %s' % (argv[0], args[2]))
  470. stderr('run %s -h for help')
  471. return 1
  472. if not cfg.unit_tests and not cfg.functional_tests:
  473. cfg.unit_tests = True
  474. # Set up the python path
  475. sys.path[0] = cfg.basedir
  476. # Set up tracing before we start importing things
  477. tracer = None
  478. if cfg.run_tests and cfg.coverage:
  479. import trace
  480. # trace.py in Python 2.3.1 is buggy:
  481. # 1) Despite sys.prefix being in ignoredirs, a lot of system-wide
  482. # modules are included in the coverage reports
  483. # 2) Some module file names do not have the first two characters,
  484. # and in general the prefix used seems to be arbitrary
  485. # These bugs are fixed in src/trace.py which should be in PYTHONPATH
  486. # before the official one.
  487. ignoremods = ['test']
  488. ignoredirs = [sys.prefix, sys.exec_prefix]
  489. tracer = trace.Trace(count=True, trace=False,
  490. ignoremods=ignoremods, ignoredirs=ignoredirs)
  491. # Finding and importing
  492. test_files = get_test_files(cfg)
  493. if cfg.list_tests or cfg.run_tests:
  494. test_cases = get_test_cases(test_files, cfg, tracer=tracer)
  495. if cfg.list_hooks or cfg.run_tests:
  496. test_hooks = get_test_hooks(test_files, cfg, tracer=tracer)
  497. # Configure the logging module
  498. import logging
  499. logging.basicConfig()
  500. logging.root.setLevel(logging.CRITICAL)
  501. # Running
  502. success = True
  503. if cfg.list_files:
  504. baselen = len(cfg.basedir) + 1
  505. print("\n".join([fn[baselen:] for fn in test_files]))
  506. if cfg.list_tests:
  507. print("\n".join([test.id() for test in test_cases]))
  508. if cfg.list_hooks:
  509. print("\n".join([str(hook) for hook in test_hooks]))
  510. if cfg.run_tests:
  511. runner = CustomTestRunner(cfg, test_hooks)
  512. suite = unittest.TestSuite()
  513. suite.addTests(test_cases)
  514. if tracer is not None:
  515. success = tracer.runfunc(runner.run, suite).wasSuccessful()
  516. results = tracer.results()
  517. results.write_results(show_missing=True, coverdir=cfg.coverdir)
  518. else:
  519. success = runner.run(suite).wasSuccessful()
  520. # That's all
  521. if success:
  522. return 0
  523. else:
  524. return 1
  525. if __name__ == '__main__':
  526. exitcode = main(sys.argv)
  527. sys.exit(exitcode)