overview.txt 13 KB

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