runner.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798
  1. import ctypes
  2. import itertools
  3. import logging
  4. import multiprocessing
  5. import os
  6. import pickle
  7. import textwrap
  8. import unittest
  9. from importlib import import_module
  10. from io import StringIO
  11. from django.core.management import call_command
  12. from django.db import connections
  13. from django.test import SimpleTestCase, TestCase
  14. from django.test.utils import (
  15. setup_databases as _setup_databases, setup_test_environment,
  16. teardown_databases as _teardown_databases, teardown_test_environment,
  17. )
  18. from django.utils.datastructures import OrderedSet
  19. from django.utils.version import PY37
  20. try:
  21. import ipdb as pdb
  22. except ImportError:
  23. import pdb
  24. try:
  25. import tblib.pickling_support
  26. except ImportError:
  27. tblib = None
  28. class DebugSQLTextTestResult(unittest.TextTestResult):
  29. def __init__(self, stream, descriptions, verbosity):
  30. self.logger = logging.getLogger('django.db.backends')
  31. self.logger.setLevel(logging.DEBUG)
  32. super().__init__(stream, descriptions, verbosity)
  33. def startTest(self, test):
  34. self.debug_sql_stream = StringIO()
  35. self.handler = logging.StreamHandler(self.debug_sql_stream)
  36. self.logger.addHandler(self.handler)
  37. super().startTest(test)
  38. def stopTest(self, test):
  39. super().stopTest(test)
  40. self.logger.removeHandler(self.handler)
  41. if self.showAll:
  42. self.debug_sql_stream.seek(0)
  43. self.stream.write(self.debug_sql_stream.read())
  44. self.stream.writeln(self.separator2)
  45. def addError(self, test, err):
  46. super().addError(test, err)
  47. self.debug_sql_stream.seek(0)
  48. self.errors[-1] = self.errors[-1] + (self.debug_sql_stream.read(),)
  49. def addFailure(self, test, err):
  50. super().addFailure(test, err)
  51. self.debug_sql_stream.seek(0)
  52. self.failures[-1] = self.failures[-1] + (self.debug_sql_stream.read(),)
  53. def addSubTest(self, test, subtest, err):
  54. super().addSubTest(test, subtest, err)
  55. if err is not None:
  56. self.debug_sql_stream.seek(0)
  57. errors = self.failures if issubclass(err[0], test.failureException) else self.errors
  58. errors[-1] = errors[-1] + (self.debug_sql_stream.read(),)
  59. def printErrorList(self, flavour, errors):
  60. for test, err, sql_debug in errors:
  61. self.stream.writeln(self.separator1)
  62. self.stream.writeln("%s: %s" % (flavour, self.getDescription(test)))
  63. self.stream.writeln(self.separator2)
  64. self.stream.writeln(err)
  65. self.stream.writeln(self.separator2)
  66. self.stream.writeln(sql_debug)
  67. class PDBDebugResult(unittest.TextTestResult):
  68. """
  69. Custom result class that triggers a PDB session when an error or failure
  70. occurs.
  71. """
  72. def addError(self, test, err):
  73. super().addError(test, err)
  74. self.debug(err)
  75. def addFailure(self, test, err):
  76. super().addFailure(test, err)
  77. self.debug(err)
  78. def debug(self, error):
  79. exc_type, exc_value, traceback = error
  80. print("\nOpening PDB: %r" % exc_value)
  81. pdb.post_mortem(traceback)
  82. class RemoteTestResult:
  83. """
  84. Record information about which tests have succeeded and which have failed.
  85. The sole purpose of this class is to record events in the child processes
  86. so they can be replayed in the master process. As a consequence it doesn't
  87. inherit unittest.TestResult and doesn't attempt to implement all its API.
  88. The implementation matches the unpythonic coding style of unittest2.
  89. """
  90. def __init__(self):
  91. if tblib is not None:
  92. tblib.pickling_support.install()
  93. self.events = []
  94. self.failfast = False
  95. self.shouldStop = False
  96. self.testsRun = 0
  97. @property
  98. def test_index(self):
  99. return self.testsRun - 1
  100. def _confirm_picklable(self, obj):
  101. """
  102. Confirm that obj can be pickled and unpickled as multiprocessing will
  103. need to pickle the exception in the child process and unpickle it in
  104. the parent process. Let the exception rise, if not.
  105. """
  106. pickle.loads(pickle.dumps(obj))
  107. def _print_unpicklable_subtest(self, test, subtest, pickle_exc):
  108. print("""
  109. Subtest failed:
  110. test: {}
  111. subtest: {}
  112. Unfortunately, the subtest that failed cannot be pickled, so the parallel
  113. test runner cannot handle it cleanly. Here is the pickling error:
  114. > {}
  115. You should re-run this test with --parallel=1 to reproduce the failure
  116. with a cleaner failure message.
  117. """.format(test, subtest, pickle_exc))
  118. def check_picklable(self, test, err):
  119. # Ensure that sys.exc_info() tuples are picklable. This displays a
  120. # clear multiprocessing.pool.RemoteTraceback generated in the child
  121. # process instead of a multiprocessing.pool.MaybeEncodingError, making
  122. # the root cause easier to figure out for users who aren't familiar
  123. # with the multiprocessing module. Since we're in a forked process,
  124. # our best chance to communicate with them is to print to stdout.
  125. try:
  126. self._confirm_picklable(err)
  127. except Exception as exc:
  128. original_exc_txt = repr(err[1])
  129. original_exc_txt = textwrap.fill(original_exc_txt, 75, initial_indent=' ', subsequent_indent=' ')
  130. pickle_exc_txt = repr(exc)
  131. pickle_exc_txt = textwrap.fill(pickle_exc_txt, 75, initial_indent=' ', subsequent_indent=' ')
  132. if tblib is None:
  133. print("""
  134. {} failed:
  135. {}
  136. Unfortunately, tracebacks cannot be pickled, making it impossible for the
  137. parallel test runner to handle this exception cleanly.
  138. In order to see the traceback, you should install tblib:
  139. python -m pip install tblib
  140. """.format(test, original_exc_txt))
  141. else:
  142. print("""
  143. {} failed:
  144. {}
  145. Unfortunately, the exception it raised cannot be pickled, making it impossible
  146. for the parallel test runner to handle it cleanly.
  147. Here's the error encountered while trying to pickle the exception:
  148. {}
  149. You should re-run this test with the --parallel=1 option to reproduce the
  150. failure and get a correct traceback.
  151. """.format(test, original_exc_txt, pickle_exc_txt))
  152. raise
  153. def check_subtest_picklable(self, test, subtest):
  154. try:
  155. self._confirm_picklable(subtest)
  156. except Exception as exc:
  157. self._print_unpicklable_subtest(test, subtest, exc)
  158. raise
  159. def stop_if_failfast(self):
  160. if self.failfast:
  161. self.stop()
  162. def stop(self):
  163. self.shouldStop = True
  164. def startTestRun(self):
  165. self.events.append(('startTestRun',))
  166. def stopTestRun(self):
  167. self.events.append(('stopTestRun',))
  168. def startTest(self, test):
  169. self.testsRun += 1
  170. self.events.append(('startTest', self.test_index))
  171. def stopTest(self, test):
  172. self.events.append(('stopTest', self.test_index))
  173. def addError(self, test, err):
  174. self.check_picklable(test, err)
  175. self.events.append(('addError', self.test_index, err))
  176. self.stop_if_failfast()
  177. def addFailure(self, test, err):
  178. self.check_picklable(test, err)
  179. self.events.append(('addFailure', self.test_index, err))
  180. self.stop_if_failfast()
  181. def addSubTest(self, test, subtest, err):
  182. # Follow Python 3.5's implementation of unittest.TestResult.addSubTest()
  183. # by not doing anything when a subtest is successful.
  184. if err is not None:
  185. # Call check_picklable() before check_subtest_picklable() since
  186. # check_picklable() performs the tblib check.
  187. self.check_picklable(test, err)
  188. self.check_subtest_picklable(test, subtest)
  189. self.events.append(('addSubTest', self.test_index, subtest, err))
  190. self.stop_if_failfast()
  191. def addSuccess(self, test):
  192. self.events.append(('addSuccess', self.test_index))
  193. def addSkip(self, test, reason):
  194. self.events.append(('addSkip', self.test_index, reason))
  195. def addExpectedFailure(self, test, err):
  196. # If tblib isn't installed, pickling the traceback will always fail.
  197. # However we don't want tblib to be required for running the tests
  198. # when they pass or fail as expected. Drop the traceback when an
  199. # expected failure occurs.
  200. if tblib is None:
  201. err = err[0], err[1], None
  202. self.check_picklable(test, err)
  203. self.events.append(('addExpectedFailure', self.test_index, err))
  204. def addUnexpectedSuccess(self, test):
  205. self.events.append(('addUnexpectedSuccess', self.test_index))
  206. self.stop_if_failfast()
  207. class RemoteTestRunner:
  208. """
  209. Run tests and record everything but don't display anything.
  210. The implementation matches the unpythonic coding style of unittest2.
  211. """
  212. resultclass = RemoteTestResult
  213. def __init__(self, failfast=False, resultclass=None):
  214. self.failfast = failfast
  215. if resultclass is not None:
  216. self.resultclass = resultclass
  217. def run(self, test):
  218. result = self.resultclass()
  219. unittest.registerResult(result)
  220. result.failfast = self.failfast
  221. test(result)
  222. return result
  223. def default_test_processes():
  224. """Default number of test processes when using the --parallel option."""
  225. # The current implementation of the parallel test runner requires
  226. # multiprocessing to start subprocesses with fork().
  227. if multiprocessing.get_start_method() != 'fork':
  228. return 1
  229. try:
  230. return int(os.environ['DJANGO_TEST_PROCESSES'])
  231. except KeyError:
  232. return multiprocessing.cpu_count()
  233. _worker_id = 0
  234. def _init_worker(counter):
  235. """
  236. Switch to databases dedicated to this worker.
  237. This helper lives at module-level because of the multiprocessing module's
  238. requirements.
  239. """
  240. global _worker_id
  241. with counter.get_lock():
  242. counter.value += 1
  243. _worker_id = counter.value
  244. for alias in connections:
  245. connection = connections[alias]
  246. settings_dict = connection.creation.get_test_db_clone_settings(str(_worker_id))
  247. # connection.settings_dict must be updated in place for changes to be
  248. # reflected in django.db.connections. If the following line assigned
  249. # connection.settings_dict = settings_dict, new threads would connect
  250. # to the default database instead of the appropriate clone.
  251. connection.settings_dict.update(settings_dict)
  252. connection.close()
  253. def _run_subsuite(args):
  254. """
  255. Run a suite of tests with a RemoteTestRunner and return a RemoteTestResult.
  256. This helper lives at module-level and its arguments are wrapped in a tuple
  257. because of the multiprocessing module's requirements.
  258. """
  259. runner_class, subsuite_index, subsuite, failfast = args
  260. runner = runner_class(failfast=failfast)
  261. result = runner.run(subsuite)
  262. return subsuite_index, result.events
  263. class ParallelTestSuite(unittest.TestSuite):
  264. """
  265. Run a series of tests in parallel in several processes.
  266. While the unittest module's documentation implies that orchestrating the
  267. execution of tests is the responsibility of the test runner, in practice,
  268. it appears that TestRunner classes are more concerned with formatting and
  269. displaying test results.
  270. Since there are fewer use cases for customizing TestSuite than TestRunner,
  271. implementing parallelization at the level of the TestSuite improves
  272. interoperability with existing custom test runners. A single instance of a
  273. test runner can still collect results from all tests without being aware
  274. that they have been run in parallel.
  275. """
  276. # In case someone wants to modify these in a subclass.
  277. init_worker = _init_worker
  278. run_subsuite = _run_subsuite
  279. runner_class = RemoteTestRunner
  280. def __init__(self, suite, processes, failfast=False):
  281. self.subsuites = partition_suite_by_case(suite)
  282. self.processes = processes
  283. self.failfast = failfast
  284. super().__init__()
  285. def run(self, result):
  286. """
  287. Distribute test cases across workers.
  288. Return an identifier of each test case with its result in order to use
  289. imap_unordered to show results as soon as they're available.
  290. To minimize pickling errors when getting results from workers:
  291. - pass back numeric indexes in self.subsuites instead of tests
  292. - make tracebacks picklable with tblib, if available
  293. Even with tblib, errors may still occur for dynamically created
  294. exception classes which cannot be unpickled.
  295. """
  296. counter = multiprocessing.Value(ctypes.c_int, 0)
  297. pool = multiprocessing.Pool(
  298. processes=self.processes,
  299. initializer=self.init_worker.__func__,
  300. initargs=[counter],
  301. )
  302. args = [
  303. (self.runner_class, index, subsuite, self.failfast)
  304. for index, subsuite in enumerate(self.subsuites)
  305. ]
  306. test_results = pool.imap_unordered(self.run_subsuite.__func__, args)
  307. while True:
  308. if result.shouldStop:
  309. pool.terminate()
  310. break
  311. try:
  312. subsuite_index, events = test_results.next(timeout=0.1)
  313. except multiprocessing.TimeoutError:
  314. continue
  315. except StopIteration:
  316. pool.close()
  317. break
  318. tests = list(self.subsuites[subsuite_index])
  319. for event in events:
  320. event_name = event[0]
  321. handler = getattr(result, event_name, None)
  322. if handler is None:
  323. continue
  324. test = tests[event[1]]
  325. args = event[2:]
  326. handler(test, *args)
  327. pool.join()
  328. return result
  329. def __iter__(self):
  330. return iter(self.subsuites)
  331. class DiscoverRunner:
  332. """A Django test runner that uses unittest2 test discovery."""
  333. test_suite = unittest.TestSuite
  334. parallel_test_suite = ParallelTestSuite
  335. test_runner = unittest.TextTestRunner
  336. test_loader = unittest.defaultTestLoader
  337. reorder_by = (TestCase, SimpleTestCase)
  338. def __init__(self, pattern=None, top_level=None, verbosity=1,
  339. interactive=True, failfast=False, keepdb=False,
  340. reverse=False, debug_mode=False, debug_sql=False, parallel=0,
  341. tags=None, exclude_tags=None, test_name_patterns=None,
  342. pdb=False, **kwargs):
  343. self.pattern = pattern
  344. self.top_level = top_level
  345. self.verbosity = verbosity
  346. self.interactive = interactive
  347. self.failfast = failfast
  348. self.keepdb = keepdb
  349. self.reverse = reverse
  350. self.debug_mode = debug_mode
  351. self.debug_sql = debug_sql
  352. self.parallel = parallel
  353. self.tags = set(tags or [])
  354. self.exclude_tags = set(exclude_tags or [])
  355. self.pdb = pdb
  356. if self.pdb and self.parallel > 1:
  357. raise ValueError('You cannot use --pdb with parallel tests; pass --parallel=1 to use it.')
  358. self.test_name_patterns = None
  359. if test_name_patterns:
  360. # unittest does not export the _convert_select_pattern function
  361. # that converts command-line arguments to patterns.
  362. self.test_name_patterns = {
  363. pattern if '*' in pattern else '*%s*' % pattern
  364. for pattern in test_name_patterns
  365. }
  366. @classmethod
  367. def add_arguments(cls, parser):
  368. parser.add_argument(
  369. '-t', '--top-level-directory', dest='top_level',
  370. help='Top level of project for unittest discovery.',
  371. )
  372. parser.add_argument(
  373. '-p', '--pattern', default="test*.py",
  374. help='The test matching pattern. Defaults to test*.py.',
  375. )
  376. parser.add_argument(
  377. '--keepdb', action='store_true',
  378. help='Preserves the test DB between runs.'
  379. )
  380. parser.add_argument(
  381. '-r', '--reverse', action='store_true',
  382. help='Reverses test cases order.',
  383. )
  384. parser.add_argument(
  385. '--debug-mode', action='store_true',
  386. help='Sets settings.DEBUG to True.',
  387. )
  388. parser.add_argument(
  389. '-d', '--debug-sql', action='store_true',
  390. help='Prints logged SQL queries on failure.',
  391. )
  392. parser.add_argument(
  393. '--parallel', nargs='?', default=1, type=int,
  394. const=default_test_processes(), metavar='N',
  395. help='Run tests using up to N parallel processes.',
  396. )
  397. parser.add_argument(
  398. '--tag', action='append', dest='tags',
  399. help='Run only tests with the specified tag. Can be used multiple times.',
  400. )
  401. parser.add_argument(
  402. '--exclude-tag', action='append', dest='exclude_tags',
  403. help='Do not run tests with the specified tag. Can be used multiple times.',
  404. )
  405. parser.add_argument(
  406. '--pdb', action='store_true',
  407. help='Runs a debugger (pdb, or ipdb if installed) on error or failure.'
  408. )
  409. if PY37:
  410. parser.add_argument(
  411. '-k', action='append', dest='test_name_patterns',
  412. help=(
  413. 'Only run test methods and classes that match the pattern '
  414. 'or substring. Can be used multiple times. Same as '
  415. 'unittest -k option.'
  416. ),
  417. )
  418. def setup_test_environment(self, **kwargs):
  419. setup_test_environment(debug=self.debug_mode)
  420. unittest.installHandler()
  421. def build_suite(self, test_labels=None, extra_tests=None, **kwargs):
  422. suite = self.test_suite()
  423. test_labels = test_labels or ['.']
  424. extra_tests = extra_tests or []
  425. self.test_loader.testNamePatterns = self.test_name_patterns
  426. discover_kwargs = {}
  427. if self.pattern is not None:
  428. discover_kwargs['pattern'] = self.pattern
  429. if self.top_level is not None:
  430. discover_kwargs['top_level_dir'] = self.top_level
  431. for label in test_labels:
  432. kwargs = discover_kwargs.copy()
  433. tests = None
  434. label_as_path = os.path.abspath(label)
  435. # if a module, or "module.ClassName[.method_name]", just run those
  436. if not os.path.exists(label_as_path):
  437. tests = self.test_loader.loadTestsFromName(label)
  438. elif os.path.isdir(label_as_path) and not self.top_level:
  439. # Try to be a bit smarter than unittest about finding the
  440. # default top-level for a given directory path, to avoid
  441. # breaking relative imports. (Unittest's default is to set
  442. # top-level equal to the path, which means relative imports
  443. # will result in "Attempted relative import in non-package.").
  444. # We'd be happy to skip this and require dotted module paths
  445. # (which don't cause this problem) instead of file paths (which
  446. # do), but in the case of a directory in the cwd, which would
  447. # be equally valid if considered as a top-level module or as a
  448. # directory path, unittest unfortunately prefers the latter.
  449. top_level = label_as_path
  450. while True:
  451. init_py = os.path.join(top_level, '__init__.py')
  452. if os.path.exists(init_py):
  453. try_next = os.path.dirname(top_level)
  454. if try_next == top_level:
  455. # __init__.py all the way down? give up.
  456. break
  457. top_level = try_next
  458. continue
  459. break
  460. kwargs['top_level_dir'] = top_level
  461. if not (tests and tests.countTestCases()) and is_discoverable(label):
  462. # Try discovery if path is a package or directory
  463. tests = self.test_loader.discover(start_dir=label, **kwargs)
  464. # Make unittest forget the top-level dir it calculated from this
  465. # run, to support running tests from two different top-levels.
  466. self.test_loader._top_level_dir = None
  467. suite.addTests(tests)
  468. for test in extra_tests:
  469. suite.addTest(test)
  470. if self.tags or self.exclude_tags:
  471. if self.verbosity >= 2:
  472. if self.tags:
  473. print('Including test tag(s): %s.' % ', '.join(sorted(self.tags)))
  474. if self.exclude_tags:
  475. print('Excluding test tag(s): %s.' % ', '.join(sorted(self.exclude_tags)))
  476. suite = filter_tests_by_tags(suite, self.tags, self.exclude_tags)
  477. suite = reorder_suite(suite, self.reorder_by, self.reverse)
  478. if self.parallel > 1:
  479. parallel_suite = self.parallel_test_suite(suite, self.parallel, self.failfast)
  480. # Since tests are distributed across processes on a per-TestCase
  481. # basis, there's no need for more processes than TestCases.
  482. parallel_units = len(parallel_suite.subsuites)
  483. self.parallel = min(self.parallel, parallel_units)
  484. # If there's only one TestCase, parallelization isn't needed.
  485. if self.parallel > 1:
  486. suite = parallel_suite
  487. return suite
  488. def setup_databases(self, **kwargs):
  489. return _setup_databases(
  490. self.verbosity, self.interactive, self.keepdb, self.debug_sql,
  491. self.parallel, **kwargs
  492. )
  493. def get_resultclass(self):
  494. if self.debug_sql:
  495. return DebugSQLTextTestResult
  496. elif self.pdb:
  497. return PDBDebugResult
  498. def get_test_runner_kwargs(self):
  499. return {
  500. 'failfast': self.failfast,
  501. 'resultclass': self.get_resultclass(),
  502. 'verbosity': self.verbosity,
  503. }
  504. def run_checks(self):
  505. # Checks are run after database creation since some checks require
  506. # database access.
  507. call_command('check', verbosity=self.verbosity)
  508. def run_suite(self, suite, **kwargs):
  509. kwargs = self.get_test_runner_kwargs()
  510. runner = self.test_runner(**kwargs)
  511. return runner.run(suite)
  512. def teardown_databases(self, old_config, **kwargs):
  513. """Destroy all the non-mirror databases."""
  514. _teardown_databases(
  515. old_config,
  516. verbosity=self.verbosity,
  517. parallel=self.parallel,
  518. keepdb=self.keepdb,
  519. )
  520. def teardown_test_environment(self, **kwargs):
  521. unittest.removeHandler()
  522. teardown_test_environment()
  523. def suite_result(self, suite, result, **kwargs):
  524. return len(result.failures) + len(result.errors)
  525. def _get_databases(self, suite):
  526. databases = set()
  527. for test in suite:
  528. if isinstance(test, unittest.TestCase):
  529. test_databases = getattr(test, 'databases', None)
  530. if test_databases == '__all__':
  531. return set(connections)
  532. if test_databases:
  533. databases.update(test_databases)
  534. else:
  535. databases.update(self._get_databases(test))
  536. return databases
  537. def get_databases(self, suite):
  538. databases = self._get_databases(suite)
  539. if self.verbosity >= 2:
  540. unused_databases = [alias for alias in connections if alias not in databases]
  541. if unused_databases:
  542. print('Skipping setup of unused database(s): %s.' % ', '.join(sorted(unused_databases)))
  543. return databases
  544. def run_tests(self, test_labels, extra_tests=None, **kwargs):
  545. """
  546. Run the unit tests for all the test labels in the provided list.
  547. Test labels should be dotted Python paths to test modules, test
  548. classes, or test methods.
  549. A list of 'extra' tests may also be provided; these tests
  550. will be added to the test suite.
  551. Return the number of tests that failed.
  552. """
  553. self.setup_test_environment()
  554. suite = self.build_suite(test_labels, extra_tests)
  555. databases = self.get_databases(suite)
  556. old_config = self.setup_databases(aliases=databases)
  557. run_failed = False
  558. try:
  559. self.run_checks()
  560. result = self.run_suite(suite)
  561. except Exception:
  562. run_failed = True
  563. raise
  564. finally:
  565. try:
  566. self.teardown_databases(old_config)
  567. self.teardown_test_environment()
  568. except Exception:
  569. # Silence teardown exceptions if an exception was raised during
  570. # runs to avoid shadowing it.
  571. if not run_failed:
  572. raise
  573. return self.suite_result(suite, result)
  574. def is_discoverable(label):
  575. """
  576. Check if a test label points to a Python package or file directory.
  577. Relative labels like "." and ".." are seen as directories.
  578. """
  579. try:
  580. mod = import_module(label)
  581. except (ImportError, TypeError):
  582. pass
  583. else:
  584. return hasattr(mod, '__path__')
  585. return os.path.isdir(os.path.abspath(label))
  586. def reorder_suite(suite, classes, reverse=False):
  587. """
  588. Reorder a test suite by test type.
  589. `classes` is a sequence of types
  590. All tests of type classes[0] are placed first, then tests of type
  591. classes[1], etc. Tests with no match in classes are placed last.
  592. If `reverse` is True, sort tests within classes in opposite order but
  593. don't reverse test classes.
  594. """
  595. class_count = len(classes)
  596. suite_class = type(suite)
  597. bins = [OrderedSet() for i in range(class_count + 1)]
  598. partition_suite_by_type(suite, classes, bins, reverse=reverse)
  599. reordered_suite = suite_class()
  600. for i in range(class_count + 1):
  601. reordered_suite.addTests(bins[i])
  602. return reordered_suite
  603. def partition_suite_by_type(suite, classes, bins, reverse=False):
  604. """
  605. Partition a test suite by test type. Also prevent duplicated tests.
  606. classes is a sequence of types
  607. bins is a sequence of TestSuites, one more than classes
  608. reverse changes the ordering of tests within bins
  609. Tests of type classes[i] are added to bins[i],
  610. tests with no match found in classes are place in bins[-1]
  611. """
  612. suite_class = type(suite)
  613. if reverse:
  614. suite = reversed(tuple(suite))
  615. for test in suite:
  616. if isinstance(test, suite_class):
  617. partition_suite_by_type(test, classes, bins, reverse=reverse)
  618. else:
  619. for i in range(len(classes)):
  620. if isinstance(test, classes[i]):
  621. bins[i].add(test)
  622. break
  623. else:
  624. bins[-1].add(test)
  625. def partition_suite_by_case(suite):
  626. """Partition a test suite by test case, preserving the order of tests."""
  627. groups = []
  628. suite_class = type(suite)
  629. for test_type, test_group in itertools.groupby(suite, type):
  630. if issubclass(test_type, unittest.TestCase):
  631. groups.append(suite_class(test_group))
  632. else:
  633. for item in test_group:
  634. groups.extend(partition_suite_by_case(item))
  635. return groups
  636. def filter_tests_by_tags(suite, tags, exclude_tags):
  637. suite_class = type(suite)
  638. filtered_suite = suite_class()
  639. for test in suite:
  640. if isinstance(test, suite_class):
  641. filtered_suite.addTests(filter_tests_by_tags(test, tags, exclude_tags))
  642. else:
  643. test_tags = set(getattr(test, 'tags', set()))
  644. test_fn_name = getattr(test, '_testMethodName', str(test))
  645. test_fn = getattr(test, test_fn_name, test)
  646. test_fn_tags = set(getattr(test_fn, 'tags', set()))
  647. all_tags = test_tags.union(test_fn_tags)
  648. matched_tags = all_tags.intersection(tags)
  649. if (matched_tags or not tags) and not all_tags.intersection(exclude_tags):
  650. filtered_suite.addTest(test)
  651. return filtered_suite