helpers.rst 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393
  1. .. _helpers:
  2. Django helpers
  3. ==============
  4. Assertions
  5. ----------
  6. All of Django's :py:class:`~django:django.test.TestCase`
  7. :ref:`django:assertions` are available in ``pytest_django.asserts``, e.g.
  8. ::
  9. from pytest_django.asserts import assertTemplateUsed
  10. Markers
  11. -------
  12. ``pytest-django`` registers and uses markers. See the pytest documentation_
  13. on what marks are and for notes on using_ them.
  14. .. _documentation: https://pytest.org/en/latest/mark.html
  15. .. _using: https://pytest.org/en/latest/example/markers.html#marking-whole-classes-or-modules
  16. ``pytest.mark.django_db`` - request database access
  17. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  18. .. :py:function:: pytest.mark.django_db([transaction=False, reset_sequences=False]):
  19. This is used to mark a test function as requiring the database. It
  20. will ensure the database is set up correctly for the test. Each test
  21. will run in its own transaction which will be rolled back at the end
  22. of the test. This behavior is the same as Django's standard
  23. `django.test.TestCase`_ class.
  24. In order for a test to have access to the database it must either
  25. be marked using the ``django_db`` mark or request one of the ``db``,
  26. ``transactional_db`` or ``django_db_reset_sequences`` fixtures. Otherwise the
  27. test will fail when trying to access the database.
  28. :type transaction: bool
  29. :param transaction:
  30. The ``transaction`` argument will allow the test to use real transactions.
  31. With ``transaction=False`` (the default when not specified), transaction
  32. operations are noops during the test. This is the same behavior that
  33. `django.test.TestCase`_
  34. uses. When ``transaction=True``, the behavior will be the same as
  35. `django.test.TransactionTestCase`_
  36. :type reset_sequences: bool
  37. :param reset_sequences:
  38. The ``reset_sequences`` argument will ask to reset auto increment sequence
  39. values (e.g. primary keys) before running the test. Defaults to
  40. ``False``. Must be used together with ``transaction=True`` to have an
  41. effect. Please be aware that not all databases support this feature.
  42. For details see :py:attr:`django.test.TransactionTestCase.reset_sequences`.
  43. .. note::
  44. If you want access to the Django database *inside a fixture*
  45. this marker will not help even if the function requesting your
  46. fixture has this marker applied. To access the database in a
  47. fixture, the fixture itself will have to request the ``db``,
  48. ``transactional_db`` or ``django_db_reset_sequences`` fixture. See below
  49. for a description of them.
  50. .. note:: Automatic usage with ``django.test.TestCase``.
  51. Test classes that subclass `django.test.TestCase`_ will have access to
  52. the database always to make them compatible with existing Django tests.
  53. Test classes that subclass Python's ``unittest.TestCase`` need to have the
  54. marker applied in order to access the database.
  55. .. _django.test.TestCase: https://docs.djangoproject.com/en/dev/topics/testing/overview/#testcase
  56. .. _django.test.TransactionTestCase: https://docs.djangoproject.com/en/dev/topics/testing/overview/#transactiontestcase
  57. ``pytest.mark.urls`` - override the urlconf
  58. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  59. .. py:function:: pytest.mark.urls(urls)
  60. Specify a different ``settings.ROOT_URLCONF`` module for the marked tests.
  61. :type urls: str
  62. :param urls:
  63. The urlconf module to use for the test, e.g. ``myapp.test_urls``. This is
  64. similar to Django's ``TestCase.urls`` attribute.
  65. Example usage::
  66. @pytest.mark.urls('myapp.test_urls')
  67. def test_something(client):
  68. assert 'Success!' in client.get('/some_url_defined_in_test_urls/').content
  69. ``pytest.mark.ignore_template_errors`` - ignore invalid template variables
  70. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  71. .. py:function:: pytest.mark.ignore_template_errors
  72. Ignore errors when using the ``--fail-on-template-vars`` option, i.e.
  73. do not cause tests to fail if your templates contain invalid variables.
  74. This marker sets the ``string_if_invalid`` template option, or
  75. the older ``settings.TEMPLATE_STRING_IF_INVALID=None`` (Django up to 1.10).
  76. See :ref:`django:invalid-template-variables`.
  77. Example usage::
  78. @pytest.mark.ignore_template_errors
  79. def test_something(client):
  80. client('some-url-with-invalid-template-vars')
  81. Fixtures
  82. --------
  83. pytest-django provides some pytest fixtures to provide dependencies for tests.
  84. More information on fixtures is available in the `pytest documentation
  85. <https://pytest.org/en/latest/fixture.html>`_.
  86. ``rf`` - ``RequestFactory``
  87. ~~~~~~~~~~~~~~~~~~~~~~~~~~~
  88. An instance of a `django.test.RequestFactory`_
  89. .. _django.test.RequestFactory: https://docs.djangoproject.com/en/dev/topics/testing/advanced/#django.test.RequestFactory
  90. Example
  91. """""""
  92. ::
  93. from myapp.views import my_view
  94. def test_details(rf):
  95. request = rf.get('/customer/details')
  96. response = my_view(request)
  97. assert response.status_code == 200
  98. ``client`` - ``django.test.Client``
  99. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  100. An instance of a `django.test.Client`_
  101. .. _django.test.Client: https://docs.djangoproject.com/en/dev/topics/testing/tools/#the-test-client
  102. Example
  103. """""""
  104. ::
  105. def test_with_client(client):
  106. response = client.get('/')
  107. assert response.content == 'Foobar'
  108. To use `client` as an authenticated standard user, call its `login()` method before accessing a URL:
  109. ::
  110. def test_with_authenticated_client(client, django_user_model):
  111. username = "user1"
  112. password = "bar"
  113. django_user_model.objects.create_user(username=username, password=password)
  114. client.login(username=username, password=password)
  115. response = client.get('/private')
  116. assert response.content == 'Protected Area'
  117. ``admin_client`` - ``django.test.Client`` logged in as admin
  118. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  119. An instance of a `django.test.Client`_, logged in as an admin user.
  120. Example
  121. """""""
  122. ::
  123. def test_an_admin_view(admin_client):
  124. response = admin_client.get('/admin/')
  125. assert response.status_code == 200
  126. Using the `admin_client` fixture will cause the test to automatically be marked for database use (no need to specify the
  127. ``django_db`` mark).
  128. .. fixture:: admin_user
  129. ``admin_user`` - an admin user (superuser)
  130. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  131. An instance of a superuser, with username "admin" and password "password" (in
  132. case there is no "admin" user yet).
  133. Using the `admin_user` fixture will cause the test to automatically be marked for database use (no need to specify the
  134. ``django_db`` mark).
  135. ``django_user_model``
  136. ~~~~~~~~~~~~~~~~~~~~~
  137. A shortcut to the User model configured for use by the current Django project (aka the model referenced by
  138. `settings.AUTH_USER_MODEL`). Use this fixture to make pluggable apps testable regardless what User model is configured
  139. in the containing Django project.
  140. Example
  141. """""""
  142. ::
  143. def test_new_user(django_user_model):
  144. django_user_model.objects.create(username="someone", password="something")
  145. ``django_username_field``
  146. ~~~~~~~~~~~~~~~~~~~~~~~~~
  147. This fixture extracts the field name used for the username on the user model, i.e. resolves to the current
  148. ``settings.USERNAME_FIELD``. Use this fixture to make pluggable apps testable regardless what the username field
  149. is configured to be in the containing Django project.
  150. ``db``
  151. ~~~~~~~
  152. .. fixture:: db
  153. This fixture will ensure the Django database is set up. Only
  154. required for fixtures that want to use the database themselves. A
  155. test function should normally use the ``pytest.mark.django_db``
  156. mark to signal it needs the database.
  157. ``transactional_db``
  158. ~~~~~~~~~~~~~~~~~~~~
  159. This fixture can be used to request access to the database including
  160. transaction support. This is only required for fixtures which need
  161. database access themselves. A test function should normally use the
  162. ``pytest.mark.django_db`` mark with ``transaction=True``.
  163. ``django_db_reset_sequences``
  164. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  165. .. fixture:: django_db_reset_sequences
  166. This fixture provides the same transactional database access as
  167. ``transactional_db``, with additional support for reset of auto increment
  168. sequences (if your database supports it). This is only required for
  169. fixtures which need database access themselves. A test function should
  170. normally use the ``pytest.mark.django_db`` mark with ``transaction=True`` and ``reset_sequences=True``.
  171. ``live_server``
  172. ~~~~~~~~~~~~~~~
  173. This fixture runs a live Django server in a background thread. The
  174. server's URL can be retrieved using the ``live_server.url`` attribute
  175. or by requesting it's string value: ``unicode(live_server)``. You can
  176. also directly concatenate a string to form a URL: ``live_server +
  177. '/foo``.
  178. .. note:: Combining database access fixtures.
  179. When using multiple database fixtures together, only one of them is
  180. used. Their order of precedence is as follows (the last one wins):
  181. * ``db``
  182. * ``transactional_db``
  183. * ``django_db_reset_sequences``
  184. In addition, using ``live_server`` will also trigger transactional
  185. database access, if not specified.
  186. ``settings``
  187. ~~~~~~~~~~~~
  188. This fixture will provide a handle on the Django settings module, and
  189. automatically revert any changes made to the settings (modifications, additions
  190. and deletions).
  191. Example
  192. """""""
  193. ::
  194. def test_with_specific_settings(settings):
  195. settings.USE_TZ = True
  196. assert settings.USE_TZ
  197. .. fixture:: django_assert_num_queries
  198. ``django_assert_num_queries``
  199. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  200. .. py:function:: django_assert_num_queries(num, connection=None, info=None)
  201. :param num: expected number of queries
  202. :param connection: optional non-default DB connection
  203. :param str info: optional info message to display on failure
  204. This fixture allows to check for an expected number of DB queries.
  205. If the assertion failed, the executed queries can be shown by using
  206. the verbose command line option.
  207. It wraps `django.test.utils.CaptureQueriesContext` and yields the wrapped
  208. CaptureQueriesContext instance.
  209. Example usage::
  210. def test_queries(django_assert_num_queries):
  211. with django_assert_num_queries(3) as captured:
  212. Item.objects.create('foo')
  213. Item.objects.create('bar')
  214. Item.objects.create('baz')
  215. assert 'foo' in captured.captured_queries[0]['sql']
  216. .. fixture:: django_assert_max_num_queries
  217. ``django_assert_max_num_queries``
  218. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  219. .. py:function:: django_assert_max_num_queries(num, connection=None, info=None)
  220. :param num: expected maximum number of queries
  221. :param connection: optional non-default DB connection
  222. :param str info: optional info message to display on failure
  223. This fixture allows to check for an expected maximum number of DB queries.
  224. It is a specialized version of :fixture:`django_assert_num_queries`.
  225. Example usage::
  226. def test_max_queries(django_assert_max_num_queries):
  227. with django_assert_max_num_queries(2):
  228. Item.objects.create('foo')
  229. Item.objects.create('bar')
  230. ``mailoutbox``
  231. ~~~~~~~~~~~~~~
  232. A clean email outbox to which Django-generated emails are sent.
  233. Example
  234. """""""
  235. ::
  236. from django.core import mail
  237. def test_mail(mailoutbox):
  238. mail.send_mail('subject', 'body', 'from@example.com', ['to@example.com'])
  239. assert len(mailoutbox) == 1
  240. m = mailoutbox[0]
  241. assert m.subject == 'subject'
  242. assert m.body == 'body'
  243. assert m.from_email == 'from@example.com'
  244. assert list(m.to) == ['to@example.com']
  245. This uses the ``django_mail_patch_dns`` fixture, which patches
  246. ``DNS_NAME`` used by :py:mod:`django.core.mail` with the value from
  247. the ``django_mail_dnsname`` fixture, which defaults to
  248. "fake-tests.example.com".
  249. Automatic cleanup
  250. -----------------
  251. pytest-django provides some functionality to assure a clean and consistent environment
  252. during tests.
  253. Clearing of site cache
  254. ~~~~~~~~~~~~~~~~~~~~~~
  255. If ``django.contrib.sites`` is in your INSTALLED_APPS, Site cache will
  256. be cleared for each test to avoid hitting the cache and causing the wrong Site
  257. object to be returned by ``Site.objects.get_current()``.
  258. Clearing of mail.outbox
  259. ~~~~~~~~~~~~~~~~~~~~~~~
  260. ``mail.outbox`` will be cleared for each pytest, to give each new test an empty
  261. mailbox to work with. However, it's more "pytestic" to use the ``mailoutbox`` fixture described above
  262. than to access ``mail.outbox``.