unit-tests.txt 18 KB

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