PageRenderTime 54ms CodeModel.GetById 16ms RepoModel.GetById 0ms app.codeStats 0ms

/contrib/mk/test/testlib.py

https://gitlab.com/Smileyt/KomodoEdit
Python | 706 lines | 630 code | 22 blank | 54 comment | 26 complexity | b5e2aa3c78983a611afde398435c8cfe MD5 | raw file
  1. #!python
  2. # Copyright (c) 2000-2006 ActiveState Software Inc.
  3. # See the file LICENSE.txt for licensing information.
  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. -L <directive> Specify a logging level via
  17. <logname>:<levelname>
  18. For example:
  19. codeintel.db:DEBUG
  20. This option can be used multiple times.
  21. By default this will run all tests in all available "test_*" modules.
  22. Tags can be specified to control which tests are run. For example:
  23. test python # run tests with the 'python' tag
  24. test python cpln # run tests with both 'python' and 'cpln' tags
  25. test -- -python # exclude tests with the 'python' tag
  26. # (the '--' is necessary to end the option list)
  27. The full name and base name of a test module are implicit tags for that
  28. module, e.g. module "test_xdebug.py" has tags "test_xdebug" and "xdebug".
  29. A TestCase's class name (with and without "TestCase") is an implicit
  30. tag for an test_* methods. A "test_foo" method also has "test_foo"
  31. and "foo" implicit tags.
  32. Tags can be added explicitly added:
  33. - to modules via a __tags__ global list; and
  34. - to individual test_* methods via a "tags" attribute list (you can
  35. use the testlib.tag() decorator for this).
  36. """
  37. #TODO:
  38. # - Document how tests are found (note the special "test_cases()" and
  39. # "test_suite_class" hooks).
  40. # - See the optparse "TODO" below.
  41. # - Make the quiet option actually quiet.
  42. __revision__ = "$Id: testlib.py 199 2007-10-22 21:25:26Z trentm $"
  43. __version_info__ = (0, 4, 0)
  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:
  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.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. sys.path.insert(0, testdir)
  203. try:
  204. testmod = imp.load_module(testmod_name, *iinfo)
  205. finally:
  206. del sys.path[0]
  207. except TestSkipped, ex:
  208. log.warn("'%s' module skipped: %s", testmod_name, ex)
  209. except Exception, ex:
  210. log.warn("could not import test module '%s': %s (skipping, "
  211. "run with '-d' for full traceback)",
  212. testmod_path, ex)
  213. if log.isEnabledFor(logging.DEBUG):
  214. traceback.print_exc()
  215. else:
  216. yield testmod
  217. def testcases_from_testmod(testmod):
  218. """Gather tests from a 'test_*' module.
  219. Returns a list of TestCase-subclass instances. One instance for each
  220. found test function.
  221. In general the normal unittest TestLoader.loadTests*() semantics are
  222. used for loading tests with some differences:
  223. - TestCase subclasses beginning with '_' are skipped (presumed to be
  224. internal).
  225. - If the module has a top-level "test_cases", it is called for a list of
  226. TestCase subclasses from which to load tests (can be a generator). This
  227. allows for run-time setup of test cases.
  228. - If the module has a top-level "test_suite_class", it is used to group
  229. all test cases from that module into an instance of that TestSuite
  230. subclass. This allows for overriding of test running behaviour.
  231. """
  232. class TestListLoader(unittest.TestLoader):
  233. suiteClass = list
  234. loader = TestListLoader()
  235. if hasattr(testmod, "test_cases"):
  236. try:
  237. for testcase_class in testmod.test_cases():
  238. if testcase_class.__name__.startswith("_"):
  239. log.debug("skip private TestCase class '%s'",
  240. testcase_class.__name__)
  241. continue
  242. for testcase in loader.loadTestsFromTestCase(testcase_class):
  243. yield testcase
  244. except Exception, ex:
  245. testmod_path = testmod.__file__
  246. if testmod_path.endswith(".pyc"):
  247. testmod_path = testmod_path[:-1]
  248. log.warn("error running test_cases() in '%s': %s (skipping, "
  249. "run with '-d' for full traceback)",
  250. testmod_path, ex)
  251. if log.isEnabledFor(logging.DEBUG):
  252. traceback.print_exc()
  253. else:
  254. class_names_skipped = []
  255. for testcases in loader.loadTestsFromModule(testmod):
  256. for testcase in testcases:
  257. class_name = testcase.__class__.__name__
  258. if class_name in class_names_skipped:
  259. pass
  260. elif class_name.startswith("_"):
  261. log.debug("skip private TestCase class '%s'", class_name)
  262. class_names_skipped.append(class_name)
  263. else:
  264. yield testcase
  265. def tests_from_manifest(testdir_from_ns):
  266. """Return a list of `testlib.Test` instances for each test found in
  267. the manifest.
  268. There will be a test for
  269. (a) each "test*" function of
  270. (b) each TestCase-subclass in
  271. (c) each "test_*" Python module in
  272. (d) each test dir in the manifest.
  273. If a "test_*" module has a top-level "test_suite_class", it will later
  274. be used to group all test cases from that module into an instance of that
  275. TestSuite subclass. This allows for overriding of test running behaviour.
  276. """
  277. for ns, testdir in testdir_from_ns.items():
  278. for testmod in testmods_from_testdir(testdir):
  279. if hasattr(testmod, "test_suite_class"):
  280. testsuite_class = testmod.test_suite_class
  281. if not issubclass(testsuite_class, unittest.TestSuite):
  282. testmod_path = testmod.__file__
  283. if testmod_path.endswith(".pyc"):
  284. testmod_path = testmod_path[:-1]
  285. log.warn("'test_suite_class' of '%s' module is not a "
  286. "subclass of 'unittest.TestSuite': ignoring",
  287. testmod_path)
  288. else:
  289. testsuite_class = None
  290. for testcase in testcases_from_testmod(testmod):
  291. try:
  292. yield Test(ns, testmod, testcase,
  293. testcase._testMethodName,
  294. testsuite_class)
  295. except AttributeError:
  296. # Python 2.4 and older:
  297. yield Test(ns, testmod, testcase,
  298. testcase._TestCase__testMethodName,
  299. testsuite_class)
  300. def tests_from_manifest_and_tags(testdir_from_ns, tags):
  301. include_tags = [tag.lower() for tag in tags if not tag.startswith('-')]
  302. exclude_tags = [tag[1:].lower() for tag in tags if tag.startswith('-')]
  303. for test in tests_from_manifest(testdir_from_ns):
  304. test_tags = [t.lower() for t in test.tags()]
  305. matching_exclude_tags = [t for t in exclude_tags if t in test_tags]
  306. if matching_exclude_tags:
  307. #log.debug("test '%s' matches exclude tag(s) '%s': skipping",
  308. # test.shortname(), "', '".join(matching_exclude_tags))
  309. continue
  310. if not include_tags:
  311. yield test
  312. else:
  313. for tag in include_tags:
  314. if tag not in test_tags:
  315. #log.debug("test '%s' does not match tag '%s': skipping",
  316. # test.shortname(), tag)
  317. break
  318. else:
  319. #log.debug("test '%s' matches tags: %s", test.shortname(),
  320. # ' '.join(tags))
  321. yield test
  322. def test(testdir_from_ns, tags=[], setup_func=None):
  323. log.debug("test(testdir_from_ns=%r, tags=%r, ...)",
  324. testdir_from_ns, tags)
  325. tests = list(tests_from_manifest_and_tags(testdir_from_ns, tags))
  326. if not tests:
  327. return None
  328. if tests and setup_func is not None:
  329. setup_func()
  330. # Groups test cases into a test suite class given by their test module's
  331. # "test_suite_class" hook, if any.
  332. suite = unittest.TestSuite()
  333. suite_for_testmod = None
  334. testmod = None
  335. for test in tests:
  336. if test.testmod != testmod:
  337. if suite_for_testmod is not None:
  338. suite.addTest(suite_for_testmod)
  339. suite_for_testmod = (test.testsuite_class or unittest.TestSuite)()
  340. testmod = test.testmod
  341. suite_for_testmod.addTest(test.testcase)
  342. if suite_for_testmod is not None:
  343. suite.addTest(suite_for_testmod)
  344. runner = ConsoleTestRunner(sys.stdout)
  345. result = runner.run(suite)
  346. return result
  347. def list_tests(testdir_from_ns, tags):
  348. # Say I have two test_* modules:
  349. # test_python.py:
  350. # __tags__ = ["guido"]
  351. # class BasicTestCase(unittest.TestCase):
  352. # def test_def(self):
  353. # def test_class(self):
  354. # class ComplexTestCase(unittest.TestCase):
  355. # def test_foo(self):
  356. # def test_bar(self):
  357. # test_perl/__init__.py:
  358. # __tags__ = ["larry", "wall"]
  359. # class BasicTestCase(unittest.TestCase):
  360. # def test_sub(self):
  361. # def test_package(self):
  362. # class EclecticTestCase(unittest.TestCase):
  363. # def test_foo(self):
  364. # def test_bar(self):
  365. # The short-form list output for this should look like:
  366. # python/basic/def [guido]
  367. # python/basic/class [guido]
  368. # python/complex/foo [guido]
  369. # python/complex/bar [guido]
  370. # perl/basic/sub [larry, wall]
  371. # perl/basic/package [larry, wall]
  372. # perl/eclectic/foo [larry, wall]
  373. # perl/eclectic/bar [larry, wall]
  374. log.debug("list_tests(testdir_from_ns=%r, tags=%r)",
  375. testdir_from_ns, tags)
  376. tests = list(tests_from_manifest_and_tags(testdir_from_ns, tags))
  377. if not tests:
  378. return
  379. WIDTH = 78
  380. if log.isEnabledFor(logging.INFO): # long-form
  381. for i, t in enumerate(tests):
  382. if i:
  383. print
  384. testfile = t.testmod.__file__
  385. if testfile.endswith(".pyc"):
  386. testfile = testfile[:-1]
  387. print "%s:" % t.shortname()
  388. print " from: %s#%s.%s" \
  389. % (testfile, t.testcase.__class__.__name__, t.testfn_name)
  390. wrapped = textwrap.fill(' '.join(t.tags()), WIDTH-10)
  391. print " tags: %s" % _indent(wrapped, 8, True)
  392. if t.doc():
  393. print _indent(t.doc(), width=2)
  394. else:
  395. for t in tests:
  396. line = t.shortname() + ' '
  397. if t.explicit_tags():
  398. line += '[%s]' % ' '.join(t.explicit_tags())
  399. print line
  400. #---- text test runner that can handle TestSkipped reasonably
  401. class _ConsoleTestResult(unittest.TestResult):
  402. """A test result class that can print formatted text results to a stream.
  403. Used by ConsoleTestRunner.
  404. """
  405. separator1 = '=' * 70
  406. separator2 = '-' * 70
  407. def __init__(self, stream):
  408. unittest.TestResult.__init__(self)
  409. self.skips = []
  410. self.stream = stream
  411. def getDescription(self, test):
  412. if test._testlib_explicit_tags_:
  413. return "%s [%s]" % (test._testlib_shortname_,
  414. ', '.join(test._testlib_explicit_tags_))
  415. else:
  416. return test._testlib_shortname_
  417. def startTest(self, test):
  418. unittest.TestResult.startTest(self, test)
  419. self.stream.write(self.getDescription(test))
  420. self.stream.write(" ... ")
  421. def addSuccess(self, test):
  422. unittest.TestResult.addSuccess(self, test)
  423. self.stream.write("ok\n")
  424. def addSkip(self, test, err):
  425. why = str(err[1])
  426. self.skips.append((test, why))
  427. self.stream.write("skipped (%s)\n" % why)
  428. def addError(self, test, err):
  429. if isinstance(err[1], TestSkipped):
  430. self.addSkip(test, err)
  431. else:
  432. unittest.TestResult.addError(self, test, err)
  433. self.stream.write("ERROR\n")
  434. def addFailure(self, test, err):
  435. unittest.TestResult.addFailure(self, test, err)
  436. self.stream.write("FAIL\n")
  437. def printSummary(self):
  438. self.stream.write('\n')
  439. self.printErrorList('ERROR', self.errors)
  440. self.printErrorList('FAIL', self.failures)
  441. def printErrorList(self, flavour, errors):
  442. for test, err in errors:
  443. self.stream.write(self.separator1 + '\n')
  444. self.stream.write("%s: %s\n"
  445. % (flavour, self.getDescription(test)))
  446. self.stream.write(self.separator2 + '\n')
  447. self.stream.write("%s\n" % err)
  448. class ConsoleTestRunner:
  449. """A test runner class that displays results on the console.
  450. It prints out the names of tests as they are run, errors as they
  451. occur, and a summary of the results at the end of the test run.
  452. Differences with unittest.TextTestRunner:
  453. - adds support for *skipped* tests (those that raise TestSkipped)
  454. - no verbosity option (only have equiv of verbosity=2)
  455. - test "short desc" is it 3-level tag name (e.g. 'foo/bar/baz' where
  456. that identifies: 'test_foo.py::BarTestCase.test_baz'.
  457. """
  458. def __init__(self, stream=sys.stderr):
  459. self.stream = stream
  460. def run(self, test_or_suite):
  461. """Run the given test case or test suite."""
  462. result = _ConsoleTestResult(self.stream)
  463. start_time = time.time()
  464. test_or_suite.run(result)
  465. time_taken = time.time() - start_time
  466. result.printSummary()
  467. self.stream.write(result.separator2 + '\n')
  468. self.stream.write("Ran %d test%s in %.3fs\n\n"
  469. % (result.testsRun, result.testsRun != 1 and "s" or "",
  470. time_taken))
  471. details = []
  472. num_skips = len(result.skips)
  473. if num_skips:
  474. details.append("%d skip%s"
  475. % (num_skips, (num_skips != 1 and "s" or "")))
  476. if not result.wasSuccessful():
  477. num_failures = len(result.failures)
  478. if num_failures:
  479. details.append("%d failure%s"
  480. % (num_failures, (num_failures != 1 and "s" or "")))
  481. num_errors = len(result.errors)
  482. if num_errors:
  483. details.append("%d error%s"
  484. % (num_errors, (num_errors != 1 and "s" or "")))
  485. self.stream.write("FAILED (%s)\n" % ', '.join(details))
  486. elif details:
  487. self.stream.write("OK (%s)\n" % ', '.join(details))
  488. else:
  489. self.stream.write("OK\n")
  490. return result
  491. #---- internal support stuff
  492. # Recipe: indent (0.2.1)
  493. def _indent(s, width=4, skip_first_line=False):
  494. """_indent(s, [width=4]) -> 's' indented by 'width' spaces
  495. The optional "skip_first_line" argument is a boolean (default False)
  496. indicating if the first line should NOT be indented.
  497. """
  498. lines = s.splitlines(1)
  499. indentstr = ' '*width
  500. if skip_first_line:
  501. return indentstr.join(lines)
  502. else:
  503. return indentstr + indentstr.join(lines)
  504. #---- mainline
  505. #TODO: pass in add_help_option=False and add it ourself here.
  506. ## Optparse's handling of the doc passed in for -h|--help handling is
  507. ## abysmal. Hence we'll stick with getopt.
  508. #def _parse_opts(args):
  509. # """_parse_opts(args) -> (options, tags)"""
  510. # usage = "usage: %prog [OPTIONS...] [TAGS...]"
  511. # parser = optparse.OptionParser(prog="test", usage=usage,
  512. # description=__doc__)
  513. # parser.add_option("-v", "--verbose", dest="log_level",
  514. # action="store_const", const=logging.DEBUG,
  515. # help="more verbose output")
  516. # parser.add_option("-q", "--quiet", dest="log_level",
  517. # action="store_const", const=logging.WARNING,
  518. # help="quieter output")
  519. # parser.add_option("-l", "--list", dest="action",
  520. # action="store_const", const="list",
  521. # help="list available tests")
  522. # parser.set_defaults(log_level=logging.INFO, action="test")
  523. # opts, raw_tags = parser.parse_args()
  524. #
  525. # # Trim '.py' from user-supplied tags. They might have gotten there
  526. # # via shell expansion.
  527. # ...
  528. #
  529. # return opts, raw_tags
  530. def _parse_opts(args):
  531. """_parse_opts(args) -> (log_level, action, tags)"""
  532. opts, raw_tags = getopt.getopt(args, "hvqdlL:",
  533. ["help", "verbose", "quiet", "debug", "list"])
  534. log_level = logging.WARN
  535. action = "test"
  536. for opt, optarg in opts:
  537. if opt in ("-h", "--help"):
  538. action = "help"
  539. elif opt in ("-v", "--verbose"):
  540. log_level = logging.INFO
  541. elif opt in ("-q", "--quiet"):
  542. log_level = logging.ERROR
  543. elif opt in ("-d", "--debug"):
  544. log_level = logging.DEBUG
  545. elif opt in ("-l", "--list"):
  546. action = "list"
  547. elif opt == "-L":
  548. # Optarg is of the form '<logname>:<levelname>', e.g.
  549. # "codeintel:DEBUG", "codeintel.db:INFO".
  550. lname, llevelname = optarg.split(':', 1)
  551. llevel = getattr(logging, llevelname)
  552. logging.getLogger(lname).setLevel(llevel)
  553. # Clean up the given tags.
  554. tags = []
  555. for raw_tag in raw_tags:
  556. if splitext(raw_tag)[1] in (".py", ".pyc", ".pyo", ".pyw") \
  557. and exists(raw_tag):
  558. # Trim '.py' from user-supplied tags if it looks to be from
  559. # shell expansion.
  560. tags.append(splitext(raw_tag)[0])
  561. elif '/' in raw_tag:
  562. # Split one '/' to allow the shortname from the test listing
  563. # to be used as a filter.
  564. tags += raw_tag.split('/')
  565. else:
  566. tags.append(raw_tag)
  567. return log_level, action, tags
  568. def harness(testdir_from_ns={None: os.curdir}, argv=sys.argv,
  569. setup_func=None):
  570. """Convenience mainline for a test harness "test.py" script.
  571. "testdir_from_ns" (optional) is basically a set of directories in
  572. which to look for test cases. It is a dict with:
  573. <namespace>: <testdir>
  574. where <namespace> is a (short) string that becomes part of the
  575. included test names and an implicit tag for filtering those
  576. tests. By default the current dir is use with an empty namespace:
  577. {None: os.curdir}
  578. "setup_func" (optional) is a callable that will be called once
  579. before any tests are run to prepare for the test suite. It
  580. is not called if no tests will be run.
  581. Typically, if you have a number of test_*.py modules you can create
  582. a test harness, "test.py", for them that looks like this:
  583. #!/usr/bin/env python
  584. if __name__ == "__main__":
  585. retval = testlib.harness()
  586. sys.exit(retval)
  587. """
  588. logging.basicConfig()
  589. try:
  590. log_level, action, tags = _parse_opts(argv[1:])
  591. except getopt.error, ex:
  592. log.error(str(ex) + " (did you need a '--' before a '-TAG' argument?)")
  593. return 1
  594. log.setLevel(log_level)
  595. if action == "help":
  596. print __doc__
  597. return 0
  598. if action == "list":
  599. return list_tests(testdir_from_ns, tags)
  600. elif action == "test":
  601. result = test(testdir_from_ns, tags, setup_func=setup_func)
  602. if result is None:
  603. return None
  604. return len(result.errors) + len(result.failures)
  605. else:
  606. raise TestError("unexpected action/mode: '%s'" % action)