unit-tests.txt 19 KB

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