unit-tests.txt 19 KB

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