1. =========================
    
  2. Writing and running tests
    
  3. =========================
    
  4. 
    
  5. .. module:: django.test
    
  6.    :synopsis: Testing tools for Django applications.
    
  7. 
    
  8. .. seealso::
    
  9. 
    
  10.     The :doc:`testing tutorial </intro/tutorial05>`, the :doc:`testing tools
    
  11.     reference </topics/testing/tools>`, and the :doc:`advanced testing topics
    
  12.     </topics/testing/advanced>`.
    
  13. 
    
  14. This document is split into two primary sections. First, we explain how to write
    
  15. tests with Django. Then, we explain how to run them.
    
  16. 
    
  17. Writing tests
    
  18. =============
    
  19. 
    
  20. Django's unit tests use a Python standard library module: :mod:`unittest`. This
    
  21. module defines tests using a class-based approach.
    
  22. 
    
  23. Here is an example which subclasses from :class:`django.test.TestCase`,
    
  24. which is a subclass of :class:`unittest.TestCase` that runs each test inside a
    
  25. transaction to provide isolation::
    
  26. 
    
  27.     from django.test import TestCase
    
  28.     from myapp.models import Animal
    
  29. 
    
  30.     class AnimalTestCase(TestCase):
    
  31.         def setUp(self):
    
  32.             Animal.objects.create(name="lion", sound="roar")
    
  33.             Animal.objects.create(name="cat", sound="meow")
    
  34. 
    
  35.         def test_animals_can_speak(self):
    
  36.             """Animals that can speak are correctly identified"""
    
  37.             lion = Animal.objects.get(name="lion")
    
  38.             cat = Animal.objects.get(name="cat")
    
  39.             self.assertEqual(lion.speak(), 'The lion says "roar"')
    
  40.             self.assertEqual(cat.speak(), 'The cat says "meow"')
    
  41. 
    
  42. When you :ref:`run your tests <running-tests>`, the default behavior of the
    
  43. test utility is to find all the test cases (that is, subclasses of
    
  44. :class:`unittest.TestCase`) in any file whose name begins with ``test``,
    
  45. automatically build a test suite out of those test cases, and run that suite.
    
  46. 
    
  47. For more details about :mod:`unittest`, see the Python documentation.
    
  48. 
    
  49. .. admonition:: Where should the tests live?
    
  50. 
    
  51.     The default :djadmin:`startapp` template creates a ``tests.py`` file in the
    
  52.     new application. This might be fine if you only have a few tests, but as
    
  53.     your test suite grows you'll likely want to restructure it into a tests
    
  54.     package so you can split your tests into different submodules such as
    
  55.     ``test_models.py``, ``test_views.py``, ``test_forms.py``, etc. Feel free to
    
  56.     pick whatever organizational scheme you like.
    
  57. 
    
  58.     See also :ref:`testing-reusable-applications`.
    
  59. 
    
  60. .. warning::
    
  61. 
    
  62.     If your tests rely on database access such as creating or querying models,
    
  63.     be sure to create your test classes as subclasses of
    
  64.     :class:`django.test.TestCase` rather than :class:`unittest.TestCase`.
    
  65. 
    
  66.     Using :class:`unittest.TestCase` avoids the cost of running each test in a
    
  67.     transaction and flushing the database, but if your tests interact with
    
  68.     the database their behavior will vary based on the order that the test
    
  69.     runner executes them. This can lead to unit tests that pass when run in
    
  70.     isolation but fail when run in a suite.
    
  71. 
    
  72. .. _running-tests:
    
  73. 
    
  74. Running tests
    
  75. =============
    
  76. 
    
  77. Once you've written tests, run them using the :djadmin:`test` command of
    
  78. your project's ``manage.py`` utility::
    
  79. 
    
  80.     $ ./manage.py test
    
  81. 
    
  82. Test discovery is based on the unittest module's :py:ref:`built-in test
    
  83. discovery <unittest-test-discovery>`.  By default, this will discover tests in
    
  84. any file named ``test*.py`` under the current working directory.
    
  85. 
    
  86. You can specify particular tests to run by supplying any number of "test
    
  87. labels" to ``./manage.py test``. Each test label can be a full Python dotted
    
  88. path to a package, module, ``TestCase`` subclass, or test method. For instance::
    
  89. 
    
  90.     # Run all the tests in the animals.tests module
    
  91.     $ ./manage.py test animals.tests
    
  92. 
    
  93.     # Run all the tests found within the 'animals' package
    
  94.     $ ./manage.py test animals
    
  95. 
    
  96.     # Run just one test case
    
  97.     $ ./manage.py test animals.tests.AnimalTestCase
    
  98. 
    
  99.     # Run just one test method
    
  100.     $ ./manage.py test animals.tests.AnimalTestCase.test_animals_can_speak
    
  101. 
    
  102. You can also provide a path to a directory to discover tests below that
    
  103. directory::
    
  104. 
    
  105.     $ ./manage.py test animals/
    
  106. 
    
  107. You can specify a custom filename pattern match using the ``-p`` (or
    
  108. ``--pattern``) option, if your test files are named differently from the
    
  109. ``test*.py`` pattern::
    
  110. 
    
  111.     $ ./manage.py test --pattern="tests_*.py"
    
  112. 
    
  113. If you press ``Ctrl-C`` while the tests are running, the test runner will
    
  114. wait for the currently running test to complete and then exit gracefully.
    
  115. During a graceful exit the test runner will output details of any test
    
  116. failures, report on how many tests were run and how many errors and failures
    
  117. were encountered, and destroy any test databases as usual. Thus pressing
    
  118. ``Ctrl-C`` can be very useful if you forget to pass the :option:`--failfast
    
  119. <test --failfast>` option, notice that some tests are unexpectedly failing and
    
  120. want to get details on the failures without waiting for the full test run to
    
  121. complete.
    
  122. 
    
  123. If you do not want to wait for the currently running test to finish, you
    
  124. can press ``Ctrl-C`` a second time and the test run will halt immediately,
    
  125. but not gracefully. No details of the tests run before the interruption will
    
  126. be reported, and any test databases created by the run will not be destroyed.
    
  127. 
    
  128. .. admonition:: Test with warnings enabled
    
  129. 
    
  130.     It's a good idea to run your tests with Python warnings enabled:
    
  131.     ``python -Wa manage.py test``. The ``-Wa`` flag tells Python to
    
  132.     display deprecation warnings. Django, like many other Python libraries,
    
  133.     uses these warnings to flag when features are going away. It also might
    
  134.     flag areas in your code that aren't strictly wrong but could benefit
    
  135.     from a better implementation.
    
  136. 
    
  137. 
    
  138. .. _the-test-database:
    
  139. 
    
  140. The test database
    
  141. -----------------
    
  142. 
    
  143. Tests that require a database (namely, model tests) will not use your "real"
    
  144. (production) database. Separate, blank databases are created for the tests.
    
  145. 
    
  146. Regardless of whether the tests pass or fail, the test databases are destroyed
    
  147. when all the tests have been executed.
    
  148. 
    
  149. You can prevent the test databases from being destroyed by using the
    
  150. :option:`test --keepdb` option. This will preserve the test database between
    
  151. runs. If the database does not exist, it will first be created. Any migrations
    
  152. will also be applied in order to keep it up to date.
    
  153. 
    
  154. As described in the previous section, if a test run is forcefully interrupted,
    
  155. the test database may not be destroyed. On the next run, you'll be asked
    
  156. whether you want to reuse or destroy the database. Use the :option:`test
    
  157. --noinput` option to suppress that prompt and automatically destroy the
    
  158. database. This can be useful when running tests on a continuous integration
    
  159. server where tests may be interrupted by a timeout, for example.
    
  160. 
    
  161. The default test database names are created by prepending ``test_`` to the
    
  162. value of each :setting:`NAME` in :setting:`DATABASES`. When using SQLite, the
    
  163. tests will use an in-memory database by default (i.e., the database will be
    
  164. created in memory, bypassing the filesystem entirely!). The :setting:`TEST
    
  165. <DATABASE-TEST>` dictionary in :setting:`DATABASES` offers a number of settings
    
  166. to configure your test database. For example, if you want to use a different
    
  167. database name, specify :setting:`NAME <TEST_NAME>` in the :setting:`TEST
    
  168. <DATABASE-TEST>` dictionary for any given database in :setting:`DATABASES`.
    
  169. 
    
  170. On PostgreSQL, :setting:`USER` will also need read access to the built-in
    
  171. ``postgres`` database.
    
  172. 
    
  173. Aside from using a separate database, the test runner will otherwise
    
  174. use all of the same database settings you have in your settings file:
    
  175. :setting:`ENGINE <DATABASE-ENGINE>`, :setting:`USER`, :setting:`HOST`, etc. The
    
  176. test database is created by the user specified by :setting:`USER`, so you'll
    
  177. need to make sure that the given user account has sufficient privileges to
    
  178. create a new database on the system.
    
  179. 
    
  180. For fine-grained control over the character encoding of your test
    
  181. database, use the :setting:`CHARSET <TEST_CHARSET>` TEST option. If you're using
    
  182. MySQL, you can also use the :setting:`COLLATION <TEST_COLLATION>` option to
    
  183. control the particular collation used by the test database. See the
    
  184. :doc:`settings documentation </ref/settings>` for details of these
    
  185. and other advanced settings.
    
  186. 
    
  187. If using an SQLite in-memory database with SQLite, `shared cache
    
  188. <https://www.sqlite.org/sharedcache.html>`_ is enabled, so you can write tests
    
  189. with ability to share the database between threads.
    
  190. 
    
  191. .. admonition:: Finding data from your production database when running tests?
    
  192. 
    
  193.     If your code attempts to access the database when its modules are compiled,
    
  194.     this will occur *before* the test database is set up, with potentially
    
  195.     unexpected results. For example, if you have a database query in
    
  196.     module-level code and a real database exists, production data could pollute
    
  197.     your tests. *It is a bad idea to have such import-time database queries in
    
  198.     your code* anyway - rewrite your code so that it doesn't do this.
    
  199. 
    
  200.     This also applies to customized implementations of
    
  201.     :meth:`~django.apps.AppConfig.ready()`.
    
  202. 
    
  203. .. seealso::
    
  204. 
    
  205.     The :ref:`advanced multi-db testing topics <topics-testing-advanced-multidb>`.
    
  206. 
    
  207. .. _order-of-tests:
    
  208. 
    
  209. Order in which tests are executed
    
  210. ---------------------------------
    
  211. 
    
  212. In order to guarantee that all ``TestCase`` code starts with a clean database,
    
  213. the Django test runner reorders tests in the following way:
    
  214. 
    
  215. * All :class:`~django.test.TestCase` subclasses are run first.
    
  216. 
    
  217. * Then, all other Django-based tests (test cases based on
    
  218.   :class:`~django.test.SimpleTestCase`, including
    
  219.   :class:`~django.test.TransactionTestCase`) are run with no particular
    
  220.   ordering guaranteed nor enforced among them.
    
  221. 
    
  222. * Then any other :class:`unittest.TestCase` tests (including doctests) that may
    
  223.   alter the database without restoring it to its original state are run.
    
  224. 
    
  225. .. note::
    
  226. 
    
  227.     The new ordering of tests may reveal unexpected dependencies on test case
    
  228.     ordering. This is the case with doctests that relied on state left in the
    
  229.     database by a given :class:`~django.test.TransactionTestCase` test, they
    
  230.     must be updated to be able to run independently.
    
  231. 
    
  232. .. note::
    
  233. 
    
  234.     Failures detected when loading tests are ordered before all of the above
    
  235.     for quicker feedback. This includes things like test modules that couldn't
    
  236.     be found or that couldn't be loaded due to syntax errors.
    
  237. 
    
  238. You may randomize and/or reverse the execution order inside groups using the
    
  239. :option:`test --shuffle` and :option:`--reverse <test --reverse>` options. This
    
  240. can help with ensuring your tests are independent from each other.
    
  241. 
    
  242. .. versionchanged:: 4.0
    
  243. 
    
  244.     In older versions, failures detected when loading tests were not ordered
    
  245.     first.
    
  246. 
    
  247. .. _test-case-serialized-rollback:
    
  248. 
    
  249. Rollback emulation
    
  250. ------------------
    
  251. 
    
  252. Any initial data loaded in migrations will only be available in ``TestCase``
    
  253. tests and not in ``TransactionTestCase`` tests, and additionally only on
    
  254. backends where transactions are supported (the most important exception being
    
  255. MyISAM). This is also true for tests which rely on ``TransactionTestCase``
    
  256. such as :class:`LiveServerTestCase` and
    
  257. :class:`~django.contrib.staticfiles.testing.StaticLiveServerTestCase`.
    
  258. 
    
  259. Django can reload that data for you on a per-testcase basis by
    
  260. setting the ``serialized_rollback`` option to ``True`` in the body of the
    
  261. ``TestCase`` or ``TransactionTestCase``, but note that this will slow down
    
  262. that test suite by approximately 3x.
    
  263. 
    
  264. Third-party apps or those developing against MyISAM will need to set this;
    
  265. in general, however, you should be developing your own projects against a
    
  266. transactional database and be using ``TestCase`` for most tests, and thus
    
  267. not need this setting.
    
  268. 
    
  269. The initial serialization is usually very quick, but if you wish to exclude
    
  270. some apps from this process (and speed up test runs slightly), you may add
    
  271. those apps to :setting:`TEST_NON_SERIALIZED_APPS`.
    
  272. 
    
  273. To prevent serialized data from being loaded twice, setting
    
  274. ``serialized_rollback=True`` disables the
    
  275. :data:`~django.db.models.signals.post_migrate` signal when flushing the test
    
  276. database.
    
  277. 
    
  278. Other test conditions
    
  279. ---------------------
    
  280. 
    
  281. Regardless of the value of the :setting:`DEBUG` setting in your configuration
    
  282. file, all Django tests run with :setting:`DEBUG`\=False. This is to ensure that
    
  283. the observed output of your code matches what will be seen in a production
    
  284. setting.
    
  285. 
    
  286. Caches are not cleared after each test, and running ``manage.py test fooapp``
    
  287. can insert data from the tests into the cache of a live system if you run your
    
  288. tests in production because, unlike databases, a separate "test cache" is not
    
  289. used. This behavior :ticket:`may change <11505>` in the future.
    
  290. 
    
  291. Understanding the test output
    
  292. -----------------------------
    
  293. 
    
  294. When you run your tests, you'll see a number of messages as the test runner
    
  295. prepares itself. You can control the level of detail of these messages with the
    
  296. ``verbosity`` option on the command line::
    
  297. 
    
  298.     Creating test database...
    
  299.     Creating table myapp_animal
    
  300.     Creating table myapp_mineral
    
  301. 
    
  302. This tells you that the test runner is creating a test database, as described
    
  303. in the previous section.
    
  304. 
    
  305. Once the test database has been created, Django will run your tests.
    
  306. If everything goes well, you'll see something like this::
    
  307. 
    
  308.     ----------------------------------------------------------------------
    
  309.     Ran 22 tests in 0.221s
    
  310. 
    
  311.     OK
    
  312. 
    
  313. If there are test failures, however, you'll see full details about which tests
    
  314. failed::
    
  315. 
    
  316.     ======================================================================
    
  317.     FAIL: test_was_published_recently_with_future_poll (polls.tests.PollMethodTests)
    
  318.     ----------------------------------------------------------------------
    
  319.     Traceback (most recent call last):
    
  320.       File "/dev/mysite/polls/tests.py", line 16, in test_was_published_recently_with_future_poll
    
  321.         self.assertIs(future_poll.was_published_recently(), False)
    
  322.     AssertionError: True is not False
    
  323. 
    
  324.     ----------------------------------------------------------------------
    
  325.     Ran 1 test in 0.003s
    
  326. 
    
  327.     FAILED (failures=1)
    
  328. 
    
  329. A full explanation of this error output is beyond the scope of this document,
    
  330. but it's pretty intuitive. You can consult the documentation of Python's
    
  331. :mod:`unittest` library for details.
    
  332. 
    
  333. Note that the return code for the test-runner script is 1 for any number of
    
  334. failed tests (whether the failure was caused by an error, a failed assertion,
    
  335. or an unexpected success). If all the tests pass, the return code is 0. This
    
  336. feature is useful if you're using the test-runner script in a shell script and
    
  337. need to test for success or failure at that level.
    
  338. 
    
  339. .. versionchanged:: 4.1
    
  340. 
    
  341.     In older versions, the return code was 0 for unexpected successes.
    
  342. 
    
  343. .. _speeding-up-tests-auth-hashers:
    
  344. 
    
  345. Speeding up the tests
    
  346. ---------------------
    
  347. 
    
  348. Running tests in parallel
    
  349. ~~~~~~~~~~~~~~~~~~~~~~~~~
    
  350. 
    
  351. As long as your tests are properly isolated, you can run them in parallel to
    
  352. gain a speed up on multi-core hardware. See :option:`test --parallel`.
    
  353. 
    
  354. Password hashing
    
  355. ~~~~~~~~~~~~~~~~
    
  356. 
    
  357. The default password hasher is rather slow by design. If you're authenticating
    
  358. many users in your tests, you may want to use a custom settings file and set
    
  359. the :setting:`PASSWORD_HASHERS` setting to a faster hashing algorithm::
    
  360. 
    
  361.     PASSWORD_HASHERS = [
    
  362.         'django.contrib.auth.hashers.MD5PasswordHasher',
    
  363.     ]
    
  364. 
    
  365. Don't forget to also include in :setting:`PASSWORD_HASHERS` any hashing
    
  366. algorithm used in fixtures, if any.
    
  367. 
    
  368. Preserving the test database
    
  369. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    
  370. 
    
  371. The :option:`test --keepdb` option preserves the test database between test
    
  372. runs. It skips the create and destroy actions which can greatly decrease the
    
  373. time to run tests.