overview.txt 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314
  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. .. admonition:: unittest2
  17. .. deprecated:: 1.7
  18. Python 2.7 introduced some major changes to the ``unittest`` library,
  19. adding some extremely useful features. To ensure that every Django project
  20. could benefit from these new features, Django used to ship with a copy of
  21. Python 2.7's ``unittest`` backported for Python 2.6 compatibility.
  22. Since Django no longer supports Python versions older than 2.7,
  23. ``django.utils.unittest`` is deprecated. Simply use ``unittest``.
  24. .. _unittest2: https://pypi.python.org/pypi/unittest2
  25. Here is an example which subclasses from :class:`django.test.TestCase`,
  26. which is a subclass of :class:`unittest.TestCase` that runs each test inside a
  27. transaction to provide isolation::
  28. from django.test import TestCase
  29. from myapp.models import Animal
  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. def test_animals_can_speak(self):
  35. """Animals that can speak are correctly identified"""
  36. lion = Animal.objects.get(name="lion")
  37. cat = Animal.objects.get(name="cat")
  38. self.assertEqual(lion.speak(), 'The lion says "roar"')
  39. self.assertEqual(cat.speak(), 'The cat says "meow"')
  40. When you :ref:`run your tests <running-tests>`, the default behavior of the
  41. test utility is to find all the test cases (that is, subclasses of
  42. :class:`unittest.TestCase`) in any file whose name begins with ``test``,
  43. automatically build a test suite out of those test cases, and run that suite.
  44. For more details about :mod:`unittest`, see the Python documentation.
  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. $ ./manage.py test
  60. Test discovery is based on the unittest module's :py:ref:`built-in test
  61. discovery <unittest-test-discovery>`. By default, this will discover tests in
  62. any file named "test*.py" under the current working directory.
  63. You can specify particular tests to run by supplying any number of "test
  64. labels" to ``./manage.py test``. Each test label can be a full Python dotted
  65. path to a package, module, ``TestCase`` subclass, or test method. For instance::
  66. # Run all the tests in the animals.tests module
  67. $ ./manage.py test animals.tests
  68. # Run all the tests found within the 'animals' package
  69. $ ./manage.py test animals
  70. # Run just one test case
  71. $ ./manage.py test animals.tests.AnimalTestCase
  72. # Run just one test method
  73. $ ./manage.py test animals.tests.AnimalTestCase.test_animals_can_speak
  74. You can also provide a path to a directory to discover tests below that
  75. directory::
  76. $ ./manage.py test animals/
  77. You can specify a custom filename pattern match using the ``-p`` (or
  78. ``--pattern``) option, if your test files are named differently from the
  79. ``test*.py`` pattern::
  80. $ ./manage.py test --pattern="tests_*.py"
  81. If you press ``Ctrl-C`` while the tests are running, the test runner will
  82. wait for the currently running test to complete and then exit gracefully.
  83. During a graceful exit the test runner will output details of any test
  84. failures, report on how many tests were run and how many errors and failures
  85. were encountered, and destroy any test databases as usual. Thus pressing
  86. ``Ctrl-C`` can be very useful if you forget to pass the :djadminopt:`--failfast`
  87. option, notice that some tests are unexpectedly failing, and want to get details
  88. on the failures without waiting for the full test run to 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 -Wall manage.py test``. The ``-Wall`` 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. .. versionadded:: 1.8
  108. You can prevent the test databases from being destroyed by adding the
  109. :djadminopt:`--keepdb` flag to the test command. This will preserve the test
  110. database between runs. If the database does not exist, it will first
  111. be created. Any migrations will also be applied in order to keep it
  112. up to date.
  113. By default the test databases get their names by prepending ``test_``
  114. to the value of the :setting:`NAME` settings for the databases
  115. defined in :setting:`DATABASES`. When using the SQLite database engine
  116. the tests will by default use an in-memory database (i.e., the
  117. database will be created in memory, bypassing the filesystem
  118. entirely!). If you want to use a different database name, specify
  119. :setting:`NAME <TEST_NAME>` in the :setting:`TEST <DATABASE-TEST>`
  120. dictionary for any given database in :setting:`DATABASES`.
  121. .. versionchanged:: 1.7
  122. On PostgreSQL, :setting:`USER` will also need read access to the built-in
  123. ``postgres`` database.
  124. Aside from using a separate database, the test runner will otherwise
  125. use all of the same database settings you have in your settings file:
  126. :setting:`ENGINE <DATABASE-ENGINE>`, :setting:`USER`, :setting:`HOST`, etc. The
  127. test database is created by the user specified by :setting:`USER`, so you'll
  128. need to make sure that the given user account has sufficient privileges to
  129. create a new database on the system.
  130. For fine-grained control over the character encoding of your test
  131. database, use the :setting:`CHARSET <TEST_CHARSET>` TEST option. If you're using
  132. MySQL, you can also use the :setting:`COLLATION <TEST_COLLATION>` option to
  133. control the particular collation used by the test database. See the
  134. :doc:`settings documentation </ref/settings>` for details of these
  135. and other advanced settings.
  136. .. versionchanged:: 1.7
  137. The different options in the :setting:`TEST <DATABASE-TEST>` database
  138. setting used to be separate options in the database settings dictionary,
  139. prefixed with ``TEST_``.
  140. .. admonition:: Finding data from your production database when running tests?
  141. If your code attempts to access the database when its modules are compiled,
  142. this will occur *before* the test database is set up, with potentially
  143. unexpected results. For example, if you have a database query in
  144. module-level code and a real database exists, production data could pollute
  145. your tests. *It is a bad idea to have such import-time database queries in
  146. your code* anyway - rewrite your code so that it doesn't do this.
  147. .. versionadded:: 1.7
  148. This also applies to customized implementations of
  149. :meth:`~django.apps.AppConfig.ready()`.
  150. .. seealso::
  151. The :ref:`advanced multi-db testing topics <topics-testing-advanced-multidb>`.
  152. .. _order-of-tests:
  153. Order in which tests are executed
  154. ---------------------------------
  155. In order to guarantee that all ``TestCase`` code starts with a clean database,
  156. the Django test runner reorders tests in the following way:
  157. * All :class:`~django.test.TestCase` subclasses are run first.
  158. * Then, all other Django-based tests (test cases based on
  159. :class:`~django.test.SimpleTestCase`, including
  160. :class:`~django.test.TransactionTestCase`) are run with no particular
  161. ordering guaranteed nor enforced among them.
  162. * Then any other :class:`unittest.TestCase` tests (including doctests) that may
  163. alter the database without restoring it to its original state are run.
  164. .. note::
  165. The new ordering of tests may reveal unexpected dependencies on test case
  166. ordering. This is the case with doctests that relied on state left in the
  167. database by a given :class:`~django.test.TransactionTestCase` test, they
  168. must be updated to be able to run independently.
  169. Other test conditions
  170. ---------------------
  171. Regardless of the value of the :setting:`DEBUG` setting in your configuration
  172. file, all Django tests run with :setting:`DEBUG`\=False. This is to ensure that
  173. the observed output of your code matches what will be seen in a production
  174. setting.
  175. Caches are not cleared after each test, and running "manage.py test fooapp" can
  176. insert data from the tests into the cache of a live system if you run your
  177. tests in production because, unlike databases, a separate "test cache" is not
  178. used. This behavior `may change`_ in the future.
  179. .. _may change: https://code.djangoproject.com/ticket/11505
  180. Understanding the test output
  181. -----------------------------
  182. When you run your tests, you'll see a number of messages as the test runner
  183. prepares itself. You can control the level of detail of these messages with the
  184. ``verbosity`` option on the command line::
  185. Creating test database...
  186. Creating table myapp_animal
  187. Creating table myapp_mineral
  188. Loading 'initial_data' fixtures...
  189. No fixtures found.
  190. This tells you that the test runner is creating a test database, as described
  191. in the previous section.
  192. Once the test database has been created, Django will run your tests.
  193. If everything goes well, you'll see something like this::
  194. ----------------------------------------------------------------------
  195. Ran 22 tests in 0.221s
  196. OK
  197. If there are test failures, however, you'll see full details about which tests
  198. failed::
  199. ======================================================================
  200. FAIL: test_was_published_recently_with_future_poll (polls.tests.PollMethodTests)
  201. ----------------------------------------------------------------------
  202. Traceback (most recent call last):
  203. File "/dev/mysite/polls/tests.py", line 16, in test_was_published_recently_with_future_poll
  204. self.assertEqual(future_poll.was_published_recently(), False)
  205. AssertionError: True != False
  206. ----------------------------------------------------------------------
  207. Ran 1 test in 0.003s
  208. FAILED (failures=1)
  209. A full explanation of this error output is beyond the scope of this document,
  210. but it's pretty intuitive. You can consult the documentation of Python's
  211. :mod:`unittest` library for details.
  212. Note that the return code for the test-runner script is 1 for any number of
  213. failed and erroneous tests. If all the tests pass, the return code is 0. This
  214. feature is useful if you're using the test-runner script in a shell script and
  215. need to test for success or failure at that level.
  216. Speeding up the tests
  217. ---------------------
  218. In recent versions of Django, the default password hasher is rather slow by
  219. design. If during your tests you are authenticating many users, you may want
  220. to use a custom settings file and set the :setting:`PASSWORD_HASHERS` setting
  221. to a faster hashing algorithm::
  222. PASSWORD_HASHERS = (
  223. 'django.contrib.auth.hashers.MD5PasswordHasher',
  224. )
  225. Don't forget to also include in :setting:`PASSWORD_HASHERS` any hashing
  226. algorithm used in fixtures, if any.