PageRenderTime 46ms CodeModel.GetById 13ms RepoModel.GetById 0ms app.codeStats 0ms

/util/testlib.py

https://gitlab.com/Smileyt/KomodoEdit
Python | 725 lines | 649 code | 22 blank | 54 comment | 27 complexity | d983f06fd6e4c7e89946b2adc151b688 MD5 | raw file
  1. #!python
  2. # Copyright (c) 2000-2008 ActiveState Software Inc.
  3. # License: MIT License (http://www.opensource.org/licenses/mit-license.php)
  4. """
  5. test suite harness
  6. Usage:
  7. test --list [<tags>...] # list available tests modules
  8. test [<tags>...] # run test modules
  9. Options:
  10. -v, --verbose more verbose output
  11. -q, --quiet don't print anything except if a test fails
  12. -d, --debug log debug information
  13. -h, --help print this text and exit
  14. -l, --list Just list the available test modules. You can also
  15. specify tags to play with module filtering.
  16. -n, --no-default-tags Ignore default tags
  17. -L <directive> Specify a logging level via
  18. <logname>:<levelname>
  19. For example:
  20. codeintel.db:DEBUG
  21. This option can be used multiple times.
  22. By default this will run all tests in all available "test_*" modules.
  23. Tags can be specified to control which tests are run. For example:
  24. test python # run tests with the 'python' tag
  25. test python cpln # run tests with both 'python' and 'cpln' tags
  26. test -- -python # exclude tests with the 'python' tag
  27. # (the '--' is necessary to end the option list)
  28. The full name and base name of a test module are implicit tags for that
  29. module, e.g. module "test_xdebug.py" has tags "test_xdebug" and "xdebug".
  30. A TestCase's class name (with and without "TestCase") is an implicit
  31. tag for an test_* methods. A "test_foo" method also has "test_foo"
  32. and "foo" implicit tags.
  33. Tags can be added explicitly added:
  34. - to modules via a __tags__ global list; and
  35. - to individual test_* methods via a "tags" attribute list (you can
  36. use the testlib.tag() decorator for this).
  37. """
  38. #TODO:
  39. # - Document how tests are found (note the special "test_cases()" and
  40. # "test_suite_class" hooks).
  41. # - See the optparse "TODO" below.
  42. # - Make the quiet option actually quiet.
  43. __version_info__ = (0, 6, 6)
  44. __version__ = '.'.join(map(str, __version_info__))
  45. import os
  46. from os.path import join, basename, dirname, abspath, splitext, \
  47. isfile, isdir, normpath, exists
  48. import sys
  49. import getopt
  50. import glob
  51. import time
  52. import types
  53. import tempfile
  54. import unittest
  55. from pprint import pprint
  56. import imp
  57. import optparse
  58. import logging
  59. import textwrap
  60. import traceback
  61. #---- globals and exceptions
  62. log = logging.getLogger("test")
  63. #---- exports generally useful to test cases
  64. class TestError(Exception):
  65. pass
  66. class TestSkipped(Exception):
  67. """Raise this to indicate that a test is being skipped.
  68. ConsoleTestRunner knows to interpret these at NOT failures.
  69. """
  70. pass
  71. class TestFailed(Exception):
  72. pass
  73. def tag(*tags):
  74. """Decorator to add tags to test_* functions.
  75. Example:
  76. class MyTestCase(unittest.TestCase):
  77. @testlib.tag("knownfailure")
  78. def test_foo(self):
  79. #...
  80. """
  81. def decorate(f):
  82. if not hasattr(f, "tags"):
  83. f.tags = []
  84. f.tags += tags
  85. return f
  86. return decorate
  87. #---- timedtest decorator
  88. # Use this to assert that a test completes in a given amount of time.
  89. # This is from http://www.artima.com/forums/flat.jsp?forum=122&thread=129497
  90. # Including here, becase it might be useful.
  91. # NOTE: Untested and I suspect some breakage.
  92. TOLERANCE = 0.05
  93. class DurationError(AssertionError): pass
  94. def timedtest(max_time, tolerance=TOLERANCE):
  95. """ timedtest decorator
  96. decorates the test method with a timer
  97. when the time spent by the test exceeds
  98. max_time in seconds, an Assertion error is thrown.
  99. """
  100. def _timedtest(function):
  101. def wrapper(*args, **kw):
  102. start_time = time.time()
  103. try:
  104. function(*args, **kw)
  105. finally:
  106. total_time = time.time() - start_time
  107. if total_time > max_time + tolerance:
  108. raise DurationError(('Test was too long (%.2f s)'
  109. % total_time))
  110. return wrapper
  111. return _timedtest
  112. #---- module api
  113. class Test(object):
  114. def __init__(self, ns, testmod, testcase, testfn_name,
  115. testsuite_class=None):
  116. self.ns = ns
  117. self.testmod = testmod
  118. self.testcase = testcase
  119. self.testfn_name = testfn_name
  120. self.testsuite_class = testsuite_class
  121. # Give each testcase some extra testlib attributes for useful
  122. # introspection on TestCase instances later on.
  123. self.testcase._testlib_shortname_ = self.shortname()
  124. self.testcase._testlib_explicit_tags_ = self.explicit_tags()
  125. self.testcase._testlib_implicit_tags_ = self.implicit_tags()
  126. def __str__(self):
  127. return self.shortname()
  128. def __repr__(self):
  129. return "<Test %s>" % self.shortname()
  130. def shortname(self):
  131. bits = [self._normname(self.testmod.__name__),
  132. self._normname(self.testcase.__class__.__name__),
  133. self._normname(self.testfn_name)]
  134. if self.ns:
  135. bits.insert(0, self.ns)
  136. return '/'.join(bits)
  137. def _flatten_tags(self, tags):
  138. """Split tags with '/' in them into multiple tags.
  139. '/' is the reserved tag separator and allowing tags with
  140. embedded '/' results in one being unable to select those via
  141. filtering. As long as tag order is stable then presentation of
  142. these subsplit tags should be fine.
  143. """
  144. flattened = []
  145. for t in tags:
  146. flattened += t.replace(os.sep, '/').split('/')
  147. return flattened
  148. def explicit_tags(self):
  149. tags = []
  150. if hasattr(self.testmod, "__tags__"):
  151. tags += self.testmod.__tags__
  152. if hasattr(self.testcase, "__tags__"):
  153. tags += self.testcase.__tags__
  154. testfn = getattr(self.testcase, self.testfn_name)
  155. if hasattr(testfn, "tags"):
  156. tags += testfn.tags
  157. return self._flatten_tags(tags)
  158. def implicit_tags(self):
  159. tags = [
  160. self.testmod.__name__.lower(),
  161. self._normname(self.testmod.__name__),
  162. self.testcase.__class__.__name__.lower(),
  163. self._normname(self.testcase.__class__.__name__),
  164. self.testfn_name,
  165. self._normname(self.testfn_name),
  166. ]
  167. if self.ns:
  168. tags.insert(0, self.ns)
  169. return self._flatten_tags(tags)
  170. def tags(self):
  171. return self.explicit_tags() + self.implicit_tags()
  172. def doc(self):
  173. testfn = getattr(self.testcase, self.testfn_name)
  174. return testfn.__doc__ or ""
  175. def _normname(self, name):
  176. if name.startswith("test_"):
  177. return name[5:].lower()
  178. elif name.startswith("test"):
  179. return name[4:].lower()
  180. elif name.endswith("TestCase"):
  181. return name[:-8].lower()
  182. else:
  183. return name
  184. def testmod_paths_from_testdir(testdir):
  185. """Generate test module paths in the given dir."""
  186. for path in glob.glob(join(testdir, "test_*.py")):
  187. yield path
  188. for path in glob.glob(join(testdir, "test_*")):
  189. if not isdir(path): continue
  190. if not isfile(join(path, "__init__.py")): continue
  191. yield path
  192. def testmods_from_testdir(testdir):
  193. """Generate test modules in the given test dir.
  194. Modules are imported with 'testdir' first on sys.path.
  195. """
  196. testdir = normpath(testdir)
  197. for testmod_path in testmod_paths_from_testdir(testdir):
  198. testmod_name = splitext(basename(testmod_path))[0]
  199. log.debug("import test module '%s'", testmod_path)
  200. try:
  201. iinfo = imp.find_module(testmod_name, [dirname(testmod_path)])
  202. testabsdir = abspath(testdir)
  203. sys.path.insert(0, testabsdir)
  204. old_dir = os.getcwd()
  205. os.chdir(testdir)
  206. try:
  207. testmod = imp.load_module(testmod_name, *iinfo)
  208. finally:
  209. os.chdir(old_dir)
  210. sys.path.remove(testabsdir)
  211. except TestSkipped:
  212. _, ex, _ = sys.exc_info()
  213. log.warn("'%s' module skipped: %s", testmod_name, ex)
  214. except Exception:
  215. _, ex, _ = sys.exc_info()
  216. log.warn("could not import test module '%s': %s (skipping, "
  217. "run with '-d' for full traceback)",
  218. testmod_path, ex)
  219. if log.isEnabledFor(logging.DEBUG):
  220. traceback.print_exc()
  221. else:
  222. yield testmod
  223. def testcases_from_testmod(testmod):
  224. """Gather tests from a 'test_*' module.
  225. Returns a list of TestCase-subclass instances. One instance for each
  226. found test function.
  227. In general the normal unittest TestLoader.loadTests*() semantics are
  228. used for loading tests with some differences:
  229. - TestCase subclasses beginning with '_' are skipped (presumed to be
  230. internal).
  231. - If the module has a top-level "test_cases", it is called for a list of
  232. TestCase subclasses from which to load tests (can be a generator). This
  233. allows for run-time setup of test cases.
  234. - If the module has a top-level "test_suite_class", it is used to group
  235. all test cases from that module into an instance of that TestSuite
  236. subclass. This allows for overriding of test running behaviour.
  237. """
  238. class TestListLoader(unittest.TestLoader):
  239. suiteClass = list
  240. loader = TestListLoader()
  241. if hasattr(testmod, "test_cases"):
  242. try:
  243. for testcase_class in testmod.test_cases():
  244. if testcase_class.__name__.startswith("_"):
  245. log.debug("skip private TestCase class '%s'",
  246. testcase_class.__name__)
  247. continue
  248. for testcase in loader.loadTestsFromTestCase(testcase_class):
  249. yield testcase
  250. except Exception:
  251. _, ex, _ = sys.exc_info()
  252. testmod_path = testmod.__file__
  253. if testmod_path.endswith(".pyc"):
  254. testmod_path = testmod_path[:-1]
  255. log.warn("error running test_cases() in '%s': %s (skipping, "
  256. "run with '-d' for full traceback)",
  257. testmod_path, ex)
  258. if log.isEnabledFor(logging.DEBUG):
  259. traceback.print_exc()
  260. else:
  261. class_names_skipped = []
  262. for testcases in loader.loadTestsFromModule(testmod):
  263. for testcase in testcases:
  264. class_name = testcase.__class__.__name__
  265. if class_name in class_names_skipped:
  266. pass
  267. elif class_name.startswith("_"):
  268. log.debug("skip private TestCase class '%s'", class_name)
  269. class_names_skipped.append(class_name)
  270. else:
  271. yield testcase
  272. def tests_from_manifest(testdir_from_ns):
  273. """Return a list of `testlib.Test` instances for each test found in
  274. the manifest.
  275. There will be a test for
  276. (a) each "test*" function of
  277. (b) each TestCase-subclass in
  278. (c) each "test_*" Python module in
  279. (d) each test dir in the manifest.
  280. If a "test_*" module has a top-level "test_suite_class", it will later
  281. be used to group all test cases from that module into an instance of that
  282. TestSuite subclass. This allows for overriding of test running behaviour.
  283. """
  284. for ns, testdir in testdir_from_ns.items():
  285. for testmod in testmods_from_testdir(testdir):
  286. if hasattr(testmod, "test_suite_class"):
  287. testsuite_class = testmod.test_suite_class
  288. if not issubclass(testsuite_class, unittest.TestSuite):
  289. testmod_path = testmod.__file__
  290. if testmod_path.endswith(".pyc"):
  291. testmod_path = testmod_path[:-1]
  292. log.warn("'test_suite_class' of '%s' module is not a "
  293. "subclass of 'unittest.TestSuite': ignoring",
  294. testmod_path)
  295. else:
  296. testsuite_class = None
  297. for testcase in testcases_from_testmod(testmod):
  298. try:
  299. yield Test(ns, testmod, testcase,
  300. testcase._testMethodName,
  301. testsuite_class)
  302. except AttributeError:
  303. # Python 2.4 and older:
  304. yield Test(ns, testmod, testcase,
  305. testcase._TestCase__testMethodName,
  306. testsuite_class)
  307. def tests_from_manifest_and_tags(testdir_from_ns, tags):
  308. include_tags = [tag.lower() for tag in tags if not tag.startswith('-')]
  309. exclude_tags = [tag[1:].lower() for tag in tags if tag.startswith('-')]
  310. for test in tests_from_manifest(testdir_from_ns):
  311. test_tags = [t.lower() for t in test.tags()]
  312. matching_exclude_tags = [t for t in exclude_tags if t in test_tags]
  313. if matching_exclude_tags:
  314. #log.debug("test '%s' matches exclude tag(s) '%s': skipping",
  315. # test.shortname(), "', '".join(matching_exclude_tags))
  316. continue
  317. if not include_tags:
  318. yield test
  319. else:
  320. for tag in include_tags:
  321. if tag not in test_tags:
  322. #log.debug("test '%s' does not match tag '%s': skipping",
  323. # test.shortname(), tag)
  324. break
  325. else:
  326. #log.debug("test '%s' matches tags: %s", test.shortname(),
  327. # ' '.join(tags))
  328. yield test
  329. def test(testdir_from_ns, tags=[], setup_func=None):
  330. log.debug("test(testdir_from_ns=%r, tags=%r, ...)",
  331. testdir_from_ns, tags)
  332. if setup_func is not None:
  333. setup_func()
  334. tests = list(tests_from_manifest_and_tags(testdir_from_ns, tags))
  335. if not tests:
  336. return None
  337. # Groups test cases into a test suite class given by their test module's
  338. # "test_suite_class" hook, if any.
  339. suite = unittest.TestSuite()
  340. suite_for_testmod = None
  341. testmod = None
  342. for test in tests:
  343. if test.testmod != testmod:
  344. if suite_for_testmod is not None:
  345. suite.addTest(suite_for_testmod)
  346. suite_for_testmod = (test.testsuite_class or unittest.TestSuite)()
  347. testmod = test.testmod
  348. suite_for_testmod.addTest(test.testcase)
  349. if suite_for_testmod is not None:
  350. suite.addTest(suite_for_testmod)
  351. runner = ConsoleTestRunner(sys.stdout)
  352. result = runner.run(suite)
  353. return result
  354. def list_tests(testdir_from_ns, tags):
  355. # Say I have two test_* modules:
  356. # test_python.py:
  357. # __tags__ = ["guido"]
  358. # class BasicTestCase(unittest.TestCase):
  359. # def test_def(self):
  360. # def test_class(self):
  361. # class ComplexTestCase(unittest.TestCase):
  362. # def test_foo(self):
  363. # def test_bar(self):
  364. # test_perl/__init__.py:
  365. # __tags__ = ["larry", "wall"]
  366. # class BasicTestCase(unittest.TestCase):
  367. # def test_sub(self):
  368. # def test_package(self):
  369. # class EclecticTestCase(unittest.TestCase):
  370. # def test_foo(self):
  371. # def test_bar(self):
  372. # The short-form list output for this should look like:
  373. # python/basic/def [guido]
  374. # python/basic/class [guido]
  375. # python/complex/foo [guido]
  376. # python/complex/bar [guido]
  377. # perl/basic/sub [larry, wall]
  378. # perl/basic/package [larry, wall]
  379. # perl/eclectic/foo [larry, wall]
  380. # perl/eclectic/bar [larry, wall]
  381. log.debug("list_tests(testdir_from_ns=%r, tags=%r)",
  382. testdir_from_ns, tags)
  383. tests = list(tests_from_manifest_and_tags(testdir_from_ns, tags))
  384. if not tests:
  385. return
  386. WIDTH = 78
  387. if log.isEnabledFor(logging.INFO): # long-form
  388. for i, t in enumerate(tests):
  389. if i:
  390. print()
  391. testfile = t.testmod.__file__
  392. if testfile.endswith(".pyc"):
  393. testfile = testfile[:-1]
  394. print("%s:" % t.shortname())
  395. print(" from: %s#%s.%s" % (testfile,
  396. t.testcase.__class__.__name__, t.testfn_name))
  397. wrapped = textwrap.fill(' '.join(t.tags()), WIDTH-10)
  398. print(" tags: %s" % _indent(wrapped, 8, True))
  399. if t.doc():
  400. print(_indent(t.doc(), width=2))
  401. else:
  402. for t in tests:
  403. line = t.shortname() + ' '
  404. if t.explicit_tags():
  405. line += '[%s]' % ' '.join(t.explicit_tags())
  406. print(line)
  407. #---- text test runner that can handle TestSkipped reasonably
  408. class ConsoleTestResult(unittest.TestResult):
  409. """A test result class that can print formatted text results to a stream.
  410. Used by ConsoleTestRunner.
  411. """
  412. separator1 = '=' * 70
  413. separator2 = '-' * 70
  414. def __init__(self, stream):
  415. unittest.TestResult.__init__(self)
  416. self.skips = []
  417. self.stream = stream
  418. def getDescription(self, test):
  419. try:
  420. if test._testlib_explicit_tags_:
  421. return "%s [%s]" % (test._testlib_shortname_,
  422. ', '.join(test._testlib_explicit_tags_))
  423. else:
  424. return test._testlib_shortname_
  425. except:
  426. return "<Error getting description for %s>" % (test,)
  427. def startTest(self, test):
  428. unittest.TestResult.startTest(self, test)
  429. self.stream.write(self.getDescription(test))
  430. self.stream.write(" ... ")
  431. def addSuccess(self, test):
  432. unittest.TestResult.addSuccess(self, test)
  433. self.stream.write("ok\n")
  434. def addSkip(self, test, err):
  435. why = str(err[1])
  436. self.skips.append((test, why))
  437. self.stream.write("skipped (%s)\n" % why)
  438. def addError(self, test, err):
  439. if isinstance(err[1], TestSkipped):
  440. self.addSkip(test, err)
  441. else:
  442. unittest.TestResult.addError(self, test, err)
  443. self.stream.write("ERROR\n")
  444. def addFailure(self, test, err):
  445. unittest.TestResult.addFailure(self, test, err)
  446. self.stream.write("FAIL\n")
  447. def printSummary(self):
  448. self.stream.write('\n')
  449. self.printErrorList('ERROR', self.errors)
  450. self.printErrorList('FAIL', self.failures)
  451. def printErrorList(self, flavour, errors):
  452. for test, err in errors:
  453. self.stream.write(self.separator1 + '\n')
  454. self.stream.write("%s: %s\n"
  455. % (flavour, self.getDescription(test)))
  456. self.stream.write(self.separator2 + '\n')
  457. self.stream.write("%s\n" % err)
  458. class ConsoleTestRunner(object):
  459. """A test runner class that displays results on the console.
  460. It prints out the names of tests as they are run, errors as they
  461. occur, and a summary of the results at the end of the test run.
  462. Differences with unittest.TextTestRunner:
  463. - adds support for *skipped* tests (those that raise TestSkipped)
  464. - no verbosity option (only have equiv of verbosity=2)
  465. - test "short desc" is it 3-level tag name (e.g. 'foo/bar/baz' where
  466. that identifies: 'test_foo.py::BarTestCase.test_baz'.
  467. """
  468. def __init__(self, stream=sys.stderr):
  469. self.stream = stream
  470. def run(self, test_or_suite, test_result_class=ConsoleTestResult):
  471. """Run the given test case or test suite."""
  472. result = test_result_class(self.stream)
  473. start_time = time.time()
  474. test_or_suite.run(result)
  475. time_taken = time.time() - start_time
  476. result.printSummary()
  477. self.stream.write(result.separator2 + '\n')
  478. self.stream.write("Ran %d test%s in %.3fs\n\n"
  479. % (result.testsRun, result.testsRun != 1 and "s" or "",
  480. time_taken))
  481. details = []
  482. num_skips = len(result.skips)
  483. if num_skips:
  484. details.append("%d skip%s"
  485. % (num_skips, (num_skips != 1 and "s" or "")))
  486. if not result.wasSuccessful():
  487. num_failures = len(result.failures)
  488. if num_failures:
  489. details.append("%d failure%s"
  490. % (num_failures, (num_failures != 1 and "s" or "")))
  491. num_errors = len(result.errors)
  492. if num_errors:
  493. details.append("%d error%s"
  494. % (num_errors, (num_errors != 1 and "s" or "")))
  495. self.stream.write("FAILED (%s)\n" % ', '.join(details))
  496. elif details:
  497. self.stream.write("OK (%s)\n" % ', '.join(details))
  498. else:
  499. self.stream.write("OK\n")
  500. return result
  501. #---- internal support stuff
  502. # Recipe: indent (0.2.1)
  503. def _indent(s, width=4, skip_first_line=False):
  504. """_indent(s, [width=4]) -> 's' indented by 'width' spaces
  505. The optional "skip_first_line" argument is a boolean (default False)
  506. indicating if the first line should NOT be indented.
  507. """
  508. lines = s.splitlines(1)
  509. indentstr = ' '*width
  510. if skip_first_line:
  511. return indentstr.join(lines)
  512. else:
  513. return indentstr + indentstr.join(lines)
  514. #---- mainline
  515. #TODO: pass in add_help_option=False and add it ourself here.
  516. ## Optparse's handling of the doc passed in for -h|--help handling is
  517. ## abysmal. Hence we'll stick with getopt.
  518. #def _parse_opts(args):
  519. # """_parse_opts(args) -> (options, tags)"""
  520. # usage = "usage: %prog [OPTIONS...] [TAGS...]"
  521. # parser = optparse.OptionParser(prog="test", usage=usage,
  522. # description=__doc__)
  523. # parser.add_option("-v", "--verbose", dest="log_level",
  524. # action="store_const", const=logging.DEBUG,
  525. # help="more verbose output")
  526. # parser.add_option("-q", "--quiet", dest="log_level",
  527. # action="store_const", const=logging.WARNING,
  528. # help="quieter output")
  529. # parser.add_option("-l", "--list", dest="action",
  530. # action="store_const", const="list",
  531. # help="list available tests")
  532. # parser.set_defaults(log_level=logging.INFO, action="test")
  533. # opts, raw_tags = parser.parse_args()
  534. #
  535. # # Trim '.py' from user-supplied tags. They might have gotten there
  536. # # via shell expansion.
  537. # ...
  538. #
  539. # return opts, raw_tags
  540. def _parse_opts(args, default_tags):
  541. """_parse_opts(args) -> (log_level, action, tags)"""
  542. opts, raw_tags = getopt.getopt(args, "hvqdlL:n",
  543. ["help", "verbose", "quiet", "debug", "list", "no-default-tags"])
  544. log_level = logging.WARN
  545. action = "test"
  546. no_default_tags = False
  547. for opt, optarg in opts:
  548. if opt in ("-h", "--help"):
  549. action = "help"
  550. elif opt in ("-v", "--verbose"):
  551. log_level = logging.INFO
  552. elif opt in ("-q", "--quiet"):
  553. log_level = logging.ERROR
  554. elif opt in ("-d", "--debug"):
  555. log_level = logging.DEBUG
  556. elif opt in ("-l", "--list"):
  557. action = "list"
  558. elif opt in ("-n", "--no-default-tags"):
  559. no_default_tags = True
  560. elif opt == "-L":
  561. # Optarg is of the form '<logname>:<levelname>', e.g.
  562. # "codeintel:DEBUG", "codeintel.db:INFO".
  563. # if :<levelname> is not given, default to DEBUG
  564. lname, llevelname = (optarg.split(':', 1) + ["DEBUG"])[:2]
  565. llevel = getattr(logging, llevelname)
  566. logging.getLogger(lname).setLevel(llevel)
  567. # Clean up the given tags.
  568. if no_default_tags:
  569. tags = []
  570. else:
  571. tags = default_tags
  572. for raw_tag in raw_tags:
  573. if splitext(raw_tag)[1] in (".py", ".pyc", ".pyo", ".pyw") \
  574. and exists(raw_tag):
  575. # Trim '.py' from user-supplied tags if it looks to be from
  576. # shell expansion.
  577. tags.append(splitext(raw_tag)[0])
  578. elif '/' in raw_tag:
  579. # Split one '/' to allow the shortname from the test listing
  580. # to be used as a filter.
  581. tags += raw_tag.split('/')
  582. else:
  583. tags.append(raw_tag)
  584. return log_level, action, tags
  585. def harness(testdir_from_ns={None: os.curdir}, argv=sys.argv,
  586. setup_func=None, default_tags=None):
  587. """Convenience mainline for a test harness "test.py" script.
  588. "testdir_from_ns" (optional) is basically a set of directories in
  589. which to look for test cases. It is a dict with:
  590. <namespace>: <testdir>
  591. where <namespace> is a (short) string that becomes part of the
  592. included test names and an implicit tag for filtering those
  593. tests. By default the current dir is use with an empty namespace:
  594. {None: os.curdir}
  595. "setup_func" (optional) is a callable that will be called once
  596. before any tests are run to prepare for the test suite. It
  597. is not called if no tests will be run.
  598. "default_tags" (optional)
  599. Typically, if you have a number of test_*.py modules you can create
  600. a test harness, "test.py", for them that looks like this:
  601. #!/usr/bin/env python
  602. if __name__ == "__main__":
  603. retval = testlib.harness()
  604. sys.exit(retval)
  605. """
  606. if not logging.root.handlers:
  607. logging.basicConfig()
  608. try:
  609. log_level, action, tags = _parse_opts(argv[1:], default_tags or [])
  610. except getopt.error:
  611. _, ex, _ = sys.exc_info()
  612. log.error(str(ex) + " (did you need a '--' before a '-TAG' argument?)")
  613. return 1
  614. log.setLevel(log_level)
  615. if action == "help":
  616. print(__doc__)
  617. return 0
  618. if action == "list":
  619. return list_tests(testdir_from_ns, tags)
  620. elif action == "test":
  621. result = test(testdir_from_ns, tags, setup_func=setup_func)
  622. if result is None:
  623. return None
  624. return len(result.errors) + len(result.failures)
  625. else:
  626. raise TestError("unexpected action/mode: '%s'" % action)