unit-tests.txt 20 KB

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