runner.py 44 KB

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