advanced.txt 33 KB

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