unit-tests.txt 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427
  1. ==========
  2. Unit tests
  3. ==========
  4. .. highlight:: console
  5. Django comes with a test suite of its own, in the ``tests`` directory of the
  6. code base. It's our policy to make sure all tests pass at all times.
  7. We appreciate any and all contributions to the test suite!
  8. The Django tests all use the testing infrastructure that ships with Django for
  9. testing applications. See :doc:`/topics/testing/overview` for an explanation of
  10. how to write new tests.
  11. .. _running-unit-tests:
  12. Running the unit tests
  13. ======================
  14. Quickstart
  15. ----------
  16. If you are on Python 2, you'll first need to install a backport of the
  17. ``unittest.mock`` module that's available in Python 3. See
  18. :ref:`running-unit-tests-dependencies` for details on installing `mock`_ and
  19. the other optional test dependencies.
  20. Running the tests requires a Django settings module that defines the
  21. databases to use. To make it easy to get started, Django provides and uses a
  22. sample settings module that uses the SQLite database. To run the tests::
  23. $ git clone https://github.com/django/django.git django-repo
  24. $ cd django-repo/tests
  25. $ PYTHONPATH=..:$PYTHONPATH ./runtests.py
  26. .. admonition:: Windows users
  27. We recommend something like `Git Bash <https://msysgit.github.io/>`_ to run
  28. the tests using the above approach.
  29. You can avoid typing the ``PYTHONPATH`` bit each time by adding your Django
  30. checkout to your ``PYTHONPATH`` or by installing the source checkout using pip.
  31. See :ref:`installing-development-version`.
  32. Having problems? See :ref:`troubleshooting-unit-tests` for some common issues.
  33. .. _running-unit-tests-settings:
  34. Using another ``settings`` module
  35. ---------------------------------
  36. The included settings module (``tests/test_sqlite.py``) allows you to run the
  37. test suite using SQLite. If you want to run the tests using a different
  38. database, you'll need to define your own settings file. Some tests, such as
  39. those for ``contrib.postgres``, are specific to a particular database backend
  40. and will be skipped if run with a different backend.
  41. To run the tests with different settings, ensure that the module is on your
  42. ``PYTHONPATH`` and pass the module with ``--settings``.
  43. The :setting:`DATABASES` setting in any test settings module needs to define
  44. two databases:
  45. * A ``default`` database. This database should use the backend that
  46. you want to use for primary testing.
  47. * A database with the alias ``other``. The ``other`` database is used to test
  48. that queries can be directed to different databases. This database should use
  49. the same backend as the ``default``, and it must have a different name.
  50. If you're using a backend that isn't SQLite, you will need to provide other
  51. details for each database:
  52. * The :setting:`USER` option needs to specify an existing user account
  53. for the database. That user needs permission to execute ``CREATE DATABASE``
  54. so that the test database can be created.
  55. * The :setting:`PASSWORD` option needs to provide the password for
  56. the :setting:`USER` that has been specified.
  57. Test databases get their names by prepending ``test_`` to the value of the
  58. :setting:`NAME` settings for the databases defined in :setting:`DATABASES`.
  59. These test databases are deleted when the tests are finished.
  60. You will also need to ensure that your database uses UTF-8 as the default
  61. character set. If your database server doesn't use UTF-8 as a default charset,
  62. you will need to include a value for :setting:`CHARSET <TEST_CHARSET>` in the
  63. test settings dictionary for the applicable database.
  64. .. _runtests-specifying-labels:
  65. Running only some of the tests
  66. ------------------------------
  67. Django's entire test suite takes a while to run, and running every single test
  68. could be redundant if, say, you just added a test to Django that you want to
  69. run quickly without running everything else. You can run a subset of the unit
  70. tests by appending the names of the test modules to ``runtests.py`` on the
  71. command line.
  72. For example, if you'd like to run tests only for generic relations and
  73. internationalization, type::
  74. $ ./runtests.py --settings=path.to.settings generic_relations i18n
  75. How do you find out the names of individual tests? Look in ``tests/`` — each
  76. directory name there is the name of a test.
  77. If you just want to run a particular class of tests, you can specify a list of
  78. paths to individual test classes. For example, to run the ``TranslationTests``
  79. of the ``i18n`` module, type::
  80. $ ./runtests.py --settings=path.to.settings i18n.tests.TranslationTests
  81. Going beyond that, you can specify an individual test method like this::
  82. $ ./runtests.py --settings=path.to.settings i18n.tests.TranslationTests.test_lazy_objects
  83. Running the Selenium tests
  84. --------------------------
  85. Some tests require Selenium and a Web browser. To run these tests, you must
  86. install the selenium_ package and run the tests with the
  87. ``--selenium=<BROWSERS>`` option. For example, if you have Firefox and Google
  88. Chrome installed::
  89. $ ./runtests.py --selenium=firefox,chrome
  90. See the `selenium.webdriver`_ package for the list of available browsers.
  91. Specifying ``--selenium`` automatically sets ``--tags=selenium`` to run only
  92. the tests that require selenium.
  93. .. _selenium.webdriver: https://github.com/SeleniumHQ/selenium/tree/master/py/selenium/webdriver
  94. .. _running-unit-tests-dependencies:
  95. Running all the tests
  96. ---------------------
  97. If you want to run the full suite of tests, you'll need to install a number of
  98. dependencies:
  99. * argon2-cffi_ 16.1.0+
  100. * bcrypt_
  101. * docutils_
  102. * enum34_ (Python 2 only)
  103. * geoip2_
  104. * jinja2_ 2.7+
  105. * numpy_
  106. * Pillow_
  107. * PyYAML_
  108. * pytz_
  109. * setuptools_
  110. * memcached_, plus a :ref:`supported Python binding <memcached>`
  111. * mock_ (for Python 2)
  112. * gettext_ (:ref:`gettext_on_windows`)
  113. * selenium_
  114. * sqlparse_
  115. You can find these dependencies in `pip requirements files`_ inside the
  116. ``tests/requirements`` directory of the Django source tree and install them
  117. like so::
  118. $ pip install -r tests/requirements/py3.txt # Python 2: py2.txt
  119. You can also install the database adapter(s) of your choice using
  120. ``oracle.txt``, ``mysql.txt``, or ``postgres.txt``.
  121. If you want to test the memcached cache backend, you'll also need to define
  122. a :setting:`CACHES` setting that points at your memcached instance.
  123. To run the GeoDjango tests, you will need to :doc:`setup a spatial database
  124. and install the Geospatial libraries</ref/contrib/gis/install/index>`.
  125. Each of these dependencies is optional. If you're missing any of them, the
  126. associated tests will be skipped.
  127. .. _argon2-cffi: https://pypi.python.org/pypi/argon2_cffi
  128. .. _bcrypt: https://pypi.python.org/pypi/bcrypt
  129. .. _docutils: https://pypi.python.org/pypi/docutils
  130. .. _enum34: https://pypi.python.org/pypi/enum34
  131. .. _geoip2: https://pypi.python.org/pypi/geoip2
  132. .. _jinja2: https://pypi.python.org/pypi/jinja2
  133. .. _numpy: https://pypi.python.org/pypi/numpy
  134. .. _Pillow: https://pypi.python.org/pypi/Pillow/
  135. .. _PyYAML: http://pyyaml.org/wiki/PyYAML
  136. .. _pytz: https://pypi.python.org/pypi/pytz/
  137. .. _setuptools: https://pypi.python.org/pypi/setuptools/
  138. .. _memcached: http://memcached.org/
  139. .. _mock: https://pypi.python.org/pypi/mock
  140. .. _gettext: https://www.gnu.org/software/gettext/manual/gettext.html
  141. .. _selenium: https://pypi.python.org/pypi/selenium
  142. .. _sqlparse: https://pypi.python.org/pypi/sqlparse
  143. .. _pip requirements files: https://pip.pypa.io/en/latest/user_guide.html#requirements-files
  144. Code coverage
  145. -------------
  146. Contributors are encouraged to run coverage on the test suite to identify areas
  147. that need additional tests. The coverage tool installation and use is described
  148. in :ref:`testing code coverage<topics-testing-code-coverage>`.
  149. Coverage should be run in a single process to obtain accurate statistics. To
  150. run coverage on the Django test suite using the standard test settings::
  151. $ coverage run ./runtests.py --settings=test_sqlite --parallel=1
  152. After running coverage, generate the html report by running::
  153. $ coverage html
  154. When running coverage for the Django tests, the included ``.coveragerc``
  155. settings file defines ``coverage_html`` as the output directory for the report
  156. and also excludes several directories not relevant to the results
  157. (test code or external code included in Django).
  158. .. _contrib-apps:
  159. Contrib apps
  160. ============
  161. Tests for contrib apps can be found in the ``tests/`` directory, typically
  162. under ``<app_name>_tests``. For example, tests for ``contrib.auth`` are located
  163. in ``tests/auth_tests``.
  164. .. _troubleshooting-unit-tests:
  165. Troubleshooting
  166. ===============
  167. Many test failures with ``UnicodeEncodeError``
  168. ----------------------------------------------
  169. If the ``locales`` package is not installed, some tests will fail with a
  170. ``UnicodeEncodeError``.
  171. You can resolve this on Debian-based systems, for example, by running::
  172. $ apt-get install locales
  173. $ dpkg-reconfigure locales
  174. Tests that only fail in combination
  175. -----------------------------------
  176. In case a test passes when run in isolation but fails within the whole suite,
  177. we have some tools to help analyze the problem.
  178. The ``--bisect`` option of ``runtests.py`` will run the failing test while
  179. halving the test set it is run together with on each iteration, often making
  180. it possible to identify a small number of tests that may be related to the
  181. failure.
  182. For example, suppose that the failing test that works on its own is
  183. ``ModelTest.test_eq``, then using::
  184. $ ./runtests.py --bisect basic.tests.ModelTest.test_eq
  185. will try to determine a test that interferes with the given one. First, the
  186. test is run with the first half of the test suite. If a failure occurs, the
  187. first half of the test suite is split in two groups and each group is then run
  188. with the specified test. If there is no failure with the first half of the test
  189. suite, the second half of the test suite is run with the specified test and
  190. split appropriately as described earlier. The process repeats until the set of
  191. failing tests is minimized.
  192. The ``--pair`` option runs the given test alongside every other test from the
  193. suite, letting you check if another test has side-effects that cause the
  194. failure. So::
  195. $ ./runtests.py --pair basic.tests.ModelTest.test_eq
  196. will pair ``test_eq`` with every test label.
  197. With both ``--bisect`` and ``--pair``, if you already suspect which cases
  198. might be responsible for the failure, you may limit tests to be cross-analyzed
  199. by :ref:`specifying further test labels <runtests-specifying-labels>` after
  200. the first one::
  201. $ ./runtests.py --pair basic.tests.ModelTest.test_eq queries transactions
  202. You can also try running any set of tests in reverse using the ``--reverse``
  203. option in order to verify that executing tests in a different order does not
  204. cause any trouble::
  205. $ ./runtests.py basic --reverse
  206. Seeing the SQL queries run during a test
  207. ----------------------------------------
  208. If you wish to examine the SQL being run in failing tests, you can turn on
  209. :ref:`SQL logging <django-db-logger>` using the ``--debug-sql`` option. If you
  210. combine this with ``--verbosity=2``, all SQL queries will be output::
  211. $ ./runtests.py basic --debug-sql
  212. Seeing the full traceback of a test failure
  213. -------------------------------------------
  214. By default tests are run in parallel with one process per core. When the tests
  215. are run in parallel, however, you'll only see a truncated traceback for any
  216. test failures. You can adjust this behavior with the ``--parallel`` option::
  217. $ ./runtests.py basic --parallel=1
  218. You can also use the ``DJANGO_TEST_PROCESSES`` environment variable for this
  219. purpose.
  220. .. versionadded:: 1.9
  221. Support for running tests in parallel and the ``--parallel`` option were
  222. added.
  223. Tips for writing tests
  224. ----------------------
  225. .. highlight:: python
  226. Isolating model registration
  227. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  228. To avoid polluting the global :attr:`~django.apps.apps` registry and prevent
  229. unnecessary table creation, models defined in a test method should be bound to
  230. a temporary ``Apps`` instance::
  231. from django.apps.registry import Apps
  232. from django.db import models
  233. from django.test import SimpleTestCase
  234. class TestModelDefinition(SimpleTestCase):
  235. def test_model_definition(self):
  236. test_apps = Apps(['app_label'])
  237. class TestModel(models.Model):
  238. class Meta:
  239. apps = test_apps
  240. ...
  241. .. function:: django.test.utils.isolate_apps(*app_labels, attr_name=None, kwarg_name=None)
  242. .. versionadded:: 1.10
  243. Since this pattern involves a lot of boilerplate, Django provides the
  244. :func:`~django.test.utils.isolate_apps` decorator. It's used like this::
  245. from django.db import models
  246. from django.test import SimpleTestCase
  247. from django.test.utils import isolate_apps
  248. class TestModelDefinition(SimpleTestCase):
  249. @isolate_apps('app_label')
  250. def test_model_definition(self):
  251. class TestModel(models.Model):
  252. pass
  253. ...
  254. .. admonition:: Setting ``app_label``
  255. Models defined in a test method with no explicit
  256. :attr:`~django.db.models.Options.app_label` are automatically assigned the
  257. label of the app in which their test class is located.
  258. In order to make sure the models defined within the context of
  259. :func:`~django.test.utils.isolate_apps` instances are correctly
  260. installed, you should pass the set of targeted ``app_label`` as arguments:
  261. .. snippet::
  262. :filename: tests/app_label/tests.py
  263. from django.db import models
  264. from django.test import SimpleTestCase
  265. from django.test.utils import isolate_apps
  266. class TestModelDefinition(SimpleTestCase):
  267. @isolate_apps('app_label', 'other_app_label')
  268. def test_model_definition(self):
  269. # This model automatically receives app_label='app_label'
  270. class TestModel(models.Model):
  271. pass
  272. class OtherAppModel(models.Model):
  273. class Meta:
  274. app_label = 'other_app_label'
  275. ...
  276. The decorator can also be applied to classes::
  277. from django.db import models
  278. from django.test import SimpleTestCase
  279. from django.test.utils import isolate_apps
  280. @isolate_apps('app_label')
  281. class TestModelDefinition(SimpleTestCase):
  282. def test_model_definition(self):
  283. class TestModel(models.Model):
  284. pass
  285. ...
  286. The temporary ``Apps`` instance used to isolate model registration can be
  287. retrieved as an attribute when used as a class decorator by using the
  288. ``attr_name`` parameter::
  289. from django.db import models
  290. from django.test import SimpleTestCase
  291. from django.test.utils import isolate_apps
  292. @isolate_apps('app_label', attr_name='apps')
  293. class TestModelDefinition(SimpleTestCase):
  294. def test_model_definition(self):
  295. class TestModel(models.Model):
  296. pass
  297. self.assertIs(self.apps.get_model('app_label', 'TestModel'), TestModel)
  298. Or as an argument on the test method when used as a method decorator by using
  299. the ``kwarg_name`` parameter::
  300. from django.db import models
  301. from django.test import SimpleTestCase
  302. from django.test.utils import isolate_apps
  303. class TestModelDefinition(SimpleTestCase):
  304. @isolate_apps('app_label', kwarg_name='apps')
  305. def test_model_definition(self, apps):
  306. class TestModel(models.Model):
  307. pass
  308. self.assertIs(apps.get_model('app_label', 'TestModel'), TestModel)