Funktionierender Prototyp des Serious Games zur Vermittlung von Wissen zu Software-Engineering-Arbeitsmodellen.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

runner.py 41KB

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