runner.py 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224
  1. import argparse
  2. import ctypes
  3. import faulthandler
  4. import io
  5. import itertools
  6. import logging
  7. import multiprocessing
  8. import os
  9. import pickle
  10. import random
  11. import sys
  12. import textwrap
  13. import unittest
  14. import warnings
  15. from collections import defaultdict
  16. from contextlib import contextmanager
  17. from importlib import import_module
  18. from io import StringIO
  19. import sqlparse
  20. import django
  21. from django.core.management import call_command
  22. from django.db import connections
  23. from django.test import SimpleTestCase, TestCase
  24. from django.test.utils import NullTimeKeeper, TimeKeeper, iter_test_cases
  25. from django.test.utils import setup_databases as _setup_databases
  26. from django.test.utils import setup_test_environment
  27. from django.test.utils import teardown_databases as _teardown_databases
  28. from django.test.utils import teardown_test_environment
  29. from django.utils.crypto import new_hash
  30. from django.utils.datastructures import OrderedSet
  31. from django.utils.deprecation import RemovedInDjango50Warning
  32. try:
  33. import ipdb as pdb
  34. except ImportError:
  35. import pdb
  36. try:
  37. import tblib.pickling_support
  38. except ImportError:
  39. tblib = None
  40. class DebugSQLTextTestResult(unittest.TextTestResult):
  41. def __init__(self, stream, descriptions, verbosity):
  42. self.logger = logging.getLogger("django.db.backends")
  43. self.logger.setLevel(logging.DEBUG)
  44. self.debug_sql_stream = None
  45. super().__init__(stream, descriptions, verbosity)
  46. def startTest(self, test):
  47. self.debug_sql_stream = StringIO()
  48. self.handler = logging.StreamHandler(self.debug_sql_stream)
  49. self.logger.addHandler(self.handler)
  50. super().startTest(test)
  51. def stopTest(self, test):
  52. super().stopTest(test)
  53. self.logger.removeHandler(self.handler)
  54. if self.showAll:
  55. self.debug_sql_stream.seek(0)
  56. self.stream.write(self.debug_sql_stream.read())
  57. self.stream.writeln(self.separator2)
  58. def addError(self, test, err):
  59. super().addError(test, err)
  60. if self.debug_sql_stream is None:
  61. # Error before tests e.g. in setUpTestData().
  62. sql = ""
  63. else:
  64. self.debug_sql_stream.seek(0)
  65. sql = self.debug_sql_stream.read()
  66. self.errors[-1] = self.errors[-1] + (sql,)
  67. def addFailure(self, test, err):
  68. super().addFailure(test, err)
  69. self.debug_sql_stream.seek(0)
  70. self.failures[-1] = self.failures[-1] + (self.debug_sql_stream.read(),)
  71. def addSubTest(self, test, subtest, err):
  72. super().addSubTest(test, subtest, err)
  73. if err is not None:
  74. self.debug_sql_stream.seek(0)
  75. errors = (
  76. self.failures
  77. if issubclass(err[0], test.failureException)
  78. else self.errors
  79. )
  80. errors[-1] = errors[-1] + (self.debug_sql_stream.read(),)
  81. def printErrorList(self, flavour, errors):
  82. for test, err, sql_debug in errors:
  83. self.stream.writeln(self.separator1)
  84. self.stream.writeln("%s: %s" % (flavour, self.getDescription(test)))
  85. self.stream.writeln(self.separator2)
  86. self.stream.writeln(err)
  87. self.stream.writeln(self.separator2)
  88. self.stream.writeln(
  89. sqlparse.format(sql_debug, reindent=True, keyword_case="upper")
  90. )
  91. class PDBDebugResult(unittest.TextTestResult):
  92. """
  93. Custom result class that triggers a PDB session when an error or failure
  94. occurs.
  95. """
  96. def addError(self, test, err):
  97. super().addError(test, err)
  98. self.debug(err)
  99. def addFailure(self, test, err):
  100. super().addFailure(test, err)
  101. self.debug(err)
  102. def addSubTest(self, test, subtest, err):
  103. if err is not None:
  104. self.debug(err)
  105. super().addSubTest(test, subtest, err)
  106. def debug(self, error):
  107. self._restoreStdout()
  108. self.buffer = False
  109. exc_type, exc_value, traceback = error
  110. print("\nOpening PDB: %r" % exc_value)
  111. pdb.post_mortem(traceback)
  112. class DummyList:
  113. """
  114. Dummy list class for faking storage of results in unittest.TestResult.
  115. """
  116. __slots__ = ()
  117. def append(self, item):
  118. pass
  119. class RemoteTestResult(unittest.TestResult):
  120. """
  121. Extend unittest.TestResult to record events in the child processes so they
  122. can be replayed in the parent process. Events include things like which
  123. tests succeeded or failed.
  124. """
  125. def __init__(self, *args, **kwargs):
  126. super().__init__(*args, **kwargs)
  127. # Fake storage of results to reduce memory usage. These are used by the
  128. # unittest default methods, but here 'events' is used instead.
  129. dummy_list = DummyList()
  130. self.failures = dummy_list
  131. self.errors = dummy_list
  132. self.skipped = dummy_list
  133. self.expectedFailures = dummy_list
  134. self.unexpectedSuccesses = dummy_list
  135. if tblib is not None:
  136. tblib.pickling_support.install()
  137. self.events = []
  138. def __getstate__(self):
  139. # Make this class picklable by removing the file-like buffer
  140. # attributes. This is possible since they aren't used after unpickling
  141. # after being sent to ParallelTestSuite.
  142. state = self.__dict__.copy()
  143. state.pop("_stdout_buffer", None)
  144. state.pop("_stderr_buffer", None)
  145. state.pop("_original_stdout", None)
  146. state.pop("_original_stderr", None)
  147. return state
  148. @property
  149. def test_index(self):
  150. return self.testsRun - 1
  151. def _confirm_picklable(self, obj):
  152. """
  153. Confirm that obj can be pickled and unpickled as multiprocessing will
  154. need to pickle the exception in the child process and unpickle it in
  155. the parent process. Let the exception rise, if not.
  156. """
  157. pickle.loads(pickle.dumps(obj))
  158. def _print_unpicklable_subtest(self, test, subtest, pickle_exc):
  159. print(
  160. """
  161. Subtest failed:
  162. test: {}
  163. subtest: {}
  164. Unfortunately, the subtest that failed cannot be pickled, so the parallel
  165. test runner cannot handle it cleanly. Here is the pickling error:
  166. > {}
  167. You should re-run this test with --parallel=1 to reproduce the failure
  168. with a cleaner failure message.
  169. """.format(
  170. test, subtest, pickle_exc
  171. )
  172. )
  173. def check_picklable(self, test, err):
  174. # Ensure that sys.exc_info() tuples are picklable. This displays a
  175. # clear multiprocessing.pool.RemoteTraceback generated in the child
  176. # process instead of a multiprocessing.pool.MaybeEncodingError, making
  177. # the root cause easier to figure out for users who aren't familiar
  178. # with the multiprocessing module. Since we're in a forked process,
  179. # our best chance to communicate with them is to print to stdout.
  180. try:
  181. self._confirm_picklable(err)
  182. except Exception as exc:
  183. original_exc_txt = repr(err[1])
  184. original_exc_txt = textwrap.fill(
  185. original_exc_txt, 75, initial_indent=" ", subsequent_indent=" "
  186. )
  187. pickle_exc_txt = repr(exc)
  188. pickle_exc_txt = textwrap.fill(
  189. pickle_exc_txt, 75, initial_indent=" ", subsequent_indent=" "
  190. )
  191. if tblib is None:
  192. print(
  193. """
  194. {} failed:
  195. {}
  196. Unfortunately, tracebacks cannot be pickled, making it impossible for the
  197. parallel test runner to handle this exception cleanly.
  198. In order to see the traceback, you should install tblib:
  199. python -m pip install tblib
  200. """.format(
  201. test, original_exc_txt
  202. )
  203. )
  204. else:
  205. print(
  206. """
  207. {} failed:
  208. {}
  209. Unfortunately, the exception it raised cannot be pickled, making it impossible
  210. for the parallel test runner to handle it cleanly.
  211. Here's the error encountered while trying to pickle the exception:
  212. {}
  213. You should re-run this test with the --parallel=1 option to reproduce the
  214. failure and get a correct traceback.
  215. """.format(
  216. test, original_exc_txt, pickle_exc_txt
  217. )
  218. )
  219. raise
  220. def check_subtest_picklable(self, test, subtest):
  221. try:
  222. self._confirm_picklable(subtest)
  223. except Exception as exc:
  224. self._print_unpicklable_subtest(test, subtest, exc)
  225. raise
  226. def startTestRun(self):
  227. super().startTestRun()
  228. self.events.append(("startTestRun",))
  229. def stopTestRun(self):
  230. super().stopTestRun()
  231. self.events.append(("stopTestRun",))
  232. def startTest(self, test):
  233. super().startTest(test)
  234. self.events.append(("startTest", self.test_index))
  235. def stopTest(self, test):
  236. super().stopTest(test)
  237. self.events.append(("stopTest", self.test_index))
  238. def addError(self, test, err):
  239. self.check_picklable(test, err)
  240. self.events.append(("addError", self.test_index, err))
  241. super().addError(test, err)
  242. def addFailure(self, test, err):
  243. self.check_picklable(test, err)
  244. self.events.append(("addFailure", self.test_index, err))
  245. super().addFailure(test, err)
  246. def addSubTest(self, test, subtest, err):
  247. # Follow Python's implementation of unittest.TestResult.addSubTest() by
  248. # not doing anything when a subtest is successful.
  249. if err is not None:
  250. # Call check_picklable() before check_subtest_picklable() since
  251. # check_picklable() performs the tblib check.
  252. self.check_picklable(test, err)
  253. self.check_subtest_picklable(test, subtest)
  254. self.events.append(("addSubTest", self.test_index, subtest, err))
  255. super().addSubTest(test, subtest, err)
  256. def addSuccess(self, test):
  257. self.events.append(("addSuccess", self.test_index))
  258. super().addSuccess(test)
  259. def addSkip(self, test, reason):
  260. self.events.append(("addSkip", self.test_index, reason))
  261. super().addSkip(test, reason)
  262. def addExpectedFailure(self, test, err):
  263. # If tblib isn't installed, pickling the traceback will always fail.
  264. # However we don't want tblib to be required for running the tests
  265. # when they pass or fail as expected. Drop the traceback when an
  266. # expected failure occurs.
  267. if tblib is None:
  268. err = err[0], err[1], None
  269. self.check_picklable(test, err)
  270. self.events.append(("addExpectedFailure", self.test_index, err))
  271. super().addExpectedFailure(test, err)
  272. def addUnexpectedSuccess(self, test):
  273. self.events.append(("addUnexpectedSuccess", self.test_index))
  274. super().addUnexpectedSuccess(test)
  275. def wasSuccessful(self):
  276. """Tells whether or not this result was a success."""
  277. failure_types = {"addError", "addFailure", "addSubTest", "addUnexpectedSuccess"}
  278. return all(e[0] not in failure_types for e in self.events)
  279. def _exc_info_to_string(self, err, test):
  280. # Make this method no-op. It only powers the default unittest behavior
  281. # for recording errors, but this class pickles errors into 'events'
  282. # instead.
  283. return ""
  284. class RemoteTestRunner:
  285. """
  286. Run tests and record everything but don't display anything.
  287. The implementation matches the unpythonic coding style of unittest2.
  288. """
  289. resultclass = RemoteTestResult
  290. def __init__(self, failfast=False, resultclass=None, buffer=False):
  291. self.failfast = failfast
  292. self.buffer = buffer
  293. if resultclass is not None:
  294. self.resultclass = resultclass
  295. def run(self, test):
  296. result = self.resultclass()
  297. unittest.registerResult(result)
  298. result.failfast = self.failfast
  299. result.buffer = self.buffer
  300. test(result)
  301. return result
  302. def get_max_test_processes():
  303. """
  304. The maximum number of test processes when using the --parallel option.
  305. """
  306. # The current implementation of the parallel test runner requires
  307. # multiprocessing to start subprocesses with fork() or spawn().
  308. if multiprocessing.get_start_method() not in {"fork", "spawn"}:
  309. return 1
  310. try:
  311. return int(os.environ["DJANGO_TEST_PROCESSES"])
  312. except KeyError:
  313. return multiprocessing.cpu_count()
  314. def parallel_type(value):
  315. """Parse value passed to the --parallel option."""
  316. if value == "auto":
  317. return value
  318. try:
  319. return int(value)
  320. except ValueError:
  321. raise argparse.ArgumentTypeError(
  322. f"{value!r} is not an integer or the string 'auto'"
  323. )
  324. _worker_id = 0
  325. def _init_worker(
  326. counter,
  327. initial_settings=None,
  328. serialized_contents=None,
  329. process_setup=None,
  330. process_setup_args=None,
  331. debug_mode=None,
  332. ):
  333. """
  334. Switch to databases dedicated to this worker.
  335. This helper lives at module-level because of the multiprocessing module's
  336. requirements.
  337. """
  338. global _worker_id
  339. with counter.get_lock():
  340. counter.value += 1
  341. _worker_id = counter.value
  342. start_method = multiprocessing.get_start_method()
  343. if start_method == "spawn":
  344. if process_setup and callable(process_setup):
  345. if process_setup_args is None:
  346. process_setup_args = ()
  347. process_setup(*process_setup_args)
  348. django.setup()
  349. setup_test_environment(debug=debug_mode)
  350. for alias in connections:
  351. connection = connections[alias]
  352. if start_method == "spawn":
  353. # Restore initial settings in spawned processes.
  354. connection.settings_dict.update(initial_settings[alias])
  355. if value := serialized_contents.get(alias):
  356. connection._test_serialized_contents = value
  357. connection.creation.setup_worker_connection(_worker_id)
  358. def _run_subsuite(args):
  359. """
  360. Run a suite of tests with a RemoteTestRunner and return a RemoteTestResult.
  361. This helper lives at module-level and its arguments are wrapped in a tuple
  362. because of the multiprocessing module's requirements.
  363. """
  364. runner_class, subsuite_index, subsuite, failfast, buffer = args
  365. runner = runner_class(failfast=failfast, buffer=buffer)
  366. result = runner.run(subsuite)
  367. return subsuite_index, result.events
  368. def _process_setup_stub(*args):
  369. """Stub method to simplify run() implementation."""
  370. pass
  371. class ParallelTestSuite(unittest.TestSuite):
  372. """
  373. Run a series of tests in parallel in several processes.
  374. While the unittest module's documentation implies that orchestrating the
  375. execution of tests is the responsibility of the test runner, in practice,
  376. it appears that TestRunner classes are more concerned with formatting and
  377. displaying test results.
  378. Since there are fewer use cases for customizing TestSuite than TestRunner,
  379. implementing parallelization at the level of the TestSuite improves
  380. interoperability with existing custom test runners. A single instance of a
  381. test runner can still collect results from all tests without being aware
  382. that they have been run in parallel.
  383. """
  384. # In case someone wants to modify these in a subclass.
  385. init_worker = _init_worker
  386. process_setup = _process_setup_stub
  387. process_setup_args = ()
  388. run_subsuite = _run_subsuite
  389. runner_class = RemoteTestRunner
  390. def __init__(
  391. self, subsuites, processes, failfast=False, debug_mode=False, buffer=False
  392. ):
  393. self.subsuites = subsuites
  394. self.processes = processes
  395. self.failfast = failfast
  396. self.debug_mode = debug_mode
  397. self.buffer = buffer
  398. self.initial_settings = None
  399. self.serialized_contents = None
  400. super().__init__()
  401. def run(self, result):
  402. """
  403. Distribute test cases across workers.
  404. Return an identifier of each test case with its result in order to use
  405. imap_unordered to show results as soon as they're available.
  406. To minimize pickling errors when getting results from workers:
  407. - pass back numeric indexes in self.subsuites instead of tests
  408. - make tracebacks picklable with tblib, if available
  409. Even with tblib, errors may still occur for dynamically created
  410. exception classes which cannot be unpickled.
  411. """
  412. self.initialize_suite()
  413. counter = multiprocessing.Value(ctypes.c_int, 0)
  414. pool = multiprocessing.Pool(
  415. processes=self.processes,
  416. initializer=self.init_worker.__func__,
  417. initargs=[
  418. counter,
  419. self.initial_settings,
  420. self.serialized_contents,
  421. self.process_setup.__func__,
  422. self.process_setup_args,
  423. self.debug_mode,
  424. ],
  425. )
  426. args = [
  427. (self.runner_class, index, subsuite, self.failfast, self.buffer)
  428. for index, subsuite in enumerate(self.subsuites)
  429. ]
  430. test_results = pool.imap_unordered(self.run_subsuite.__func__, args)
  431. while True:
  432. if result.shouldStop:
  433. pool.terminate()
  434. break
  435. try:
  436. subsuite_index, events = test_results.next(timeout=0.1)
  437. except multiprocessing.TimeoutError:
  438. continue
  439. except StopIteration:
  440. pool.close()
  441. break
  442. tests = list(self.subsuites[subsuite_index])
  443. for event in events:
  444. event_name = event[0]
  445. handler = getattr(result, event_name, None)
  446. if handler is None:
  447. continue
  448. test = tests[event[1]]
  449. args = event[2:]
  450. handler(test, *args)
  451. pool.join()
  452. return result
  453. def __iter__(self):
  454. return iter(self.subsuites)
  455. def initialize_suite(self):
  456. if multiprocessing.get_start_method() == "spawn":
  457. self.initial_settings = {
  458. alias: connections[alias].settings_dict for alias in connections
  459. }
  460. self.serialized_contents = {
  461. alias: connections[alias]._test_serialized_contents
  462. for alias in connections
  463. if alias in self.serialized_aliases
  464. }
  465. class Shuffler:
  466. """
  467. This class implements shuffling with a special consistency property.
  468. Consistency means that, for a given seed and key function, if two sets of
  469. items are shuffled, the resulting order will agree on the intersection of
  470. the two sets. For example, if items are removed from an original set, the
  471. shuffled order for the new set will be the shuffled order of the original
  472. set restricted to the smaller set.
  473. """
  474. # This doesn't need to be cryptographically strong, so use what's fastest.
  475. hash_algorithm = "md5"
  476. @classmethod
  477. def _hash_text(cls, text):
  478. h = new_hash(cls.hash_algorithm, usedforsecurity=False)
  479. h.update(text.encode("utf-8"))
  480. return h.hexdigest()
  481. def __init__(self, seed=None):
  482. if seed is None:
  483. # Limit seeds to 10 digits for simpler output.
  484. seed = random.randint(0, 10**10 - 1)
  485. seed_source = "generated"
  486. else:
  487. seed_source = "given"
  488. self.seed = seed
  489. self.seed_source = seed_source
  490. @property
  491. def seed_display(self):
  492. return f"{self.seed!r} ({self.seed_source})"
  493. def _hash_item(self, item, key):
  494. text = "{}{}".format(self.seed, key(item))
  495. return self._hash_text(text)
  496. def shuffle(self, items, key):
  497. """
  498. Return a new list of the items in a shuffled order.
  499. The `key` is a function that accepts an item in `items` and returns
  500. a string unique for that item that can be viewed as a string id. The
  501. order of the return value is deterministic. It depends on the seed
  502. and key function but not on the original order.
  503. """
  504. hashes = {}
  505. for item in items:
  506. hashed = self._hash_item(item, key)
  507. if hashed in hashes:
  508. msg = "item {!r} has same hash {!r} as item {!r}".format(
  509. item,
  510. hashed,
  511. hashes[hashed],
  512. )
  513. raise RuntimeError(msg)
  514. hashes[hashed] = item
  515. return [hashes[hashed] for hashed in sorted(hashes)]
  516. class DiscoverRunner:
  517. """A Django test runner that uses unittest2 test discovery."""
  518. test_suite = unittest.TestSuite
  519. parallel_test_suite = ParallelTestSuite
  520. test_runner = unittest.TextTestRunner
  521. test_loader = unittest.defaultTestLoader
  522. reorder_by = (TestCase, SimpleTestCase)
  523. def __init__(
  524. self,
  525. pattern=None,
  526. top_level=None,
  527. verbosity=1,
  528. interactive=True,
  529. failfast=False,
  530. keepdb=False,
  531. reverse=False,
  532. debug_mode=False,
  533. debug_sql=False,
  534. parallel=0,
  535. tags=None,
  536. exclude_tags=None,
  537. test_name_patterns=None,
  538. pdb=False,
  539. buffer=False,
  540. enable_faulthandler=True,
  541. timing=False,
  542. shuffle=False,
  543. logger=None,
  544. **kwargs,
  545. ):
  546. self.pattern = pattern
  547. self.top_level = top_level
  548. self.verbosity = verbosity
  549. self.interactive = interactive
  550. self.failfast = failfast
  551. self.keepdb = keepdb
  552. self.reverse = reverse
  553. self.debug_mode = debug_mode
  554. self.debug_sql = debug_sql
  555. self.parallel = parallel
  556. self.tags = set(tags or [])
  557. self.exclude_tags = set(exclude_tags or [])
  558. if not faulthandler.is_enabled() and enable_faulthandler:
  559. try:
  560. faulthandler.enable(file=sys.stderr.fileno())
  561. except (AttributeError, io.UnsupportedOperation):
  562. faulthandler.enable(file=sys.__stderr__.fileno())
  563. self.pdb = pdb
  564. if self.pdb and self.parallel > 1:
  565. raise ValueError(
  566. "You cannot use --pdb with parallel tests; pass --parallel=1 to use it."
  567. )
  568. self.buffer = buffer
  569. self.test_name_patterns = None
  570. self.time_keeper = TimeKeeper() if timing else NullTimeKeeper()
  571. if test_name_patterns:
  572. # unittest does not export the _convert_select_pattern function
  573. # that converts command-line arguments to patterns.
  574. self.test_name_patterns = {
  575. pattern if "*" in pattern else "*%s*" % pattern
  576. for pattern in test_name_patterns
  577. }
  578. self.shuffle = shuffle
  579. self._shuffler = None
  580. self.logger = logger
  581. @classmethod
  582. def add_arguments(cls, parser):
  583. parser.add_argument(
  584. "-t",
  585. "--top-level-directory",
  586. dest="top_level",
  587. help="Top level of project for unittest discovery.",
  588. )
  589. parser.add_argument(
  590. "-p",
  591. "--pattern",
  592. default="test*.py",
  593. help="The test matching pattern. Defaults to test*.py.",
  594. )
  595. parser.add_argument(
  596. "--keepdb", action="store_true", help="Preserves the test DB between runs."
  597. )
  598. parser.add_argument(
  599. "--shuffle",
  600. nargs="?",
  601. default=False,
  602. type=int,
  603. metavar="SEED",
  604. help="Shuffles test case order.",
  605. )
  606. parser.add_argument(
  607. "-r",
  608. "--reverse",
  609. action="store_true",
  610. help="Reverses test case order.",
  611. )
  612. parser.add_argument(
  613. "--debug-mode",
  614. action="store_true",
  615. help="Sets settings.DEBUG to True.",
  616. )
  617. parser.add_argument(
  618. "-d",
  619. "--debug-sql",
  620. action="store_true",
  621. help="Prints logged SQL queries on failure.",
  622. )
  623. parser.add_argument(
  624. "--parallel",
  625. nargs="?",
  626. const="auto",
  627. default=0,
  628. type=parallel_type,
  629. metavar="N",
  630. help=(
  631. "Run tests using up to N parallel processes. Use the value "
  632. '"auto" to run one test process for each processor core.'
  633. ),
  634. )
  635. parser.add_argument(
  636. "--tag",
  637. action="append",
  638. dest="tags",
  639. help="Run only tests with the specified tag. Can be used multiple times.",
  640. )
  641. parser.add_argument(
  642. "--exclude-tag",
  643. action="append",
  644. dest="exclude_tags",
  645. help="Do not run tests with the specified tag. Can be used multiple times.",
  646. )
  647. parser.add_argument(
  648. "--pdb",
  649. action="store_true",
  650. help="Runs a debugger (pdb, or ipdb if installed) on error or failure.",
  651. )
  652. parser.add_argument(
  653. "-b",
  654. "--buffer",
  655. action="store_true",
  656. help="Discard output from passing tests.",
  657. )
  658. parser.add_argument(
  659. "--no-faulthandler",
  660. action="store_false",
  661. dest="enable_faulthandler",
  662. help="Disables the Python faulthandler module during tests.",
  663. )
  664. parser.add_argument(
  665. "--timing",
  666. action="store_true",
  667. help=("Output timings, including database set up and total run time."),
  668. )
  669. parser.add_argument(
  670. "-k",
  671. action="append",
  672. dest="test_name_patterns",
  673. help=(
  674. "Only run test methods and classes that match the pattern "
  675. "or substring. Can be used multiple times. Same as "
  676. "unittest -k option."
  677. ),
  678. )
  679. @property
  680. def shuffle_seed(self):
  681. if self._shuffler is None:
  682. return None
  683. return self._shuffler.seed
  684. def log(self, msg, level=None):
  685. """
  686. Log the message at the given logging level (the default is INFO).
  687. If a logger isn't set, the message is instead printed to the console,
  688. respecting the configured verbosity. A verbosity of 0 prints no output,
  689. a verbosity of 1 prints INFO and above, and a verbosity of 2 or higher
  690. prints all levels.
  691. """
  692. if level is None:
  693. level = logging.INFO
  694. if self.logger is None:
  695. if self.verbosity <= 0 or (self.verbosity == 1 and level < logging.INFO):
  696. return
  697. print(msg)
  698. else:
  699. self.logger.log(level, msg)
  700. def setup_test_environment(self, **kwargs):
  701. setup_test_environment(debug=self.debug_mode)
  702. unittest.installHandler()
  703. def setup_shuffler(self):
  704. if self.shuffle is False:
  705. return
  706. shuffler = Shuffler(seed=self.shuffle)
  707. self.log(f"Using shuffle seed: {shuffler.seed_display}")
  708. self._shuffler = shuffler
  709. @contextmanager
  710. def load_with_patterns(self):
  711. original_test_name_patterns = self.test_loader.testNamePatterns
  712. self.test_loader.testNamePatterns = self.test_name_patterns
  713. try:
  714. yield
  715. finally:
  716. # Restore the original patterns.
  717. self.test_loader.testNamePatterns = original_test_name_patterns
  718. def load_tests_for_label(self, label, discover_kwargs):
  719. label_as_path = os.path.abspath(label)
  720. tests = None
  721. # If a module, or "module.ClassName[.method_name]", just run those.
  722. if not os.path.exists(label_as_path):
  723. with self.load_with_patterns():
  724. tests = self.test_loader.loadTestsFromName(label)
  725. if tests.countTestCases():
  726. return tests
  727. # Try discovery if "label" is a package or directory.
  728. is_importable, is_package = try_importing(label)
  729. if is_importable:
  730. if not is_package:
  731. return tests
  732. elif not os.path.isdir(label_as_path):
  733. if os.path.exists(label_as_path):
  734. assert tests is None
  735. raise RuntimeError(
  736. f"One of the test labels is a path to a file: {label!r}, "
  737. f"which is not supported. Use a dotted module name or "
  738. f"path to a directory instead."
  739. )
  740. return tests
  741. kwargs = discover_kwargs.copy()
  742. if os.path.isdir(label_as_path) and not self.top_level:
  743. kwargs["top_level_dir"] = find_top_level(label_as_path)
  744. with self.load_with_patterns():
  745. tests = self.test_loader.discover(start_dir=label, **kwargs)
  746. # Make unittest forget the top-level dir it calculated from this run,
  747. # to support running tests from two different top-levels.
  748. self.test_loader._top_level_dir = None
  749. return tests
  750. def build_suite(self, test_labels=None, extra_tests=None, **kwargs):
  751. if extra_tests is not None:
  752. warnings.warn(
  753. "The extra_tests argument is deprecated.",
  754. RemovedInDjango50Warning,
  755. stacklevel=2,
  756. )
  757. test_labels = test_labels or ["."]
  758. extra_tests = extra_tests or []
  759. discover_kwargs = {}
  760. if self.pattern is not None:
  761. discover_kwargs["pattern"] = self.pattern
  762. if self.top_level is not None:
  763. discover_kwargs["top_level_dir"] = self.top_level
  764. self.setup_shuffler()
  765. all_tests = []
  766. for label in test_labels:
  767. tests = self.load_tests_for_label(label, discover_kwargs)
  768. all_tests.extend(iter_test_cases(tests))
  769. all_tests.extend(iter_test_cases(extra_tests))
  770. if self.tags or self.exclude_tags:
  771. if self.tags:
  772. self.log(
  773. "Including test tag(s): %s." % ", ".join(sorted(self.tags)),
  774. level=logging.DEBUG,
  775. )
  776. if self.exclude_tags:
  777. self.log(
  778. "Excluding test tag(s): %s." % ", ".join(sorted(self.exclude_tags)),
  779. level=logging.DEBUG,
  780. )
  781. all_tests = filter_tests_by_tags(all_tests, self.tags, self.exclude_tags)
  782. # Put the failures detected at load time first for quicker feedback.
  783. # _FailedTest objects include things like test modules that couldn't be
  784. # found or that couldn't be loaded due to syntax errors.
  785. test_types = (unittest.loader._FailedTest, *self.reorder_by)
  786. all_tests = list(
  787. reorder_tests(
  788. all_tests,
  789. test_types,
  790. shuffler=self._shuffler,
  791. reverse=self.reverse,
  792. )
  793. )
  794. self.log("Found %d test(s)." % len(all_tests))
  795. suite = self.test_suite(all_tests)
  796. if self.parallel > 1:
  797. subsuites = partition_suite_by_case(suite)
  798. # Since tests are distributed across processes on a per-TestCase
  799. # basis, there's no need for more processes than TestCases.
  800. processes = min(self.parallel, len(subsuites))
  801. # Update also "parallel" because it's used to determine the number
  802. # of test databases.
  803. self.parallel = processes
  804. if processes > 1:
  805. suite = self.parallel_test_suite(
  806. subsuites,
  807. processes,
  808. self.failfast,
  809. self.debug_mode,
  810. self.buffer,
  811. )
  812. return suite
  813. def setup_databases(self, **kwargs):
  814. return _setup_databases(
  815. self.verbosity,
  816. self.interactive,
  817. time_keeper=self.time_keeper,
  818. keepdb=self.keepdb,
  819. debug_sql=self.debug_sql,
  820. parallel=self.parallel,
  821. **kwargs,
  822. )
  823. def get_resultclass(self):
  824. if self.debug_sql:
  825. return DebugSQLTextTestResult
  826. elif self.pdb:
  827. return PDBDebugResult
  828. def get_test_runner_kwargs(self):
  829. return {
  830. "failfast": self.failfast,
  831. "resultclass": self.get_resultclass(),
  832. "verbosity": self.verbosity,
  833. "buffer": self.buffer,
  834. }
  835. def run_checks(self, databases):
  836. # Checks are run after database creation since some checks require
  837. # database access.
  838. call_command("check", verbosity=self.verbosity, databases=databases)
  839. def run_suite(self, suite, **kwargs):
  840. kwargs = self.get_test_runner_kwargs()
  841. runner = self.test_runner(**kwargs)
  842. try:
  843. return runner.run(suite)
  844. finally:
  845. if self._shuffler is not None:
  846. seed_display = self._shuffler.seed_display
  847. self.log(f"Used shuffle seed: {seed_display}")
  848. def teardown_databases(self, old_config, **kwargs):
  849. """Destroy all the non-mirror databases."""
  850. _teardown_databases(
  851. old_config,
  852. verbosity=self.verbosity,
  853. parallel=self.parallel,
  854. keepdb=self.keepdb,
  855. )
  856. def teardown_test_environment(self, **kwargs):
  857. unittest.removeHandler()
  858. teardown_test_environment()
  859. def suite_result(self, suite, result, **kwargs):
  860. return (
  861. len(result.failures) + len(result.errors) + len(result.unexpectedSuccesses)
  862. )
  863. def _get_databases(self, suite):
  864. databases = {}
  865. for test in iter_test_cases(suite):
  866. test_databases = getattr(test, "databases", None)
  867. if test_databases == "__all__":
  868. test_databases = connections
  869. if test_databases:
  870. serialized_rollback = getattr(test, "serialized_rollback", False)
  871. databases.update(
  872. (alias, serialized_rollback or databases.get(alias, False))
  873. for alias in test_databases
  874. )
  875. return databases
  876. def get_databases(self, suite):
  877. databases = self._get_databases(suite)
  878. unused_databases = [alias for alias in connections if alias not in databases]
  879. if unused_databases:
  880. self.log(
  881. "Skipping setup of unused database(s): %s."
  882. % ", ".join(sorted(unused_databases)),
  883. level=logging.DEBUG,
  884. )
  885. return databases
  886. def run_tests(self, test_labels, extra_tests=None, **kwargs):
  887. """
  888. Run the unit tests for all the test labels in the provided list.
  889. Test labels should be dotted Python paths to test modules, test
  890. classes, or test methods.
  891. Return the number of tests that failed.
  892. """
  893. if extra_tests is not None:
  894. warnings.warn(
  895. "The extra_tests argument is deprecated.",
  896. RemovedInDjango50Warning,
  897. stacklevel=2,
  898. )
  899. self.setup_test_environment()
  900. suite = self.build_suite(test_labels, extra_tests)
  901. databases = self.get_databases(suite)
  902. suite.serialized_aliases = set(
  903. alias for alias, serialize in databases.items() if serialize
  904. )
  905. with self.time_keeper.timed("Total database setup"):
  906. old_config = self.setup_databases(
  907. aliases=databases,
  908. serialized_aliases=suite.serialized_aliases,
  909. )
  910. run_failed = False
  911. try:
  912. self.run_checks(databases)
  913. result = self.run_suite(suite)
  914. except Exception:
  915. run_failed = True
  916. raise
  917. finally:
  918. try:
  919. with self.time_keeper.timed("Total database teardown"):
  920. self.teardown_databases(old_config)
  921. self.teardown_test_environment()
  922. except Exception:
  923. # Silence teardown exceptions if an exception was raised during
  924. # runs to avoid shadowing it.
  925. if not run_failed:
  926. raise
  927. self.time_keeper.print_results()
  928. return self.suite_result(suite, result)
  929. def try_importing(label):
  930. """
  931. Try importing a test label, and return (is_importable, is_package).
  932. Relative labels like "." and ".." are seen as directories.
  933. """
  934. try:
  935. mod = import_module(label)
  936. except (ImportError, TypeError):
  937. return (False, False)
  938. return (True, hasattr(mod, "__path__"))
  939. def find_top_level(top_level):
  940. # Try to be a bit smarter than unittest about finding the default top-level
  941. # for a given directory path, to avoid breaking relative imports.
  942. # (Unittest's default is to set top-level equal to the path, which means
  943. # relative imports will result in "Attempted relative import in
  944. # non-package.").
  945. # We'd be happy to skip this and require dotted module paths (which don't
  946. # cause this problem) instead of file paths (which do), but in the case of
  947. # a directory in the cwd, which would be equally valid if considered as a
  948. # top-level module or as a directory path, unittest unfortunately prefers
  949. # the latter.
  950. while True:
  951. init_py = os.path.join(top_level, "__init__.py")
  952. if not os.path.exists(init_py):
  953. break
  954. try_next = os.path.dirname(top_level)
  955. if try_next == top_level:
  956. # __init__.py all the way down? give up.
  957. break
  958. top_level = try_next
  959. return top_level
  960. def _class_shuffle_key(cls):
  961. return f"{cls.__module__}.{cls.__qualname__}"
  962. def shuffle_tests(tests, shuffler):
  963. """
  964. Return an iterator over the given tests in a shuffled order, keeping tests
  965. next to other tests of their class.
  966. `tests` should be an iterable of tests.
  967. """
  968. tests_by_type = {}
  969. for _, class_tests in itertools.groupby(tests, type):
  970. class_tests = list(class_tests)
  971. test_type = type(class_tests[0])
  972. class_tests = shuffler.shuffle(class_tests, key=lambda test: test.id())
  973. tests_by_type[test_type] = class_tests
  974. classes = shuffler.shuffle(tests_by_type, key=_class_shuffle_key)
  975. return itertools.chain(*(tests_by_type[cls] for cls in classes))
  976. def reorder_test_bin(tests, shuffler=None, reverse=False):
  977. """
  978. Return an iterator that reorders the given tests, keeping tests next to
  979. other tests of their class.
  980. `tests` should be an iterable of tests that supports reversed().
  981. """
  982. if shuffler is None:
  983. if reverse:
  984. return reversed(tests)
  985. # The function must return an iterator.
  986. return iter(tests)
  987. tests = shuffle_tests(tests, shuffler)
  988. if not reverse:
  989. return tests
  990. # Arguments to reversed() must be reversible.
  991. return reversed(list(tests))
  992. def reorder_tests(tests, classes, reverse=False, shuffler=None):
  993. """
  994. Reorder an iterable of tests, grouping by the given TestCase classes.
  995. This function also removes any duplicates and reorders so that tests of the
  996. same type are consecutive.
  997. The result is returned as an iterator. `classes` is a sequence of types.
  998. Tests that are instances of `classes[0]` are grouped first, followed by
  999. instances of `classes[1]`, etc. Tests that are not instances of any of the
  1000. classes are grouped last.
  1001. If `reverse` is True, the tests within each `classes` group are reversed,
  1002. but without reversing the order of `classes` itself.
  1003. The `shuffler` argument is an optional instance of this module's `Shuffler`
  1004. class. If provided, tests will be shuffled within each `classes` group, but
  1005. keeping tests with other tests of their TestCase class. Reversing is
  1006. applied after shuffling to allow reversing the same random order.
  1007. """
  1008. # Each bin maps TestCase class to OrderedSet of tests. This permits tests
  1009. # to be grouped by TestCase class even if provided non-consecutively.
  1010. bins = [defaultdict(OrderedSet) for i in range(len(classes) + 1)]
  1011. *class_bins, last_bin = bins
  1012. for test in tests:
  1013. for test_bin, test_class in zip(class_bins, classes):
  1014. if isinstance(test, test_class):
  1015. break
  1016. else:
  1017. test_bin = last_bin
  1018. test_bin[type(test)].add(test)
  1019. for test_bin in bins:
  1020. # Call list() since reorder_test_bin()'s input must support reversed().
  1021. tests = list(itertools.chain.from_iterable(test_bin.values()))
  1022. yield from reorder_test_bin(tests, shuffler=shuffler, reverse=reverse)
  1023. def partition_suite_by_case(suite):
  1024. """Partition a test suite by test case, preserving the order of tests."""
  1025. suite_class = type(suite)
  1026. all_tests = iter_test_cases(suite)
  1027. return [suite_class(tests) for _, tests in itertools.groupby(all_tests, type)]
  1028. def test_match_tags(test, tags, exclude_tags):
  1029. if isinstance(test, unittest.loader._FailedTest):
  1030. # Tests that couldn't load always match to prevent tests from falsely
  1031. # passing due e.g. to syntax errors.
  1032. return True
  1033. test_tags = set(getattr(test, "tags", []))
  1034. test_fn_name = getattr(test, "_testMethodName", str(test))
  1035. if hasattr(test, test_fn_name):
  1036. test_fn = getattr(test, test_fn_name)
  1037. test_fn_tags = list(getattr(test_fn, "tags", []))
  1038. test_tags = test_tags.union(test_fn_tags)
  1039. if tags and test_tags.isdisjoint(tags):
  1040. return False
  1041. return test_tags.isdisjoint(exclude_tags)
  1042. def filter_tests_by_tags(tests, tags, exclude_tags):
  1043. """Return the matching tests as an iterator."""
  1044. return (test for test in tests if test_match_tags(test, tags, exclude_tags))