overview.txt 15 KB

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