2
0

unit-tests.txt 20 KB

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