2
0

overview.txt 12 KB

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