1. =======================
    
  2. Advanced testing topics
    
  3. =======================
    
  4. 
    
  5. The request factory
    
  6. ===================
    
  7. 
    
  8. .. currentmodule:: django.test
    
  9. 
    
  10. .. class:: RequestFactory
    
  11. 
    
  12. The :class:`~django.test.RequestFactory` shares the same API as
    
  13. the test client. However, instead of behaving like a browser, the
    
  14. RequestFactory provides a way to generate a request instance that can
    
  15. be used as the first argument to any view. This means you can test a
    
  16. view function the same way as you would test any other function -- as
    
  17. a black box, with exactly known inputs, testing for specific outputs.
    
  18. 
    
  19. The API for the :class:`~django.test.RequestFactory` is a slightly
    
  20. restricted subset of the test client API:
    
  21. 
    
  22. * It only has access to the HTTP methods :meth:`~Client.get()`,
    
  23.   :meth:`~Client.post()`, :meth:`~Client.put()`,
    
  24.   :meth:`~Client.delete()`, :meth:`~Client.head()`,
    
  25.   :meth:`~Client.options()`, and :meth:`~Client.trace()`.
    
  26. 
    
  27. * These methods accept all the same arguments *except* for
    
  28.   ``follow``. Since this is just a factory for producing
    
  29.   requests, it's up to you to handle the response.
    
  30. 
    
  31. * It does not support middleware. Session and authentication
    
  32.   attributes must be supplied by the test itself if required
    
  33.   for the view to function properly.
    
  34. 
    
  35. Example
    
  36. -------
    
  37. 
    
  38. The following is a unit test using the request factory::
    
  39. 
    
  40.     from django.contrib.auth.models import AnonymousUser, User
    
  41.     from django.test import RequestFactory, TestCase
    
  42. 
    
  43.     from .views import MyView, my_view
    
  44. 
    
  45.     class SimpleTest(TestCase):
    
  46.         def setUp(self):
    
  47.             # Every test needs access to the request factory.
    
  48.             self.factory = RequestFactory()
    
  49.             self.user = User.objects.create_user(
    
  50.                 username='jacob', email='jacob@…', password='top_secret')
    
  51. 
    
  52.         def test_details(self):
    
  53.             # Create an instance of a GET request.
    
  54.             request = self.factory.get('/customer/details')
    
  55. 
    
  56.             # Recall that middleware are not supported. You can simulate a
    
  57.             # logged-in user by setting request.user manually.
    
  58.             request.user = self.user
    
  59. 
    
  60.             # Or you can simulate an anonymous user by setting request.user to
    
  61.             # an AnonymousUser instance.
    
  62.             request.user = AnonymousUser()
    
  63. 
    
  64.             # Test my_view() as if it were deployed at /customer/details
    
  65.             response = my_view(request)
    
  66.             # Use this syntax for class-based views.
    
  67.             response = MyView.as_view()(request)
    
  68.             self.assertEqual(response.status_code, 200)
    
  69. 
    
  70. AsyncRequestFactory
    
  71. -------------------
    
  72. 
    
  73. .. class:: AsyncRequestFactory
    
  74. 
    
  75. ``RequestFactory`` creates WSGI-like requests. If you want to create ASGI-like
    
  76. requests, including having a correct ASGI ``scope``, you can instead use
    
  77. ``django.test.AsyncRequestFactory``.
    
  78. 
    
  79. This class is directly API-compatible with ``RequestFactory``, with the only
    
  80. difference being that it returns ``ASGIRequest`` instances rather than
    
  81. ``WSGIRequest`` instances. All of its methods are still synchronous callables.
    
  82. 
    
  83. Arbitrary keyword arguments in ``defaults`` are added directly into the ASGI
    
  84. scope.
    
  85. 
    
  86. Testing class-based views
    
  87. =========================
    
  88. 
    
  89. In order to test class-based views outside of the request/response cycle you
    
  90. must ensure that they are configured correctly, by calling
    
  91. :meth:`~django.views.generic.base.View.setup` after instantiation.
    
  92. 
    
  93. For example, assuming the following class-based view:
    
  94. 
    
  95. .. code-block:: python
    
  96.     :caption: ``views.py``
    
  97. 
    
  98.     from django.views.generic import TemplateView
    
  99. 
    
  100. 
    
  101.     class HomeView(TemplateView):
    
  102.         template_name = 'myapp/home.html'
    
  103. 
    
  104.         def get_context_data(self, **kwargs):
    
  105.             kwargs['environment'] = 'Production'
    
  106.             return super().get_context_data(**kwargs)
    
  107. 
    
  108. You may directly test the ``get_context_data()`` method by first instantiating
    
  109. the view, then passing a ``request`` to ``setup()``, before proceeding with
    
  110. your test's code:
    
  111. 
    
  112. .. code-block:: python
    
  113.     :caption: ``tests.py``
    
  114. 
    
  115.     from django.test import RequestFactory, TestCase
    
  116.     from .views import HomeView
    
  117. 
    
  118. 
    
  119.     class HomePageTest(TestCase):
    
  120.         def test_environment_set_in_context(self):
    
  121.             request = RequestFactory().get('/')
    
  122.             view = HomeView()
    
  123.             view.setup(request)
    
  124. 
    
  125.             context = view.get_context_data()
    
  126.             self.assertIn('environment', context)
    
  127. 
    
  128. .. _topics-testing-advanced-multiple-hosts:
    
  129. 
    
  130. Tests and multiple host names
    
  131. =============================
    
  132. 
    
  133. The :setting:`ALLOWED_HOSTS` setting is validated when running tests. This
    
  134. allows the test client to differentiate between internal and external URLs.
    
  135. 
    
  136. Projects that support multitenancy or otherwise alter business logic based on
    
  137. the request's host and use custom host names in tests must include those hosts
    
  138. in :setting:`ALLOWED_HOSTS`.
    
  139. 
    
  140. The first option to do so is to add the hosts to your settings file. For
    
  141. example, the test suite for docs.djangoproject.com includes the following::
    
  142. 
    
  143.     from django.test import TestCase
    
  144. 
    
  145.     class SearchFormTestCase(TestCase):
    
  146.         def test_empty_get(self):
    
  147.             response = self.client.get('/en/dev/search/', HTTP_HOST='docs.djangoproject.dev:8000')
    
  148.             self.assertEqual(response.status_code, 200)
    
  149. 
    
  150. and the settings file includes a list of the domains supported by the project::
    
  151. 
    
  152.     ALLOWED_HOSTS = [
    
  153.         'www.djangoproject.dev',
    
  154.         'docs.djangoproject.dev',
    
  155.         ...
    
  156.     ]
    
  157. 
    
  158. Another option is to add the required hosts to :setting:`ALLOWED_HOSTS` using
    
  159. :meth:`~django.test.override_settings()` or
    
  160. :attr:`~django.test.SimpleTestCase.modify_settings()`. This option may be
    
  161. preferable in standalone apps that can't package their own settings file or
    
  162. for projects where the list of domains is not static (e.g., subdomains for
    
  163. multitenancy). For example, you could write a test for the domain
    
  164. ``http://otherserver/`` as follows::
    
  165. 
    
  166.     from django.test import TestCase, override_settings
    
  167. 
    
  168.     class MultiDomainTestCase(TestCase):
    
  169.         @override_settings(ALLOWED_HOSTS=['otherserver'])
    
  170.         def test_other_domain(self):
    
  171.             response = self.client.get('http://otherserver/foo/bar/')
    
  172. 
    
  173. Disabling :setting:`ALLOWED_HOSTS` checking (``ALLOWED_HOSTS = ['*']``) when
    
  174. running tests prevents the test client from raising a helpful error message if
    
  175. you follow a redirect to an external URL.
    
  176. 
    
  177. .. _topics-testing-advanced-multidb:
    
  178. 
    
  179. Tests and multiple databases
    
  180. ============================
    
  181. 
    
  182. .. _topics-testing-primaryreplica:
    
  183. 
    
  184. Testing primary/replica configurations
    
  185. --------------------------------------
    
  186. 
    
  187. If you're testing a multiple database configuration with primary/replica
    
  188. (referred to as master/slave by some databases) replication, this strategy of
    
  189. creating test databases poses a problem.
    
  190. When the test databases are created, there won't be any replication,
    
  191. and as a result, data created on the primary won't be seen on the
    
  192. replica.
    
  193. 
    
  194. To compensate for this, Django allows you to define that a database is
    
  195. a *test mirror*. Consider the following (simplified) example database
    
  196. configuration::
    
  197. 
    
  198.     DATABASES = {
    
  199.         'default': {
    
  200.             'ENGINE': 'django.db.backends.mysql',
    
  201.             'NAME': 'myproject',
    
  202.             'HOST': 'dbprimary',
    
  203.              # ... plus some other settings
    
  204.         },
    
  205.         'replica': {
    
  206.             'ENGINE': 'django.db.backends.mysql',
    
  207.             'NAME': 'myproject',
    
  208.             'HOST': 'dbreplica',
    
  209.             'TEST': {
    
  210.                 'MIRROR': 'default',
    
  211.             },
    
  212.             # ... plus some other settings
    
  213.         }
    
  214.     }
    
  215. 
    
  216. In this setup, we have two database servers: ``dbprimary``, described
    
  217. by the database alias ``default``, and ``dbreplica`` described by the
    
  218. alias ``replica``. As you might expect, ``dbreplica`` has been configured
    
  219. by the database administrator as a read replica of ``dbprimary``, so in
    
  220. normal activity, any write to ``default`` will appear on ``replica``.
    
  221. 
    
  222. If Django created two independent test databases, this would break any
    
  223. tests that expected replication to occur. However, the ``replica``
    
  224. database has been configured as a test mirror (using the
    
  225. :setting:`MIRROR <TEST_MIRROR>` test setting), indicating that under
    
  226. testing, ``replica`` should be treated as a mirror of ``default``.
    
  227. 
    
  228. When the test environment is configured, a test version of ``replica``
    
  229. will *not* be created. Instead the connection to ``replica``
    
  230. will be redirected to point at ``default``. As a result, writes to
    
  231. ``default`` will appear on ``replica`` -- but because they are actually
    
  232. the same database, not because there is data replication between the
    
  233. two databases. As this depends on transactions, the tests must use
    
  234. :class:`~django.test.TransactionTestCase` instead of
    
  235. :class:`~django.test.TestCase`.
    
  236. 
    
  237. .. _topics-testing-creation-dependencies:
    
  238. 
    
  239. Controlling creation order for test databases
    
  240. ---------------------------------------------
    
  241. 
    
  242. By default, Django will assume all databases depend on the ``default``
    
  243. database and therefore always create the ``default`` database first.
    
  244. However, no guarantees are made on the creation order of any other
    
  245. databases in your test setup.
    
  246. 
    
  247. If your database configuration requires a specific creation order, you
    
  248. can specify the dependencies that exist using the :setting:`DEPENDENCIES
    
  249. <TEST_DEPENDENCIES>` test setting. Consider the following (simplified)
    
  250. example database configuration::
    
  251. 
    
  252.     DATABASES = {
    
  253.         'default': {
    
  254.             # ... db settings
    
  255.             'TEST': {
    
  256.                 'DEPENDENCIES': ['diamonds'],
    
  257.             },
    
  258.         },
    
  259.         'diamonds': {
    
  260.             # ... db settings
    
  261.             'TEST': {
    
  262.                 'DEPENDENCIES': [],
    
  263.             },
    
  264.         },
    
  265.         'clubs': {
    
  266.             # ... db settings
    
  267.             'TEST': {
    
  268.                 'DEPENDENCIES': ['diamonds'],
    
  269.             },
    
  270.         },
    
  271.         'spades': {
    
  272.             # ... db settings
    
  273.             'TEST': {
    
  274.                 'DEPENDENCIES': ['diamonds', 'hearts'],
    
  275.             },
    
  276.         },
    
  277.         'hearts': {
    
  278.             # ... db settings
    
  279.             'TEST': {
    
  280.                 'DEPENDENCIES': ['diamonds', 'clubs'],
    
  281.             },
    
  282.         }
    
  283.     }
    
  284. 
    
  285. Under this configuration, the ``diamonds`` database will be created first,
    
  286. as it is the only database alias without dependencies. The ``default`` and
    
  287. ``clubs`` alias will be created next (although the order of creation of this
    
  288. pair is not guaranteed), then ``hearts``, and finally ``spades``.
    
  289. 
    
  290. If there are any circular dependencies in the :setting:`DEPENDENCIES
    
  291. <TEST_DEPENDENCIES>` definition, an
    
  292. :exc:`~django.core.exceptions.ImproperlyConfigured` exception will be raised.
    
  293. 
    
  294. Advanced features of ``TransactionTestCase``
    
  295. ============================================
    
  296. 
    
  297. .. attribute:: TransactionTestCase.available_apps
    
  298. 
    
  299.     .. warning::
    
  300. 
    
  301.         This attribute is a private API. It may be changed or removed without
    
  302.         a deprecation period in the future, for instance to accommodate changes
    
  303.         in application loading.
    
  304. 
    
  305.         It's used to optimize Django's own test suite, which contains hundreds
    
  306.         of models but no relations between models in different applications.
    
  307. 
    
  308.     By default, ``available_apps`` is set to ``None``. After each test, Django
    
  309.     calls :djadmin:`flush` to reset the database state. This empties all tables
    
  310.     and emits the :data:`~django.db.models.signals.post_migrate` signal, which
    
  311.     recreates one content type and four permissions for each model. This
    
  312.     operation gets expensive proportionally to the number of models.
    
  313. 
    
  314.     Setting ``available_apps`` to a list of applications instructs Django to
    
  315.     behave as if only the models from these applications were available. The
    
  316.     behavior of ``TransactionTestCase`` changes as follows:
    
  317. 
    
  318.     - :data:`~django.db.models.signals.post_migrate` is fired before each
    
  319.       test to create the content types and permissions for each model in
    
  320.       available apps, in case they're missing.
    
  321.     - After each test, Django empties only tables corresponding to models in
    
  322.       available apps. However, at the database level, truncation may cascade to
    
  323.       related models in unavailable apps. Furthermore
    
  324.       :data:`~django.db.models.signals.post_migrate` isn't fired; it will be
    
  325.       fired by the next ``TransactionTestCase``, after the correct set of
    
  326.       applications is selected.
    
  327. 
    
  328.     Since the database isn't fully flushed, if a test creates instances of
    
  329.     models not included in ``available_apps``, they will leak and they may
    
  330.     cause unrelated tests to fail. Be careful with tests that use sessions;
    
  331.     the default session engine stores them in the database.
    
  332. 
    
  333.     Since :data:`~django.db.models.signals.post_migrate` isn't emitted after
    
  334.     flushing the database, its state after a ``TransactionTestCase`` isn't the
    
  335.     same as after a ``TestCase``: it's missing the rows created by listeners
    
  336.     to :data:`~django.db.models.signals.post_migrate`. Considering the
    
  337.     :ref:`order in which tests are executed <order-of-tests>`, this isn't an
    
  338.     issue, provided either all ``TransactionTestCase`` in a given test suite
    
  339.     declare ``available_apps``, or none of them.
    
  340. 
    
  341.     ``available_apps`` is mandatory in Django's own test suite.
    
  342. 
    
  343. .. attribute:: TransactionTestCase.reset_sequences
    
  344. 
    
  345.     Setting ``reset_sequences = True`` on a ``TransactionTestCase`` will make
    
  346.     sure sequences are always reset before the test run::
    
  347. 
    
  348.         class TestsThatDependsOnPrimaryKeySequences(TransactionTestCase):
    
  349.             reset_sequences = True
    
  350. 
    
  351.             def test_animal_pk(self):
    
  352.                 lion = Animal.objects.create(name="lion", sound="roar")
    
  353.                 # lion.pk is guaranteed to always be 1
    
  354.                 self.assertEqual(lion.pk, 1)
    
  355. 
    
  356.     Unless you are explicitly testing primary keys sequence numbers, it is
    
  357.     recommended that you do not hard code primary key values in tests.
    
  358. 
    
  359.     Using ``reset_sequences = True`` will slow down the test, since the primary
    
  360.     key reset is a relatively expensive database operation.
    
  361. 
    
  362. .. _topics-testing-enforce-run-sequentially:
    
  363. 
    
  364. Enforce running test classes sequentially
    
  365. =========================================
    
  366. 
    
  367. If you have test classes that cannot be run in parallel (e.g. because they
    
  368. share a common resource), you can use ``django.test.testcases.SerializeMixin``
    
  369. to run them sequentially. This mixin uses a filesystem ``lockfile``.
    
  370. 
    
  371. For example, you can use ``__file__`` to determine that all test classes in the
    
  372. same file that inherit from ``SerializeMixin`` will run sequentially::
    
  373. 
    
  374.     import os
    
  375. 
    
  376.     from django.test import TestCase
    
  377.     from django.test.testcases import SerializeMixin
    
  378. 
    
  379.     class ImageTestCaseMixin(SerializeMixin):
    
  380.         lockfile = __file__
    
  381. 
    
  382.         def setUp(self):
    
  383.             self.filename = os.path.join(temp_storage_dir, 'my_file.png')
    
  384.             self.file = create_file(self.filename)
    
  385. 
    
  386.     class RemoveImageTests(ImageTestCaseMixin, TestCase):
    
  387.         def test_remove_image(self):
    
  388.             os.remove(self.filename)
    
  389.             self.assertFalse(os.path.exists(self.filename))
    
  390. 
    
  391.     class ResizeImageTests(ImageTestCaseMixin, TestCase):
    
  392.         def test_resize_image(self):
    
  393.             resize_image(self.file, (48, 48))
    
  394.             self.assertEqual(get_image_size(self.file), (48, 48))
    
  395. 
    
  396. .. _testing-reusable-applications:
    
  397. 
    
  398. Using the Django test runner to test reusable applications
    
  399. ==========================================================
    
  400. 
    
  401. If you are writing a :doc:`reusable application </intro/reusable-apps>`
    
  402. you may want to use the Django test runner to run your own test suite
    
  403. and thus benefit from the Django testing infrastructure.
    
  404. 
    
  405. A common practice is a *tests* directory next to the application code, with the
    
  406. following structure::
    
  407. 
    
  408.     runtests.py
    
  409.     polls/
    
  410.         __init__.py
    
  411.         models.py
    
  412.         ...
    
  413.     tests/
    
  414.         __init__.py
    
  415.         models.py
    
  416.         test_settings.py
    
  417.         tests.py
    
  418. 
    
  419. Let's take a look inside a couple of those files:
    
  420. 
    
  421. .. code-block:: python
    
  422.     :caption: ``runtests.py``
    
  423. 
    
  424.     #!/usr/bin/env python
    
  425.     import os
    
  426.     import sys
    
  427. 
    
  428.     import django
    
  429.     from django.conf import settings
    
  430.     from django.test.utils import get_runner
    
  431. 
    
  432.     if __name__ == "__main__":
    
  433.         os.environ['DJANGO_SETTINGS_MODULE'] = 'tests.test_settings'
    
  434.         django.setup()
    
  435.         TestRunner = get_runner(settings)
    
  436.         test_runner = TestRunner()
    
  437.         failures = test_runner.run_tests(["tests"])
    
  438.         sys.exit(bool(failures))
    
  439. 
    
  440. 
    
  441. This is the script that you invoke to run the test suite. It sets up the
    
  442. Django environment, creates the test database and runs the tests.
    
  443. 
    
  444. For the sake of clarity, this example contains only the bare minimum
    
  445. necessary to use the Django test runner. You may want to add
    
  446. command-line options for controlling verbosity, passing in specific test
    
  447. labels to run, etc.
    
  448. 
    
  449. .. code-block:: python
    
  450.     :caption: ``tests/test_settings.py``
    
  451. 
    
  452.     SECRET_KEY = 'fake-key'
    
  453.     INSTALLED_APPS = [
    
  454.         "tests",
    
  455.     ]
    
  456. 
    
  457. This file contains the :doc:`Django settings </topics/settings>`
    
  458. required to run your app's tests.
    
  459. 
    
  460. Again, this is a minimal example; your tests may require additional
    
  461. settings to run.
    
  462. 
    
  463. Since the *tests* package is included in :setting:`INSTALLED_APPS` when
    
  464. running your tests, you can define test-only models in its ``models.py``
    
  465. file.
    
  466. 
    
  467. 
    
  468. .. _other-testing-frameworks:
    
  469. 
    
  470. Using different testing frameworks
    
  471. ==================================
    
  472. 
    
  473. Clearly, :mod:`unittest` is not the only Python testing framework. While Django
    
  474. doesn't provide explicit support for alternative frameworks, it does provide a
    
  475. way to invoke tests constructed for an alternative framework as if they were
    
  476. normal Django tests.
    
  477. 
    
  478. When you run ``./manage.py test``, Django looks at the :setting:`TEST_RUNNER`
    
  479. setting to determine what to do. By default, :setting:`TEST_RUNNER` points to
    
  480. ``'django.test.runner.DiscoverRunner'``. This class defines the default Django
    
  481. testing behavior. This behavior involves:
    
  482. 
    
  483. #. Performing global pre-test setup.
    
  484. 
    
  485. #. Looking for tests in any file below the current directory whose name matches
    
  486.    the pattern ``test*.py``.
    
  487. 
    
  488. #. Creating the test databases.
    
  489. 
    
  490. #. Running ``migrate`` to install models and initial data into the test
    
  491.    databases.
    
  492. 
    
  493. #. Running the :doc:`system checks </topics/checks>`.
    
  494. 
    
  495. #. Running the tests that were found.
    
  496. 
    
  497. #. Destroying the test databases.
    
  498. 
    
  499. #. Performing global post-test teardown.
    
  500. 
    
  501. If you define your own test runner class and point :setting:`TEST_RUNNER` at
    
  502. that class, Django will execute your test runner whenever you run
    
  503. ``./manage.py test``. In this way, it is possible to use any test framework
    
  504. that can be executed from Python code, or to modify the Django test execution
    
  505. process to satisfy whatever testing requirements you may have.
    
  506. 
    
  507. .. _topics-testing-test_runner:
    
  508. 
    
  509. Defining a test runner
    
  510. ----------------------
    
  511. 
    
  512. .. currentmodule:: django.test.runner
    
  513. 
    
  514. A test runner is a class defining a ``run_tests()`` method. Django ships
    
  515. with a ``DiscoverRunner`` class that defines the default Django testing
    
  516. behavior. This class defines the ``run_tests()`` entry point, plus a
    
  517. selection of other methods that are used by ``run_tests()`` to set up, execute
    
  518. and tear down the test suite.
    
  519. 
    
  520. .. class:: DiscoverRunner(pattern='test*.py', top_level=None, verbosity=1, interactive=True, failfast=False, keepdb=False, reverse=False, debug_mode=False, debug_sql=False, parallel=0, tags=None, exclude_tags=None, test_name_patterns=None, pdb=False, buffer=False, enable_faulthandler=True, timing=True, shuffle=False, logger=None, **kwargs)
    
  521. 
    
  522.     ``DiscoverRunner`` will search for tests in any file matching ``pattern``.
    
  523. 
    
  524.     ``top_level`` can be used to specify the directory containing your
    
  525.     top-level Python modules. Usually Django can figure this out automatically,
    
  526.     so it's not necessary to specify this option. If specified, it should
    
  527.     generally be the directory containing your ``manage.py`` file.
    
  528. 
    
  529.     ``verbosity`` determines the amount of notification and debug information
    
  530.     that will be printed to the console; ``0`` is no output, ``1`` is normal
    
  531.     output, and ``2`` is verbose output.
    
  532. 
    
  533.     If ``interactive`` is ``True``, the test suite has permission to ask the
    
  534.     user for instructions when the test suite is executed. An example of this
    
  535.     behavior would be asking for permission to delete an existing test
    
  536.     database. If ``interactive`` is ``False``, the test suite must be able to
    
  537.     run without any manual intervention.
    
  538. 
    
  539.     If ``failfast`` is ``True``, the test suite will stop running after the
    
  540.     first test failure is detected.
    
  541. 
    
  542.     If ``keepdb`` is ``True``, the test suite will use the existing database,
    
  543.     or create one if necessary. If ``False``, a new database will be created,
    
  544.     prompting the user to remove the existing one, if present.
    
  545. 
    
  546.     If ``reverse`` is ``True``, test cases will be executed in the opposite
    
  547.     order. This could be useful to debug tests that aren't properly isolated
    
  548.     and have side effects. :ref:`Grouping by test class <order-of-tests>` is
    
  549.     preserved when using this option. This option can be used in conjunction
    
  550.     with ``--shuffle`` to reverse the order for a particular random seed.
    
  551. 
    
  552.     ``debug_mode`` specifies what the :setting:`DEBUG` setting should be
    
  553.     set to prior to running tests.
    
  554. 
    
  555.     ``parallel`` specifies the number of processes.  If ``parallel`` is greater
    
  556.     than ``1``, the test suite will run in ``parallel`` processes. If there are
    
  557.     fewer test cases than configured processes, Django will reduce the number
    
  558.     of processes accordingly. Each process gets its own database. This option
    
  559.     requires the third-party ``tblib`` package to display tracebacks correctly.
    
  560. 
    
  561.     ``tags`` can be used to specify a set of :ref:`tags for filtering tests
    
  562.     <topics-tagging-tests>`. May be combined with ``exclude_tags``.
    
  563. 
    
  564.     ``exclude_tags`` can be used to specify a set of
    
  565.     :ref:`tags for excluding tests <topics-tagging-tests>`. May be combined
    
  566.     with ``tags``.
    
  567. 
    
  568.     If ``debug_sql`` is ``True``, failing test cases will output SQL queries
    
  569.     logged to the :ref:`django.db.backends logger <django-db-logger>` as well
    
  570.     as the traceback. If ``verbosity`` is ``2``, then queries in all tests are
    
  571.     output.
    
  572. 
    
  573.     ``test_name_patterns`` can be used to specify a set of patterns for
    
  574.     filtering test methods and classes by their names.
    
  575. 
    
  576.     If ``pdb`` is ``True``, a debugger (``pdb`` or ``ipdb``) will be spawned at
    
  577.     each test error or failure.
    
  578. 
    
  579.     If ``buffer`` is ``True``, outputs from passing tests will be discarded.
    
  580. 
    
  581.     If ``enable_faulthandler`` is ``True``, :py:mod:`faulthandler` will be
    
  582.     enabled.
    
  583. 
    
  584.     If ``timing`` is ``True``, test timings, including database setup and total
    
  585.     run time, will be shown.
    
  586. 
    
  587.     If ``shuffle`` is an integer, test cases will be shuffled in a random order
    
  588.     prior to execution, using the integer as a random seed. If ``shuffle`` is
    
  589.     ``None``, the seed will be generated randomly. In both cases, the seed will
    
  590.     be logged and set to ``self.shuffle_seed`` prior to running tests. This
    
  591.     option can be used to help detect tests that aren't properly isolated.
    
  592.     :ref:`Grouping by test class <order-of-tests>` is preserved when using this
    
  593.     option.
    
  594. 
    
  595.     ``logger`` can be used to pass a Python :py:ref:`Logger object <logger>`.
    
  596.     If provided, the logger will be used to log messages instead of printing to
    
  597.     the console. The logger object will respect its logging level rather than
    
  598.     the ``verbosity``.
    
  599. 
    
  600.     Django may, from time to time, extend the capabilities of the test runner
    
  601.     by adding new arguments. The ``**kwargs`` declaration allows for this
    
  602.     expansion. If you subclass ``DiscoverRunner`` or write your own test
    
  603.     runner, ensure it accepts ``**kwargs``.
    
  604. 
    
  605.     Your test runner may also define additional command-line options.
    
  606.     Create or override an ``add_arguments(cls, parser)`` class method and add
    
  607.     custom arguments by calling ``parser.add_argument()`` inside the method, so
    
  608.     that the :djadmin:`test` command will be able to use those arguments.
    
  609. 
    
  610.     .. versionadded:: 4.0
    
  611. 
    
  612.         The ``logger`` and ``shuffle`` arguments were added.
    
  613. 
    
  614. Attributes
    
  615. ~~~~~~~~~~
    
  616. 
    
  617. .. attribute:: DiscoverRunner.test_suite
    
  618. 
    
  619.     The class used to build the test suite. By default it is set to
    
  620.     ``unittest.TestSuite``. This can be overridden if you wish to implement
    
  621.     different logic for collecting tests.
    
  622. 
    
  623. .. attribute:: DiscoverRunner.test_runner
    
  624. 
    
  625.     This is the class of the low-level test runner which is used to execute
    
  626.     the individual tests and format the results. By default it is set to
    
  627.     ``unittest.TextTestRunner``. Despite the unfortunate similarity in
    
  628.     naming conventions, this is not the same type of class as
    
  629.     ``DiscoverRunner``, which covers a broader set of responsibilities. You
    
  630.     can override this attribute to modify the way tests are run and reported.
    
  631. 
    
  632. .. attribute:: DiscoverRunner.test_loader
    
  633. 
    
  634.     This is the class that loads tests, whether from TestCases or modules or
    
  635.     otherwise and bundles them into test suites for the runner to execute.
    
  636.     By default it is set to ``unittest.defaultTestLoader``. You can override
    
  637.     this attribute if your tests are going to be loaded in unusual ways.
    
  638. 
    
  639. Methods
    
  640. ~~~~~~~
    
  641. 
    
  642. .. method:: DiscoverRunner.run_tests(test_labels, **kwargs)
    
  643. 
    
  644.     Run the test suite.
    
  645. 
    
  646.     ``test_labels`` allows you to specify which tests to run and supports
    
  647.     several formats (see :meth:`DiscoverRunner.build_suite` for a list of
    
  648.     supported formats).
    
  649. 
    
  650.     .. deprecated:: 4.0
    
  651. 
    
  652.         ``extra_tests`` is a list of extra ``TestCase`` instances to add to the
    
  653.         suite that is executed by the test runner. These extra tests are run in
    
  654.         addition to those discovered in the modules listed in ``test_labels``.
    
  655. 
    
  656.     This method should return the number of tests that failed.
    
  657. 
    
  658. .. classmethod:: DiscoverRunner.add_arguments(parser)
    
  659. 
    
  660.     Override this class method to add custom arguments accepted by the
    
  661.     :djadmin:`test` management command. See
    
  662.     :py:meth:`argparse.ArgumentParser.add_argument()` for details about adding
    
  663.     arguments to a parser.
    
  664. 
    
  665. .. method:: DiscoverRunner.setup_test_environment(**kwargs)
    
  666. 
    
  667.     Sets up the test environment by calling
    
  668.     :func:`~django.test.utils.setup_test_environment` and setting
    
  669.     :setting:`DEBUG` to ``self.debug_mode`` (defaults to ``False``).
    
  670. 
    
  671. .. method:: DiscoverRunner.build_suite(test_labels=None, **kwargs)
    
  672. 
    
  673.     Constructs a test suite that matches the test labels provided.
    
  674. 
    
  675.     ``test_labels`` is a list of strings describing the tests to be run. A test
    
  676.     label can take one of four forms:
    
  677. 
    
  678.     * ``path.to.test_module.TestCase.test_method`` -- Run a single test method
    
  679.       in a test case.
    
  680.     * ``path.to.test_module.TestCase`` -- Run all the test methods in a test
    
  681.       case.
    
  682.     * ``path.to.module`` -- Search for and run all tests in the named Python
    
  683.       package or module.
    
  684.     * ``path/to/directory`` -- Search for and run all tests below the named
    
  685.       directory.
    
  686. 
    
  687.     If ``test_labels`` has a value of ``None``, the test runner will search for
    
  688.     tests in all files below the current directory whose names match its
    
  689.     ``pattern`` (see above).
    
  690. 
    
  691.     .. deprecated:: 4.0
    
  692. 
    
  693.         ``extra_tests`` is a list of extra ``TestCase`` instances to add to the
    
  694.         suite that is executed by the test runner. These extra tests are run in
    
  695.         addition to those discovered in the modules listed in ``test_labels``.
    
  696. 
    
  697.     Returns a ``TestSuite`` instance ready to be run.
    
  698. 
    
  699. .. method:: DiscoverRunner.setup_databases(**kwargs)
    
  700. 
    
  701.     Creates the test databases by calling
    
  702.     :func:`~django.test.utils.setup_databases`.
    
  703. 
    
  704. .. method:: DiscoverRunner.run_checks(databases)
    
  705. 
    
  706.     Runs the :doc:`system checks </topics/checks>` on the test ``databases``.
    
  707. 
    
  708. .. method:: DiscoverRunner.run_suite(suite, **kwargs)
    
  709. 
    
  710.     Runs the test suite.
    
  711. 
    
  712.     Returns the result produced by the running the test suite.
    
  713. 
    
  714. .. method:: DiscoverRunner.get_test_runner_kwargs()
    
  715. 
    
  716.     Returns the keyword arguments to instantiate the
    
  717.     ``DiscoverRunner.test_runner`` with.
    
  718. 
    
  719. .. method:: DiscoverRunner.teardown_databases(old_config, **kwargs)
    
  720. 
    
  721.     Destroys the test databases, restoring pre-test conditions by calling
    
  722.     :func:`~django.test.utils.teardown_databases`.
    
  723. 
    
  724. .. method:: DiscoverRunner.teardown_test_environment(**kwargs)
    
  725. 
    
  726.     Restores the pre-test environment.
    
  727. 
    
  728. .. method:: DiscoverRunner.suite_result(suite, result, **kwargs)
    
  729. 
    
  730.     Computes and returns a return code based on a test suite, and the result
    
  731.     from that test suite.
    
  732. 
    
  733. .. method:: DiscoverRunner.log(msg, level=None)
    
  734. 
    
  735.     .. versionadded:: 4.0
    
  736. 
    
  737.     If a ``logger`` is set, logs the message at the given integer
    
  738.     `logging level`_ (e.g. ``logging.DEBUG``, ``logging.INFO``, or
    
  739.     ``logging.WARNING``). Otherwise, the message is printed to the console,
    
  740.     respecting the current ``verbosity``. For example, no message will be
    
  741.     printed if the ``verbosity`` is 0, ``INFO`` and above will be printed if
    
  742.     the ``verbosity`` is at least 1, and ``DEBUG`` will be printed if it is at
    
  743.     least 2. The ``level`` defaults to ``logging.INFO``.
    
  744. 
    
  745. .. _`logging level`: https://docs.python.org/3/library/logging.html#levels
    
  746. 
    
  747. Testing utilities
    
  748. -----------------
    
  749. 
    
  750. ``django.test.utils``
    
  751. ~~~~~~~~~~~~~~~~~~~~~
    
  752. 
    
  753. .. module:: django.test.utils
    
  754.    :synopsis: Helpers to write custom test runners.
    
  755. 
    
  756. To assist in the creation of your own test runner, Django provides a number of
    
  757. utility methods in the ``django.test.utils`` module.
    
  758. 
    
  759. .. function:: setup_test_environment(debug=None)
    
  760. 
    
  761.     Performs global pre-test setup, such as installing instrumentation for the
    
  762.     template rendering system and setting up the dummy email outbox.
    
  763. 
    
  764.     If ``debug`` isn't ``None``, the :setting:`DEBUG` setting is updated to its
    
  765.     value.
    
  766. 
    
  767. .. function:: teardown_test_environment()
    
  768. 
    
  769.     Performs global post-test teardown, such as removing instrumentation from
    
  770.     the template system and restoring normal email services.
    
  771. 
    
  772. .. function:: setup_databases(verbosity, interactive, *, time_keeper=None, keepdb=False, debug_sql=False, parallel=0, aliases=None, serialized_aliases=None, **kwargs)
    
  773. 
    
  774.     Creates the test databases.
    
  775. 
    
  776.     Returns a data structure that provides enough detail to undo the changes
    
  777.     that have been made. This data will be provided to the
    
  778.     :func:`teardown_databases` function at the conclusion of testing.
    
  779. 
    
  780.     The ``aliases`` argument determines which :setting:`DATABASES` aliases test
    
  781.     databases should be set up for. If it's not provided, it defaults to all of
    
  782.     :setting:`DATABASES` aliases.
    
  783. 
    
  784.     The ``serialized_aliases`` argument determines what subset of ``aliases``
    
  785.     test databases should have their state serialized to allow usage of the
    
  786.     :ref:`serialized_rollback <test-case-serialized-rollback>` feature. If
    
  787.     it's not provided, it defaults to ``aliases``.
    
  788. 
    
  789.     .. versionchanged:: 4.0
    
  790. 
    
  791.         The ``serialized_aliases`` kwarg was added.
    
  792. 
    
  793. .. function:: teardown_databases(old_config, parallel=0, keepdb=False)
    
  794. 
    
  795.     Destroys the test databases, restoring pre-test conditions.
    
  796. 
    
  797.     ``old_config`` is a data structure defining the changes in the database
    
  798.     configuration that need to be reversed. It's the return value of the
    
  799.     :meth:`setup_databases` method.
    
  800. 
    
  801. ``django.db.connection.creation``
    
  802. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    
  803. 
    
  804. .. currentmodule:: django.db.connection.creation
    
  805. 
    
  806. The creation module of the database backend also provides some utilities that
    
  807. can be useful during testing.
    
  808. 
    
  809. .. function:: create_test_db(verbosity=1, autoclobber=False, serialize=True, keepdb=False)
    
  810. 
    
  811.     Creates a new test database and runs ``migrate`` against it.
    
  812. 
    
  813.     ``verbosity`` has the same behavior as in ``run_tests()``.
    
  814. 
    
  815.     ``autoclobber`` describes the behavior that will occur if a
    
  816.     database with the same name as the test database is discovered:
    
  817. 
    
  818.     * If ``autoclobber`` is ``False``, the user will be asked to
    
  819.       approve destroying the existing database. ``sys.exit`` is
    
  820.       called if the user does not approve.
    
  821. 
    
  822.     * If ``autoclobber`` is ``True``, the database will be destroyed
    
  823.       without consulting the user.
    
  824. 
    
  825.     ``serialize`` determines if Django serializes the database into an
    
  826.     in-memory JSON string before running tests (used to restore the database
    
  827.     state between tests if you don't have transactions). You can set this to
    
  828.     ``False`` to speed up creation time if you don't have any test classes
    
  829.     with :ref:`serialized_rollback=True <test-case-serialized-rollback>`.
    
  830. 
    
  831.     If you are using the default test runner, you can control this with the
    
  832.     the :setting:`SERIALIZE <TEST_SERIALIZE>` entry in the :setting:`TEST
    
  833.     <DATABASE-TEST>` dictionary.
    
  834. 
    
  835.     ``keepdb`` determines if the test run should use an existing
    
  836.     database, or create a new one. If ``True``, the existing
    
  837.     database will be used, or created if not present. If ``False``,
    
  838.     a new database will be created, prompting the user to remove
    
  839.     the existing one, if present.
    
  840. 
    
  841.     Returns the name of the test database that it created.
    
  842. 
    
  843.     ``create_test_db()`` has the side effect of modifying the value of
    
  844.     :setting:`NAME` in :setting:`DATABASES` to match the name of the test
    
  845.     database.
    
  846. 
    
  847. .. function:: destroy_test_db(old_database_name, verbosity=1, keepdb=False)
    
  848. 
    
  849.     Destroys the database whose name is the value of :setting:`NAME` in
    
  850.     :setting:`DATABASES`, and sets :setting:`NAME` to the value of
    
  851.     ``old_database_name``.
    
  852. 
    
  853.     The ``verbosity`` argument has the same behavior as for
    
  854.     :class:`~django.test.runner.DiscoverRunner`.
    
  855. 
    
  856.     If the ``keepdb`` argument is ``True``, then the connection to the
    
  857.     database will be closed, but the database will not be destroyed.
    
  858. 
    
  859. .. _topics-testing-code-coverage:
    
  860. 
    
  861. Integration with ``coverage.py``
    
  862. ================================
    
  863. 
    
  864. Code coverage describes how much source code has been tested. It shows which
    
  865. parts of your code are being exercised by tests and which are not. It's an
    
  866. important part of testing applications, so it's strongly recommended to check
    
  867. the coverage of your tests.
    
  868. 
    
  869. Django can be easily integrated with `coverage.py`_, a tool for measuring code
    
  870. coverage of Python programs. First, `install coverage.py`_. Next, run the
    
  871. following from your project folder containing ``manage.py``::
    
  872. 
    
  873.    coverage run --source='.' manage.py test myapp
    
  874. 
    
  875. This runs your tests and collects coverage data of the executed files in your
    
  876. project. You can see a report of this data by typing following command::
    
  877. 
    
  878.    coverage report
    
  879. 
    
  880. Note that some Django code was executed while running tests, but it is not
    
  881. listed here because of the ``source`` flag passed to the previous command.
    
  882. 
    
  883. For more options like annotated HTML listings detailing missed lines, see the
    
  884. `coverage.py`_ docs.
    
  885. 
    
  886. .. _coverage.py: https://coverage.readthedocs.io/
    
  887. .. _install coverage.py: https://pypi.org/project/coverage/