advanced.txt 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744
  1. =======================
  2. Advanced testing topics
  3. =======================
  4. The request factory
  5. ===================
  6. .. currentmodule:: django.test
  7. .. class:: RequestFactory
  8. The :class:`~django.test.RequestFactory` shares the same API as
  9. the test client. However, instead of behaving like a browser, the
  10. RequestFactory provides a way to generate a request instance that can
  11. be used as the first argument to any view. This means you can test a
  12. view function the same way as you would test any other function -- as
  13. a black box, with exactly known inputs, testing for specific outputs.
  14. The API for the :class:`~django.test.RequestFactory` is a slightly
  15. restricted subset of the test client API:
  16. * It only has access to the HTTP methods :meth:`~Client.get()`,
  17. :meth:`~Client.post()`, :meth:`~Client.put()`,
  18. :meth:`~Client.delete()`, :meth:`~Client.head()`,
  19. :meth:`~Client.options()`, and :meth:`~Client.trace()`.
  20. * These methods accept all the same arguments *except* for
  21. ``follows``. Since this is just a factory for producing
  22. requests, it's up to you to handle the response.
  23. * It does not support middleware. Session and authentication
  24. attributes must be supplied by the test itself if required
  25. for the view to function properly.
  26. Example
  27. -------
  28. The following is a simple unit test using the request factory::
  29. from django.contrib.auth.models import AnonymousUser, User
  30. from django.test import TestCase, RequestFactory
  31. from .views import MyView, my_view
  32. class SimpleTest(TestCase):
  33. def setUp(self):
  34. # Every test needs access to the request factory.
  35. self.factory = RequestFactory()
  36. self.user = User.objects.create_user(
  37. username='jacob', email='jacob@…', password='top_secret')
  38. def test_details(self):
  39. # Create an instance of a GET request.
  40. request = self.factory.get('/customer/details')
  41. # Recall that middleware are not supported. You can simulate a
  42. # logged-in user by setting request.user manually.
  43. request.user = self.user
  44. # Or you can simulate an anonymous user by setting request.user to
  45. # an AnonymousUser instance.
  46. request.user = AnonymousUser()
  47. # Test my_view() as if it were deployed at /customer/details
  48. response = my_view(request)
  49. # Use this syntax for class-based views.
  50. response = MyView.as_view()(request)
  51. self.assertEqual(response.status_code, 200)
  52. .. _topics-testing-advanced-multiple-hosts:
  53. Tests and multiple host names
  54. =============================
  55. The :setting:`ALLOWED_HOSTS` setting is validated when running tests. This
  56. allows the test client to differentiate between internal and external URLs.
  57. Projects that support multitenancy or otherwise alter business logic based on
  58. the request's host and use custom host names in tests must include those hosts
  59. in :setting:`ALLOWED_HOSTS`.
  60. The first and simplest option to do so is to add the hosts to your settings
  61. file. For example, the test suite for docs.djangoproject.com includes the
  62. following::
  63. from django.test import TestCase
  64. class SearchFormTestCase(TestCase):
  65. def test_empty_get(self):
  66. response = self.client.get('/en/dev/search/', HTTP_HOST='docs.djangoproject.dev:8000')
  67. self.assertEqual(response.status_code, 200)
  68. and the settings file includes a list of the domains supported by the project::
  69. ALLOWED_HOSTS = [
  70. 'www.djangoproject.dev',
  71. 'docs.djangoproject.dev',
  72. ...
  73. ]
  74. Another option is to add the required hosts to :setting:`ALLOWED_HOSTS` using
  75. :meth:`~django.test.override_settings()` or
  76. :attr:`~django.test.SimpleTestCase.modify_settings()`. This option may be
  77. preferable in standalone apps that can't package their own settings file or
  78. for projects where the list of domains is not static (e.g., subdomains for
  79. multitenancy). For example, you could write a test for the domain
  80. ``http://otherserver/`` as follows::
  81. from django.test import TestCase, override_settings
  82. class MultiDomainTestCase(TestCase):
  83. @override_settings(ALLOWED_HOSTS=['otherserver'])
  84. def test_other_domain(self):
  85. response = self.client.get('http://otherserver/foo/bar/')
  86. Disabling :setting:`ALLOWED_HOSTS` checking (``ALLOWED_HOSTS = ['*']``) when
  87. running tests prevents the test client from raising a helpful error message if
  88. you follow a redirect to an external URL.
  89. .. versionchanged:: 1.11
  90. Older versions didn't validate ``ALLOWED_HOSTS`` while testing so these
  91. techniques weren't necessary.
  92. .. _topics-testing-advanced-multidb:
  93. Tests and multiple databases
  94. ============================
  95. .. _topics-testing-primaryreplica:
  96. Testing primary/replica configurations
  97. --------------------------------------
  98. If you're testing a multiple database configuration with primary/replica
  99. (referred to as master/slave by some databases) replication, this strategy of
  100. creating test databases poses a problem.
  101. When the test databases are created, there won't be any replication,
  102. and as a result, data created on the primary won't be seen on the
  103. replica.
  104. To compensate for this, Django allows you to define that a database is
  105. a *test mirror*. Consider the following (simplified) example database
  106. configuration::
  107. DATABASES = {
  108. 'default': {
  109. 'ENGINE': 'django.db.backends.mysql',
  110. 'NAME': 'myproject',
  111. 'HOST': 'dbprimary',
  112. # ... plus some other settings
  113. },
  114. 'replica': {
  115. 'ENGINE': 'django.db.backends.mysql',
  116. 'NAME': 'myproject',
  117. 'HOST': 'dbreplica',
  118. 'TEST': {
  119. 'MIRROR': 'default',
  120. },
  121. # ... plus some other settings
  122. }
  123. }
  124. In this setup, we have two database servers: ``dbprimary``, described
  125. by the database alias ``default``, and ``dbreplica`` described by the
  126. alias ``replica``. As you might expect, ``dbreplica`` has been configured
  127. by the database administrator as a read replica of ``dbprimary``, so in
  128. normal activity, any write to ``default`` will appear on ``replica``.
  129. If Django created two independent test databases, this would break any
  130. tests that expected replication to occur. However, the ``replica``
  131. database has been configured as a test mirror (using the
  132. :setting:`MIRROR <TEST_MIRROR>` test setting), indicating that under
  133. testing, ``replica`` should be treated as a mirror of ``default``.
  134. When the test environment is configured, a test version of ``replica``
  135. will *not* be created. Instead the connection to ``replica``
  136. will be redirected to point at ``default``. As a result, writes to
  137. ``default`` will appear on ``replica`` -- but because they are actually
  138. the same database, not because there is data replication between the
  139. two databases.
  140. .. _topics-testing-creation-dependencies:
  141. Controlling creation order for test databases
  142. ---------------------------------------------
  143. By default, Django will assume all databases depend on the ``default``
  144. database and therefore always create the ``default`` database first.
  145. However, no guarantees are made on the creation order of any other
  146. databases in your test setup.
  147. If your database configuration requires a specific creation order, you
  148. can specify the dependencies that exist using the :setting:`DEPENDENCIES
  149. <TEST_DEPENDENCIES>` test setting. Consider the following (simplified)
  150. example database configuration::
  151. DATABASES = {
  152. 'default': {
  153. # ... db settings
  154. 'TEST': {
  155. 'DEPENDENCIES': ['diamonds'],
  156. },
  157. },
  158. 'diamonds': {
  159. # ... db settings
  160. 'TEST': {
  161. 'DEPENDENCIES': [],
  162. },
  163. },
  164. 'clubs': {
  165. # ... db settings
  166. 'TEST': {
  167. 'DEPENDENCIES': ['diamonds'],
  168. },
  169. },
  170. 'spades': {
  171. # ... db settings
  172. 'TEST': {
  173. 'DEPENDENCIES': ['diamonds', 'hearts'],
  174. },
  175. },
  176. 'hearts': {
  177. # ... db settings
  178. 'TEST': {
  179. 'DEPENDENCIES': ['diamonds', 'clubs'],
  180. },
  181. }
  182. }
  183. Under this configuration, the ``diamonds`` database will be created first,
  184. as it is the only database alias without dependencies. The ``default`` and
  185. ``clubs`` alias will be created next (although the order of creation of this
  186. pair is not guaranteed), then ``hearts``, and finally ``spades``.
  187. If there are any circular dependencies in the :setting:`DEPENDENCIES
  188. <TEST_DEPENDENCIES>` definition, an
  189. :exc:`~django.core.exceptions.ImproperlyConfigured` exception will be raised.
  190. Advanced features of ``TransactionTestCase``
  191. ============================================
  192. .. attribute:: TransactionTestCase.available_apps
  193. .. warning::
  194. This attribute is a private API. It may be changed or removed without
  195. a deprecation period in the future, for instance to accommodate changes
  196. in application loading.
  197. It's used to optimize Django's own test suite, which contains hundreds
  198. of models but no relations between models in different applications.
  199. By default, ``available_apps`` is set to ``None``. After each test, Django
  200. calls :djadmin:`flush` to reset the database state. This empties all tables
  201. and emits the :data:`~django.db.models.signals.post_migrate` signal, which
  202. re-creates one content type and three permissions for each model. This
  203. operation gets expensive proportionally to the number of models.
  204. Setting ``available_apps`` to a list of applications instructs Django to
  205. behave as if only the models from these applications were available. The
  206. behavior of ``TransactionTestCase`` changes as follows:
  207. - :data:`~django.db.models.signals.post_migrate` is fired before each
  208. test to create the content types and permissions for each model in
  209. available apps, in case they're missing.
  210. - After each test, Django empties only tables corresponding to models in
  211. available apps. However, at the database level, truncation may cascade to
  212. related models in unavailable apps. Furthermore
  213. :data:`~django.db.models.signals.post_migrate` isn't fired; it will be
  214. fired by the next ``TransactionTestCase``, after the correct set of
  215. applications is selected.
  216. Since the database isn't fully flushed, if a test creates instances of
  217. models not included in ``available_apps``, they will leak and they may
  218. cause unrelated tests to fail. Be careful with tests that use sessions;
  219. the default session engine stores them in the database.
  220. Since :data:`~django.db.models.signals.post_migrate` isn't emitted after
  221. flushing the database, its state after a ``TransactionTestCase`` isn't the
  222. same as after a ``TestCase``: it's missing the rows created by listeners
  223. to :data:`~django.db.models.signals.post_migrate`. Considering the
  224. :ref:`order in which tests are executed <order-of-tests>`, this isn't an
  225. issue, provided either all ``TransactionTestCase`` in a given test suite
  226. declare ``available_apps``, or none of them.
  227. ``available_apps`` is mandatory in Django's own test suite.
  228. .. attribute:: TransactionTestCase.reset_sequences
  229. Setting ``reset_sequences = True`` on a ``TransactionTestCase`` will make
  230. sure sequences are always reset before the test run::
  231. class TestsThatDependsOnPrimaryKeySequences(TransactionTestCase):
  232. reset_sequences = True
  233. def test_animal_pk(self):
  234. lion = Animal.objects.create(name="lion", sound="roar")
  235. # lion.pk is guaranteed to always be 1
  236. self.assertEqual(lion.pk, 1)
  237. Unless you are explicitly testing primary keys sequence numbers, it is
  238. recommended that you do not hard code primary key values in tests.
  239. Using ``reset_sequences = True`` will slow down the test, since the primary
  240. key reset is an relatively expensive database operation.
  241. .. _testing-reusable-applications:
  242. Using the Django test runner to test reusable applications
  243. ==========================================================
  244. If you are writing a :doc:`reusable application </intro/reusable-apps>`
  245. you may want to use the Django test runner to run your own test suite
  246. and thus benefit from the Django testing infrastructure.
  247. A common practice is a *tests* directory next to the application code, with the
  248. following structure::
  249. runtests.py
  250. polls/
  251. __init__.py
  252. models.py
  253. ...
  254. tests/
  255. __init__.py
  256. models.py
  257. test_settings.py
  258. tests.py
  259. Let's take a look inside a couple of those files:
  260. .. snippet::
  261. :filename: runtests.py
  262. #!/usr/bin/env python
  263. import os
  264. import sys
  265. import django
  266. from django.conf import settings
  267. from django.test.utils import get_runner
  268. if __name__ == "__main__":
  269. os.environ['DJANGO_SETTINGS_MODULE'] = 'tests.test_settings'
  270. django.setup()
  271. TestRunner = get_runner(settings)
  272. test_runner = TestRunner()
  273. failures = test_runner.run_tests(["tests"])
  274. sys.exit(bool(failures))
  275. This is the script that you invoke to run the test suite. It sets up the
  276. Django environment, creates the test database and runs the tests.
  277. For the sake of clarity, this example contains only the bare minimum
  278. necessary to use the Django test runner. You may want to add
  279. command-line options for controlling verbosity, passing in specific test
  280. labels to run, etc.
  281. .. snippet::
  282. :filename: tests/test_settings.py
  283. SECRET_KEY = 'fake-key'
  284. INSTALLED_APPS = [
  285. "tests",
  286. ]
  287. This file contains the :doc:`Django settings </topics/settings>`
  288. required to run your app's tests.
  289. Again, this is a minimal example; your tests may require additional
  290. settings to run.
  291. Since the *tests* package is included in :setting:`INSTALLED_APPS` when
  292. running your tests, you can define test-only models in its ``models.py``
  293. file.
  294. .. _other-testing-frameworks:
  295. Using different testing frameworks
  296. ==================================
  297. Clearly, :mod:`unittest` is not the only Python testing framework. While Django
  298. doesn't provide explicit support for alternative frameworks, it does provide a
  299. way to invoke tests constructed for an alternative framework as if they were
  300. normal Django tests.
  301. When you run ``./manage.py test``, Django looks at the :setting:`TEST_RUNNER`
  302. setting to determine what to do. By default, :setting:`TEST_RUNNER` points to
  303. ``'django.test.runner.DiscoverRunner'``. This class defines the default Django
  304. testing behavior. This behavior involves:
  305. #. Performing global pre-test setup.
  306. #. Looking for tests in any file below the current directory whose name matches
  307. the pattern ``test*.py``.
  308. #. Creating the test databases.
  309. #. Running ``migrate`` to install models and initial data into the test
  310. databases.
  311. #. Running the :doc:`system checks </topics/checks>`.
  312. #. Running the tests that were found.
  313. #. Destroying the test databases.
  314. #. Performing global post-test teardown.
  315. .. versionchanged:: 1.11
  316. Running the system checks was added.
  317. If you define your own test runner class and point :setting:`TEST_RUNNER` at
  318. that class, Django will execute your test runner whenever you run
  319. ``./manage.py test``. In this way, it is possible to use any test framework
  320. that can be executed from Python code, or to modify the Django test execution
  321. process to satisfy whatever testing requirements you may have.
  322. .. _topics-testing-test_runner:
  323. Defining a test runner
  324. ----------------------
  325. .. currentmodule:: django.test.runner
  326. A test runner is a class defining a ``run_tests()`` method. Django ships
  327. with a ``DiscoverRunner`` class that defines the default Django testing
  328. behavior. This class defines the ``run_tests()`` entry point, plus a
  329. selection of other methods that are used to by ``run_tests()`` to set up,
  330. execute and tear down the test suite.
  331. .. class:: DiscoverRunner(pattern='test*.py', top_level=None, verbosity=1, interactive=True, failfast=False, keepdb=False, reverse=False, debug_mode=False, debug_sql=False, **kwargs)
  332. ``DiscoverRunner`` will search for tests in any file matching ``pattern``.
  333. ``top_level`` can be used to specify the directory containing your
  334. top-level Python modules. Usually Django can figure this out automatically,
  335. so it's not necessary to specify this option. If specified, it should
  336. generally be the directory containing your ``manage.py`` file.
  337. ``verbosity`` determines the amount of notification and debug information
  338. that will be printed to the console; ``0`` is no output, ``1`` is normal
  339. output, and ``2`` is verbose output.
  340. If ``interactive`` is ``True``, the test suite has permission to ask the
  341. user for instructions when the test suite is executed. An example of this
  342. behavior would be asking for permission to delete an existing test
  343. database. If ``interactive`` is ``False``, the test suite must be able to
  344. run without any manual intervention.
  345. If ``failfast`` is ``True``, the test suite will stop running after the
  346. first test failure is detected.
  347. If ``keepdb`` is ``True``, the test suite will use the existing database,
  348. or create one if necessary. If ``False``, a new database will be created,
  349. prompting the user to remove the existing one, if present.
  350. If ``reverse`` is ``True``, test cases will be executed in the opposite
  351. order. This could be useful to debug tests that aren't properly isolated
  352. and have side effects. :ref:`Grouping by test class <order-of-tests>` is
  353. preserved when using this option.
  354. ``debug_mode`` specifies what the :setting:`DEBUG` setting should be
  355. set to prior to running tests.
  356. If ``debug_sql`` is ``True``, failing test cases will output SQL queries
  357. logged to the :ref:`django.db.backends logger <django-db-logger>` as well
  358. as the traceback. If ``verbosity`` is ``2``, then queries in all tests are
  359. output.
  360. Django may, from time to time, extend the capabilities of the test runner
  361. by adding new arguments. The ``**kwargs`` declaration allows for this
  362. expansion. If you subclass ``DiscoverRunner`` or write your own test
  363. runner, ensure it accepts ``**kwargs``.
  364. Your test runner may also define additional command-line options.
  365. Create or override an ``add_arguments(cls, parser)`` class method and add
  366. custom arguments by calling ``parser.add_argument()`` inside the method, so
  367. that the :djadmin:`test` command will be able to use those arguments.
  368. .. versionadded:: 1.11
  369. The ``debug_mode`` keyword argument was added.
  370. Attributes
  371. ~~~~~~~~~~
  372. .. attribute:: DiscoverRunner.test_suite
  373. The class used to build the test suite. By default it is set to
  374. ``unittest.TestSuite``. This can be overridden if you wish to implement
  375. different logic for collecting tests.
  376. .. attribute:: DiscoverRunner.test_runner
  377. This is the class of the low-level test runner which is used to execute
  378. the individual tests and format the results. By default it is set to
  379. ``unittest.TextTestRunner``. Despite the unfortunate similarity in
  380. naming conventions, this is not the same type of class as
  381. ``DiscoverRunner``, which covers a broader set of responsibilities. You
  382. can override this attribute to modify the way tests are run and reported.
  383. .. attribute:: DiscoverRunner.test_loader
  384. This is the class that loads tests, whether from TestCases or modules or
  385. otherwise and bundles them into test suites for the runner to execute.
  386. By default it is set to ``unittest.defaultTestLoader``. You can override
  387. this attribute if your tests are going to be loaded in unusual ways.
  388. Methods
  389. ~~~~~~~
  390. .. method:: DiscoverRunner.run_tests(test_labels, extra_tests=None, **kwargs)
  391. Run the test suite.
  392. ``test_labels`` allows you to specify which tests to run and supports
  393. several formats (see :meth:`DiscoverRunner.build_suite` for a list of
  394. supported formats).
  395. ``extra_tests`` is a list of extra ``TestCase`` instances to add to the
  396. suite that is executed by the test runner. These extra tests are run
  397. in addition to those discovered in the modules listed in ``test_labels``.
  398. This method should return the number of tests that failed.
  399. .. classmethod:: DiscoverRunner.add_arguments(parser)
  400. Override this class method to add custom arguments accepted by the
  401. :djadmin:`test` management command. See
  402. :py:meth:`argparse.ArgumentParser.add_argument()` for details about adding
  403. arguments to a parser.
  404. .. method:: DiscoverRunner.setup_test_environment(**kwargs)
  405. Sets up the test environment by calling
  406. :func:`~django.test.utils.setup_test_environment` and setting
  407. :setting:`DEBUG` to ``self.debug_mode`` (defaults to ``False``).
  408. .. method:: DiscoverRunner.build_suite(test_labels, extra_tests=None, **kwargs)
  409. Constructs a test suite that matches the test labels provided.
  410. ``test_labels`` is a list of strings describing the tests to be run. A test
  411. label can take one of four forms:
  412. * ``path.to.test_module.TestCase.test_method`` -- Run a single test method
  413. in a test case.
  414. * ``path.to.test_module.TestCase`` -- Run all the test methods in a test
  415. case.
  416. * ``path.to.module`` -- Search for and run all tests in the named Python
  417. package or module.
  418. * ``path/to/directory`` -- Search for and run all tests below the named
  419. directory.
  420. If ``test_labels`` has a value of ``None``, the test runner will search for
  421. tests in all files below the current directory whose names match its
  422. ``pattern`` (see above).
  423. ``extra_tests`` is a list of extra ``TestCase`` instances to add to the
  424. suite that is executed by the test runner. These extra tests are run
  425. in addition to those discovered in the modules listed in ``test_labels``.
  426. Returns a ``TestSuite`` instance ready to be run.
  427. .. method:: DiscoverRunner.setup_databases(**kwargs)
  428. Creates the test databases by calling
  429. :func:`~django.test.utils.setup_databases`.
  430. .. method:: DiscoverRunner.run_checks()
  431. .. versionadded:: 1.11
  432. Runs the :doc:`system checks </topics/checks>`.
  433. .. method:: DiscoverRunner.run_suite(suite, **kwargs)
  434. Runs the test suite.
  435. Returns the result produced by the running the test suite.
  436. .. method:: DiscoverRunner.get_test_runner_kwargs()
  437. .. versionadded:: 1.11
  438. Returns the keyword arguments to instantiate the
  439. ``DiscoverRunner.test_runner`` with.
  440. .. method:: DiscoverRunner.teardown_databases(old_config, **kwargs)
  441. Destroys the test databases, restoring pre-test conditions by calling
  442. :func:`~django.test.utils.teardown_databases`.
  443. .. method:: DiscoverRunner.teardown_test_environment(**kwargs)
  444. Restores the pre-test environment.
  445. .. method:: DiscoverRunner.suite_result(suite, result, **kwargs)
  446. Computes and returns a return code based on a test suite, and the result
  447. from that test suite.
  448. Testing utilities
  449. -----------------
  450. ``django.test.utils``
  451. ~~~~~~~~~~~~~~~~~~~~~
  452. .. module:: django.test.utils
  453. :synopsis: Helpers to write custom test runners.
  454. To assist in the creation of your own test runner, Django provides a number of
  455. utility methods in the ``django.test.utils`` module.
  456. .. function:: setup_test_environment(debug=None)
  457. Performs global pre-test setup, such as installing instrumentation for the
  458. template rendering system and setting up the dummy email outbox.
  459. If ``debug`` isn't ``None``, the :setting:`DEBUG` setting is updated to its
  460. value.
  461. .. versionchanged:: 1.11
  462. The ``debug`` argument was added.
  463. .. function:: teardown_test_environment()
  464. Performs global post-test teardown, such as removing instrumentation from
  465. the template system and restoring normal email services.
  466. .. function:: setup_databases(verbosity, interactive, keepdb=False, debug_sql=False, parallel=0, **kwargs)
  467. .. versionadded:: 1.11
  468. Creates the test databases.
  469. Returns a data structure that provides enough detail to undo the changes
  470. that have been made. This data will be provided to the
  471. :func:`teardown_databases` function at the conclusion of testing.
  472. .. function:: teardown_databases(old_config, parallel=0, keepdb=False)
  473. .. versionadded:: 1.11
  474. Destroys the test databases, restoring pre-test conditions.
  475. ``old_config`` is a data structure defining the changes in the database
  476. configuration that need to be reversed. It's the return value of the
  477. :meth:`setup_databases` method.
  478. ``django.db.connection.creation``
  479. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  480. .. currentmodule:: django.db.connection.creation
  481. The creation module of the database backend also provides some utilities that
  482. can be useful during testing.
  483. .. function:: create_test_db(verbosity=1, autoclobber=False, serialize=True, keepdb=False)
  484. Creates a new test database and runs ``migrate`` against it.
  485. ``verbosity`` has the same behavior as in ``run_tests()``.
  486. ``autoclobber`` describes the behavior that will occur if a
  487. database with the same name as the test database is discovered:
  488. * If ``autoclobber`` is ``False``, the user will be asked to
  489. approve destroying the existing database. ``sys.exit`` is
  490. called if the user does not approve.
  491. * If autoclobber is ``True``, the database will be destroyed
  492. without consulting the user.
  493. ``serialize`` determines if Django serializes the database into an
  494. in-memory JSON string before running tests (used to restore the database
  495. state between tests if you don't have transactions). You can set this to
  496. ``False`` to speed up creation time if you don't have any test classes
  497. with :ref:`serialized_rollback=True <test-case-serialized-rollback>`.
  498. If you are using the default test runner, you can control this with the
  499. the :setting:`SERIALIZE <TEST_SERIALIZE>` entry in the :setting:`TEST
  500. <DATABASE-TEST>` dictionary.
  501. ``keepdb`` determines if the test run should use an existing
  502. database, or create a new one. If ``True``, the existing
  503. database will be used, or created if not present. If ``False``,
  504. a new database will be created, prompting the user to remove
  505. the existing one, if present.
  506. Returns the name of the test database that it created.
  507. ``create_test_db()`` has the side effect of modifying the value of
  508. :setting:`NAME` in :setting:`DATABASES` to match the name of the test
  509. database.
  510. .. function:: destroy_test_db(old_database_name, verbosity=1, keepdb=False)
  511. Destroys the database whose name is the value of :setting:`NAME` in
  512. :setting:`DATABASES`, and sets :setting:`NAME` to the value of
  513. ``old_database_name``.
  514. The ``verbosity`` argument has the same behavior as for
  515. :class:`~django.test.runner.DiscoverRunner`.
  516. If the ``keepdb`` argument is ``True``, then the connection to the
  517. database will be closed, but the database will not be destroyed.
  518. .. _topics-testing-code-coverage:
  519. Integration with ``coverage.py``
  520. ================================
  521. Code coverage describes how much source code has been tested. It shows which
  522. parts of your code are being exercised by tests and which are not. It's an
  523. important part of testing applications, so it's strongly recommended to check
  524. the coverage of your tests.
  525. Django can be easily integrated with `coverage.py`_, a tool for measuring code
  526. coverage of Python programs. First, `install coverage.py`_. Next, run the
  527. following from your project folder containing ``manage.py``::
  528. coverage run --source='.' manage.py test myapp
  529. This runs your tests and collects coverage data of the executed files in your
  530. project. You can see a report of this data by typing following command::
  531. coverage report
  532. Note that some Django code was executed while running tests, but it is not
  533. listed here because of the ``source`` flag passed to the previous command.
  534. For more options like annotated HTML listings detailing missed lines, see the
  535. `coverage.py`_ docs.
  536. .. _coverage.py: http://coverage.readthedocs.io/
  537. .. _install coverage.py: https://pypi.python.org/pypi/coverage