unit-tests.txt 22 KB

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