runner.py 41 KB

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