overview.txt 16 KB

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