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 26 KiB

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