tests.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372
  1. """
  2. Tests for django test runner
  3. """
  4. from __future__ import unicode_literals
  5. import unittest
  6. from admin_scripts.tests import AdminScriptTestCase
  7. from django import db
  8. from django.conf import settings
  9. from django.core.exceptions import ImproperlyConfigured
  10. from django.core.management import call_command
  11. from django.test import (
  12. TestCase, TransactionTestCase, mock, skipUnlessDBFeature, testcases,
  13. )
  14. from django.test.runner import DiscoverRunner, dependency_ordered
  15. from django.test.testcases import connections_support_transactions
  16. from .models import Person
  17. class DependencyOrderingTests(unittest.TestCase):
  18. def test_simple_dependencies(self):
  19. raw = [
  20. ('s1', ('s1_db', ['alpha'])),
  21. ('s2', ('s2_db', ['bravo'])),
  22. ('s3', ('s3_db', ['charlie'])),
  23. ]
  24. dependencies = {
  25. 'alpha': ['charlie'],
  26. 'bravo': ['charlie'],
  27. }
  28. ordered = dependency_ordered(raw, dependencies=dependencies)
  29. ordered_sigs = [sig for sig, value in ordered]
  30. self.assertIn('s1', ordered_sigs)
  31. self.assertIn('s2', ordered_sigs)
  32. self.assertIn('s3', ordered_sigs)
  33. self.assertLess(ordered_sigs.index('s3'), ordered_sigs.index('s1'))
  34. self.assertLess(ordered_sigs.index('s3'), ordered_sigs.index('s2'))
  35. def test_chained_dependencies(self):
  36. raw = [
  37. ('s1', ('s1_db', ['alpha'])),
  38. ('s2', ('s2_db', ['bravo'])),
  39. ('s3', ('s3_db', ['charlie'])),
  40. ]
  41. dependencies = {
  42. 'alpha': ['bravo'],
  43. 'bravo': ['charlie'],
  44. }
  45. ordered = dependency_ordered(raw, dependencies=dependencies)
  46. ordered_sigs = [sig for sig, value in ordered]
  47. self.assertIn('s1', ordered_sigs)
  48. self.assertIn('s2', ordered_sigs)
  49. self.assertIn('s3', ordered_sigs)
  50. # Explicit dependencies
  51. self.assertLess(ordered_sigs.index('s2'), ordered_sigs.index('s1'))
  52. self.assertLess(ordered_sigs.index('s3'), ordered_sigs.index('s2'))
  53. # Implied dependencies
  54. self.assertLess(ordered_sigs.index('s3'), ordered_sigs.index('s1'))
  55. def test_multiple_dependencies(self):
  56. raw = [
  57. ('s1', ('s1_db', ['alpha'])),
  58. ('s2', ('s2_db', ['bravo'])),
  59. ('s3', ('s3_db', ['charlie'])),
  60. ('s4', ('s4_db', ['delta'])),
  61. ]
  62. dependencies = {
  63. 'alpha': ['bravo', 'delta'],
  64. 'bravo': ['charlie'],
  65. 'delta': ['charlie'],
  66. }
  67. ordered = dependency_ordered(raw, dependencies=dependencies)
  68. ordered_sigs = [sig for sig, aliases in ordered]
  69. self.assertIn('s1', ordered_sigs)
  70. self.assertIn('s2', ordered_sigs)
  71. self.assertIn('s3', ordered_sigs)
  72. self.assertIn('s4', ordered_sigs)
  73. # Explicit dependencies
  74. self.assertLess(ordered_sigs.index('s2'), ordered_sigs.index('s1'))
  75. self.assertLess(ordered_sigs.index('s4'), ordered_sigs.index('s1'))
  76. self.assertLess(ordered_sigs.index('s3'), ordered_sigs.index('s2'))
  77. self.assertLess(ordered_sigs.index('s3'), ordered_sigs.index('s4'))
  78. # Implicit dependencies
  79. self.assertLess(ordered_sigs.index('s3'), ordered_sigs.index('s1'))
  80. def test_circular_dependencies(self):
  81. raw = [
  82. ('s1', ('s1_db', ['alpha'])),
  83. ('s2', ('s2_db', ['bravo'])),
  84. ]
  85. dependencies = {
  86. 'bravo': ['alpha'],
  87. 'alpha': ['bravo'],
  88. }
  89. self.assertRaises(ImproperlyConfigured, dependency_ordered, raw, dependencies=dependencies)
  90. def test_own_alias_dependency(self):
  91. raw = [
  92. ('s1', ('s1_db', ['alpha', 'bravo']))
  93. ]
  94. dependencies = {
  95. 'alpha': ['bravo']
  96. }
  97. with self.assertRaises(ImproperlyConfigured):
  98. dependency_ordered(raw, dependencies=dependencies)
  99. # reordering aliases shouldn't matter
  100. raw = [
  101. ('s1', ('s1_db', ['bravo', 'alpha']))
  102. ]
  103. with self.assertRaises(ImproperlyConfigured):
  104. dependency_ordered(raw, dependencies=dependencies)
  105. class MockTestRunner(object):
  106. def __init__(self, *args, **kwargs):
  107. pass
  108. MockTestRunner.run_tests = mock.Mock(return_value=[])
  109. class ManageCommandTests(unittest.TestCase):
  110. def test_custom_test_runner(self):
  111. call_command('test', 'sites',
  112. testrunner='test_runner.tests.MockTestRunner')
  113. MockTestRunner.run_tests.assert_called_with(('sites',))
  114. def test_bad_test_runner(self):
  115. with self.assertRaises(AttributeError):
  116. call_command('test', 'sites',
  117. testrunner='test_runner.NonExistentRunner')
  118. class CustomTestRunnerOptionsTests(AdminScriptTestCase):
  119. def setUp(self):
  120. settings = {
  121. 'TEST_RUNNER': '\'test_runner.runner.CustomOptionsTestRunner\'',
  122. }
  123. self.write_settings('settings.py', sdict=settings)
  124. def tearDown(self):
  125. self.remove_settings('settings.py')
  126. def test_default_options(self):
  127. args = ['test', '--settings=test_project.settings']
  128. out, err = self.run_django_admin(args)
  129. self.assertNoOutput(err)
  130. self.assertOutput(out, '1:2:3')
  131. def test_default_and_given_options(self):
  132. args = ['test', '--settings=test_project.settings', '--option_b=foo']
  133. out, err = self.run_django_admin(args)
  134. self.assertNoOutput(err)
  135. self.assertOutput(out, '1:foo:3')
  136. def test_option_name_and_value_separated(self):
  137. args = ['test', '--settings=test_project.settings', '--option_b', 'foo']
  138. out, err = self.run_django_admin(args)
  139. self.assertNoOutput(err)
  140. self.assertOutput(out, '1:foo:3')
  141. def test_all_options_given(self):
  142. args = ['test', '--settings=test_project.settings', '--option_a=bar',
  143. '--option_b=foo', '--option_c=31337']
  144. out, err = self.run_django_admin(args)
  145. self.assertNoOutput(err)
  146. self.assertOutput(out, 'bar:foo:31337')
  147. class Ticket17477RegressionTests(AdminScriptTestCase):
  148. def setUp(self):
  149. self.write_settings('settings.py')
  150. def tearDown(self):
  151. self.remove_settings('settings.py')
  152. def test_ticket_17477(self):
  153. """'manage.py help test' works after r16352."""
  154. args = ['help', 'test']
  155. out, err = self.run_manage(args)
  156. self.assertNoOutput(err)
  157. class Sqlite3InMemoryTestDbs(TestCase):
  158. available_apps = []
  159. @unittest.skipUnless(all(db.connections[conn].vendor == 'sqlite' for conn in db.connections),
  160. "This is an sqlite-specific issue")
  161. def test_transaction_support(self):
  162. """Ticket #16329: sqlite3 in-memory test databases"""
  163. for option_key, option_value in (
  164. ('NAME', ':memory:'), ('TEST', {'NAME': ':memory:'})):
  165. tested_connections = db.ConnectionHandler({
  166. 'default': {
  167. 'ENGINE': 'django.db.backends.sqlite3',
  168. option_key: option_value,
  169. },
  170. 'other': {
  171. 'ENGINE': 'django.db.backends.sqlite3',
  172. option_key: option_value,
  173. },
  174. })
  175. with mock.patch('django.db.connections', new=tested_connections):
  176. with mock.patch('django.test.testcases.connections', new=tested_connections):
  177. other = tested_connections['other']
  178. DiscoverRunner(verbosity=0).setup_databases()
  179. msg = ("DATABASES setting '%s' option set to sqlite3's ':memory:' value "
  180. "shouldn't interfere with transaction support detection." % option_key)
  181. # Transaction support should be properly initialized for the 'other' DB
  182. self.assertTrue(other.features.supports_transactions, msg)
  183. # And all the DBs should report that they support transactions
  184. self.assertTrue(connections_support_transactions(), msg)
  185. class DummyBackendTest(unittest.TestCase):
  186. def test_setup_databases(self):
  187. """
  188. Test that setup_databases() doesn't fail with dummy database backend.
  189. """
  190. tested_connections = db.ConnectionHandler({})
  191. with mock.patch('django.test.runner.connections', new=tested_connections):
  192. runner_instance = DiscoverRunner(verbosity=0)
  193. try:
  194. old_config = runner_instance.setup_databases()
  195. runner_instance.teardown_databases(old_config)
  196. except Exception as e:
  197. self.fail("setup_databases/teardown_databases unexpectedly raised "
  198. "an error: %s" % e)
  199. class AliasedDefaultTestSetupTest(unittest.TestCase):
  200. def test_setup_aliased_default_database(self):
  201. """
  202. Test that setup_datebases() doesn't fail when 'default' is aliased
  203. """
  204. tested_connections = db.ConnectionHandler({
  205. 'default': {
  206. 'NAME': 'dummy'
  207. },
  208. 'aliased': {
  209. 'NAME': 'dummy'
  210. }
  211. })
  212. with mock.patch('django.test.runner.connections', new=tested_connections):
  213. runner_instance = DiscoverRunner(verbosity=0)
  214. try:
  215. old_config = runner_instance.setup_databases()
  216. runner_instance.teardown_databases(old_config)
  217. except Exception as e:
  218. self.fail("setup_databases/teardown_databases unexpectedly raised "
  219. "an error: %s" % e)
  220. class SetupDatabasesTests(unittest.TestCase):
  221. def setUp(self):
  222. self.runner_instance = DiscoverRunner(verbosity=0)
  223. def test_setup_aliased_databases(self):
  224. tested_connections = db.ConnectionHandler({
  225. 'default': {
  226. 'ENGINE': 'django.db.backends.dummy',
  227. 'NAME': 'dbname',
  228. },
  229. 'other': {
  230. 'ENGINE': 'django.db.backends.dummy',
  231. 'NAME': 'dbname',
  232. }
  233. })
  234. with mock.patch('django.db.backends.dummy.base.DatabaseCreation') as mocked_db_creation:
  235. with mock.patch('django.test.runner.connections', new=tested_connections):
  236. old_config = self.runner_instance.setup_databases()
  237. self.runner_instance.teardown_databases(old_config)
  238. mocked_db_creation.return_value.destroy_test_db.assert_called_once_with('dbname', 0, False)
  239. def test_destroy_test_db_restores_db_name(self):
  240. tested_connections = db.ConnectionHandler({
  241. 'default': {
  242. 'ENGINE': settings.DATABASES[db.DEFAULT_DB_ALIAS]["ENGINE"],
  243. 'NAME': 'xxx_test_database',
  244. },
  245. })
  246. # Using the real current name as old_name to not mess with the test suite.
  247. old_name = settings.DATABASES[db.DEFAULT_DB_ALIAS]["NAME"]
  248. with mock.patch('django.db.connections', new=tested_connections):
  249. tested_connections['default'].creation.destroy_test_db(old_name, verbosity=0, keepdb=True)
  250. self.assertEqual(tested_connections['default'].settings_dict["NAME"], old_name)
  251. def test_serialization(self):
  252. tested_connections = db.ConnectionHandler({
  253. 'default': {
  254. 'ENGINE': 'django.db.backends.dummy',
  255. },
  256. })
  257. with mock.patch('django.db.backends.dummy.base.DatabaseCreation') as mocked_db_creation:
  258. with mock.patch('django.test.runner.connections', new=tested_connections):
  259. self.runner_instance.setup_databases()
  260. mocked_db_creation.return_value.create_test_db.assert_called_once_with(
  261. verbosity=0, autoclobber=False, serialize=True, keepdb=False
  262. )
  263. def test_serialized_off(self):
  264. tested_connections = db.ConnectionHandler({
  265. 'default': {
  266. 'ENGINE': 'django.db.backends.dummy',
  267. 'TEST': {'SERIALIZE': False},
  268. },
  269. })
  270. with mock.patch('django.db.backends.dummy.base.DatabaseCreation') as mocked_db_creation:
  271. with mock.patch('django.test.runner.connections', new=tested_connections):
  272. self.runner_instance.setup_databases()
  273. mocked_db_creation.return_value.create_test_db.assert_called_once_with(
  274. verbosity=0, autoclobber=False, serialize=False, keepdb=False
  275. )
  276. class AutoIncrementResetTest(TransactionTestCase):
  277. """
  278. Here we test creating the same model two times in different test methods,
  279. and check that both times they get "1" as their PK value. That is, we test
  280. that AutoField values start from 1 for each transactional test case.
  281. """
  282. available_apps = ['test_runner']
  283. reset_sequences = True
  284. @skipUnlessDBFeature('supports_sequence_reset')
  285. def test_autoincrement_reset1(self):
  286. p = Person.objects.create(first_name='Jack', last_name='Smith')
  287. self.assertEqual(p.pk, 1)
  288. @skipUnlessDBFeature('supports_sequence_reset')
  289. def test_autoincrement_reset2(self):
  290. p = Person.objects.create(first_name='Jack', last_name='Smith')
  291. self.assertEqual(p.pk, 1)
  292. class EmptyDefaultDatabaseTest(unittest.TestCase):
  293. def test_empty_default_database(self):
  294. """
  295. Test that an empty default database in settings does not raise an ImproperlyConfigured
  296. error when running a unit test that does not use a database.
  297. """
  298. testcases.connections = db.ConnectionHandler({'default': {}})
  299. connection = testcases.connections[db.utils.DEFAULT_DB_ALIAS]
  300. self.assertEqual(connection.settings_dict['ENGINE'], 'django.db.backends.dummy')
  301. try:
  302. connections_support_transactions()
  303. except Exception as e:
  304. self.fail("connections_support_transactions() unexpectedly raised an error: %s" % e)