overview.txt 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357
  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. If using a SQLite in-memory database with Python 3.4+ and SQLite 3.7.13+,
  137. `shared cache <https://www.sqlite.org/sharedcache.html>`_ will be enabled, so
  138. you can write tests with ability to share the database between threads.
  139. .. versionchanged:: 1.7
  140. The different options in the :setting:`TEST <DATABASE-TEST>` database
  141. setting used to be separate options in the database settings dictionary,
  142. prefixed with ``TEST_``.
  143. .. versionadded:: 1.8
  144. The ability to use SQLite with a shared cache as described above was added.
  145. .. admonition:: Finding data from your production database when running tests?
  146. If your code attempts to access the database when its modules are compiled,
  147. this will occur *before* the test database is set up, with potentially
  148. unexpected results. For example, if you have a database query in
  149. module-level code and a real database exists, production data could pollute
  150. your tests. *It is a bad idea to have such import-time database queries in
  151. your code* anyway - rewrite your code so that it doesn't do this.
  152. .. versionadded:: 1.7
  153. This also applies to customized implementations of
  154. :meth:`~django.apps.AppConfig.ready()`.
  155. .. seealso::
  156. The :ref:`advanced multi-db testing topics <topics-testing-advanced-multidb>`.
  157. .. _order-of-tests:
  158. Order in which tests are executed
  159. ---------------------------------
  160. In order to guarantee that all ``TestCase`` code starts with a clean database,
  161. the Django test runner reorders tests in the following way:
  162. * All :class:`~django.test.TestCase` subclasses are run first.
  163. * Then, all other Django-based tests (test cases based on
  164. :class:`~django.test.SimpleTestCase`, including
  165. :class:`~django.test.TransactionTestCase`) are run with no particular
  166. ordering guaranteed nor enforced among them.
  167. * Then any other :class:`unittest.TestCase` tests (including doctests) that may
  168. alter the database without restoring it to its original state are run.
  169. .. note::
  170. The new ordering of tests may reveal unexpected dependencies on test case
  171. ordering. This is the case with doctests that relied on state left in the
  172. database by a given :class:`~django.test.TransactionTestCase` test, they
  173. must be updated to be able to run independently.
  174. .. versionadded:: 1.8
  175. You may reverse the execution order inside groups by passing
  176. :djadminopt:`--reverse` to the test command. This can help with ensuring
  177. your tests are independent from each other.
  178. .. _test-case-serialized-rollback:
  179. Rollback emulation
  180. ------------------
  181. Any initial data loaded in migrations will only be available in ``TestCase``
  182. tests and not in ``TransactionTestCase`` tests, and additionally only on
  183. backends where transactions are supported (the most important exception being
  184. MyISAM). This is also true for tests which rely on ``TransactionTestCase``
  185. such as :class:`LiveServerTestCase` and
  186. :class:`~django.contrib.staticfiles.testing.StaticLiveServerTestCase`.
  187. Django can reload that data for you on a per-testcase basis by
  188. setting the ``serialized_rollback`` option to ``True`` in the body of the
  189. ``TestCase`` or ``TransactionTestCase``, but note that this will slow down
  190. that test suite by approximately 3x.
  191. Third-party apps or those developing against MyISAM will need to set this;
  192. in general, however, you should be developing your own projects against a
  193. transactional database and be using ``TestCase`` for most tests, and thus
  194. not need this setting.
  195. The initial serialization is usually very quick, but if you wish to exclude
  196. some apps from this process (and speed up test runs slightly), you may add
  197. those apps to :setting:`TEST_NON_SERIALIZED_APPS`.
  198. Apps without migrations are not affected; ``initial_data`` fixtures are
  199. reloaded as usual.
  200. Other test conditions
  201. ---------------------
  202. Regardless of the value of the :setting:`DEBUG` setting in your configuration
  203. file, all Django tests run with :setting:`DEBUG`\=False. This is to ensure that
  204. the observed output of your code matches what will be seen in a production
  205. setting.
  206. Caches are not cleared after each test, and running "manage.py test fooapp" can
  207. insert data from the tests into the cache of a live system if you run your
  208. tests in production because, unlike databases, a separate "test cache" is not
  209. used. This behavior `may change`_ in the future.
  210. .. _may change: https://code.djangoproject.com/ticket/11505
  211. Understanding the test output
  212. -----------------------------
  213. When you run your tests, you'll see a number of messages as the test runner
  214. prepares itself. You can control the level of detail of these messages with the
  215. ``verbosity`` option on the command line::
  216. Creating test database...
  217. Creating table myapp_animal
  218. Creating table myapp_mineral
  219. Loading 'initial_data' fixtures...
  220. No fixtures found.
  221. This tells you that the test runner is creating a test database, as described
  222. in the previous section.
  223. Once the test database has been created, Django will run your tests.
  224. If everything goes well, you'll see something like this::
  225. ----------------------------------------------------------------------
  226. Ran 22 tests in 0.221s
  227. OK
  228. If there are test failures, however, you'll see full details about which tests
  229. failed::
  230. ======================================================================
  231. FAIL: test_was_published_recently_with_future_poll (polls.tests.PollMethodTests)
  232. ----------------------------------------------------------------------
  233. Traceback (most recent call last):
  234. File "/dev/mysite/polls/tests.py", line 16, in test_was_published_recently_with_future_poll
  235. self.assertEqual(future_poll.was_published_recently(), False)
  236. AssertionError: True != False
  237. ----------------------------------------------------------------------
  238. Ran 1 test in 0.003s
  239. FAILED (failures=1)
  240. A full explanation of this error output is beyond the scope of this document,
  241. but it's pretty intuitive. You can consult the documentation of Python's
  242. :mod:`unittest` library for details.
  243. Note that the return code for the test-runner script is 1 for any number of
  244. failed and erroneous tests. If all the tests pass, the return code is 0. This
  245. feature is useful if you're using the test-runner script in a shell script and
  246. need to test for success or failure at that level.
  247. Speeding up the tests
  248. ---------------------
  249. In recent versions of Django, the default password hasher is rather slow by
  250. design. If during your tests you are authenticating many users, you may want
  251. to use a custom settings file and set the :setting:`PASSWORD_HASHERS` setting
  252. to a faster hashing algorithm::
  253. PASSWORD_HASHERS = (
  254. 'django.contrib.auth.hashers.MD5PasswordHasher',
  255. )
  256. Don't forget to also include in :setting:`PASSWORD_HASHERS` any hashing
  257. algorithm used in fixtures, if any.