1. =============
    
  2. Testing tools
    
  3. =============
    
  4. 
    
  5. .. currentmodule:: django.test
    
  6. 
    
  7. Django provides a small set of tools that come in handy when writing tests.
    
  8. 
    
  9. .. _test-client:
    
  10. 
    
  11. The test client
    
  12. ===============
    
  13. 
    
  14. The test client is a Python class that acts as a dummy web browser, allowing
    
  15. you to test your views and interact with your Django-powered application
    
  16. programmatically.
    
  17. 
    
  18. Some of the things you can do with the test client are:
    
  19. 
    
  20. * Simulate GET and POST requests on a URL and observe the response --
    
  21.   everything from low-level HTTP (result headers and status codes) to
    
  22.   page content.
    
  23. 
    
  24. * See the chain of redirects (if any) and check the URL and status code at
    
  25.   each step.
    
  26. 
    
  27. * Test that a given request is rendered by a given Django template, with
    
  28.   a template context that contains certain values.
    
  29. 
    
  30. Note that the test client is not intended to be a replacement for Selenium_ or
    
  31. other "in-browser" frameworks. Django's test client has a different focus. In
    
  32. short:
    
  33. 
    
  34. * Use Django's test client to establish that the correct template is being
    
  35.   rendered and that the template is passed the correct context data.
    
  36. 
    
  37. * Use :class:`~django.test.RequestFactory` to test view functions directly,
    
  38.   bypassing the routing and middleware layers.
    
  39. 
    
  40. * Use in-browser frameworks like Selenium_ to test *rendered* HTML and the
    
  41.   *behavior* of web pages, namely JavaScript functionality. Django also
    
  42.   provides special support for those frameworks; see the section on
    
  43.   :class:`~django.test.LiveServerTestCase` for more details.
    
  44. 
    
  45. A comprehensive test suite should use a combination of all of these test types.
    
  46. 
    
  47. Overview and a quick example
    
  48. ----------------------------
    
  49. 
    
  50. To use the test client, instantiate ``django.test.Client`` and retrieve
    
  51. web pages::
    
  52. 
    
  53.     >>> from django.test import Client
    
  54.     >>> c = Client()
    
  55.     >>> response = c.post('/login/', {'username': 'john', 'password': 'smith'})
    
  56.     >>> response.status_code
    
  57.     200
    
  58.     >>> response = c.get('/customer/details/')
    
  59.     >>> response.content
    
  60.     b'<!DOCTYPE html...'
    
  61. 
    
  62. As this example suggests, you can instantiate ``Client`` from within a session
    
  63. of the Python interactive interpreter.
    
  64. 
    
  65. Note a few important things about how the test client works:
    
  66. 
    
  67. * The test client does *not* require the web server to be running. In fact,
    
  68.   it will run just fine with no web server running at all! That's because
    
  69.   it avoids the overhead of HTTP and deals directly with the Django
    
  70.   framework. This helps make the unit tests run quickly.
    
  71. 
    
  72. * When retrieving pages, remember to specify the *path* of the URL, not the
    
  73.   whole domain. For example, this is correct::
    
  74. 
    
  75.       >>> c.get('/login/')
    
  76. 
    
  77.   This is incorrect::
    
  78. 
    
  79.       >>> c.get('https://www.example.com/login/')
    
  80. 
    
  81.   The test client is not capable of retrieving web pages that are not
    
  82.   powered by your Django project. If you need to retrieve other web pages,
    
  83.   use a Python standard library module such as :mod:`urllib`.
    
  84. 
    
  85. * To resolve URLs, the test client uses whatever URLconf is pointed-to by
    
  86.   your :setting:`ROOT_URLCONF` setting.
    
  87. 
    
  88. * Although the above example would work in the Python interactive
    
  89.   interpreter, some of the test client's functionality, notably the
    
  90.   template-related functionality, is only available *while tests are
    
  91.   running*.
    
  92. 
    
  93.   The reason for this is that Django's test runner performs a bit of black
    
  94.   magic in order to determine which template was loaded by a given view.
    
  95.   This black magic (essentially a patching of Django's template system in
    
  96.   memory) only happens during test running.
    
  97. 
    
  98. * By default, the test client will disable any CSRF checks
    
  99.   performed by your site.
    
  100. 
    
  101.   If, for some reason, you *want* the test client to perform CSRF
    
  102.   checks, you can create an instance of the test client that
    
  103.   enforces CSRF checks. To do this, pass in the
    
  104.   ``enforce_csrf_checks`` argument when you construct your
    
  105.   client::
    
  106. 
    
  107.       >>> from django.test import Client
    
  108.       >>> csrf_client = Client(enforce_csrf_checks=True)
    
  109. 
    
  110. Making requests
    
  111. ---------------
    
  112. 
    
  113. Use the ``django.test.Client`` class to make requests.
    
  114. 
    
  115. .. class:: Client(enforce_csrf_checks=False, raise_request_exception=True, json_encoder=DjangoJSONEncoder, **defaults)
    
  116. 
    
  117.     It requires no arguments at time of construction. However, you can use
    
  118.     keyword arguments to specify some default headers. For example, this will
    
  119.     send a ``User-Agent`` HTTP header in each request::
    
  120. 
    
  121.         >>> c = Client(HTTP_USER_AGENT='Mozilla/5.0')
    
  122. 
    
  123.     The values from the ``extra`` keyword arguments passed to
    
  124.     :meth:`~django.test.Client.get()`,
    
  125.     :meth:`~django.test.Client.post()`, etc. have precedence over
    
  126.     the defaults passed to the class constructor.
    
  127. 
    
  128.     The ``enforce_csrf_checks`` argument can be used to test CSRF
    
  129.     protection (see above).
    
  130. 
    
  131.     The ``raise_request_exception`` argument allows controlling whether or not
    
  132.     exceptions raised during the request should also be raised in the test.
    
  133.     Defaults to ``True``.
    
  134. 
    
  135.     The ``json_encoder`` argument allows setting a custom JSON encoder for
    
  136.     the JSON serialization that's described in :meth:`post`.
    
  137. 
    
  138.     Once you have a ``Client`` instance, you can call any of the following
    
  139.     methods:
    
  140. 
    
  141.     .. method:: Client.get(path, data=None, follow=False, secure=False, **extra)
    
  142. 
    
  143.         Makes a GET request on the provided ``path`` and returns a ``Response``
    
  144.         object, which is documented below.
    
  145. 
    
  146.         The key-value pairs in the ``data`` dictionary are used to create a GET
    
  147.         data payload. For example::
    
  148. 
    
  149.             >>> c = Client()
    
  150.             >>> c.get('/customers/details/', {'name': 'fred', 'age': 7})
    
  151. 
    
  152.         ...will result in the evaluation of a GET request equivalent to::
    
  153. 
    
  154.             /customers/details/?name=fred&age=7
    
  155. 
    
  156.         The ``extra`` keyword arguments parameter can be used to specify
    
  157.         headers to be sent in the request. For example::
    
  158. 
    
  159.             >>> c = Client()
    
  160.             >>> c.get('/customers/details/', {'name': 'fred', 'age': 7},
    
  161.             ...       HTTP_ACCEPT='application/json')
    
  162. 
    
  163.         ...will send the HTTP header ``HTTP_ACCEPT`` to the details view, which
    
  164.         is a good way to test code paths that use the
    
  165.         :meth:`django.http.HttpRequest.accepts()` method.
    
  166. 
    
  167.         .. admonition:: CGI specification
    
  168. 
    
  169.             The headers sent via ``**extra`` should follow CGI_ specification.
    
  170.             For example, emulating a different "Host" header as sent in the
    
  171.             HTTP request from the browser to the server should be passed
    
  172.             as ``HTTP_HOST``.
    
  173. 
    
  174.             .. _CGI: https://www.w3.org/CGI/
    
  175. 
    
  176.         If you already have the GET arguments in URL-encoded form, you can
    
  177.         use that encoding instead of using the data argument. For example,
    
  178.         the previous GET request could also be posed as::
    
  179. 
    
  180.         >>> c = Client()
    
  181.         >>> c.get('/customers/details/?name=fred&age=7')
    
  182. 
    
  183.         If you provide a URL with both an encoded GET data and a data argument,
    
  184.         the data argument will take precedence.
    
  185. 
    
  186.         If you set ``follow`` to ``True`` the client will follow any redirects
    
  187.         and a ``redirect_chain`` attribute will be set in the response object
    
  188.         containing tuples of the intermediate urls and status codes.
    
  189. 
    
  190.         If you had a URL ``/redirect_me/`` that redirected to ``/next/``, that
    
  191.         redirected to ``/final/``, this is what you'd see::
    
  192. 
    
  193.             >>> response = c.get('/redirect_me/', follow=True)
    
  194.             >>> response.redirect_chain
    
  195.             [('http://testserver/next/', 302), ('http://testserver/final/', 302)]
    
  196. 
    
  197.         If you set ``secure`` to ``True`` the client will emulate an HTTPS
    
  198.         request.
    
  199. 
    
  200.     .. method:: Client.post(path, data=None, content_type=MULTIPART_CONTENT, follow=False, secure=False, **extra)
    
  201. 
    
  202.         Makes a POST request on the provided ``path`` and returns a
    
  203.         ``Response`` object, which is documented below.
    
  204. 
    
  205.         The key-value pairs in the ``data`` dictionary are used to submit POST
    
  206.         data. For example::
    
  207. 
    
  208.             >>> c = Client()
    
  209.             >>> c.post('/login/', {'name': 'fred', 'passwd': 'secret'})
    
  210. 
    
  211.         ...will result in the evaluation of a POST request to this URL::
    
  212. 
    
  213.             /login/
    
  214. 
    
  215.         ...with this POST data::
    
  216. 
    
  217.             name=fred&passwd=secret
    
  218. 
    
  219.         If you provide ``content_type`` as :mimetype:`application/json`, the
    
  220.         ``data`` is serialized using :func:`json.dumps` if it's a dict, list,
    
  221.         or tuple. Serialization is performed with
    
  222.         :class:`~django.core.serializers.json.DjangoJSONEncoder` by default,
    
  223.         and can be overridden by providing a ``json_encoder`` argument to
    
  224.         :class:`Client`. This serialization also happens for :meth:`put`,
    
  225.         :meth:`patch`, and :meth:`delete` requests.
    
  226. 
    
  227.         If you provide any other ``content_type`` (e.g. :mimetype:`text/xml`
    
  228.         for an XML payload), the contents of ``data`` are sent as-is in the
    
  229.         POST request, using ``content_type`` in the HTTP ``Content-Type``
    
  230.         header.
    
  231. 
    
  232.         If you don't provide a value for ``content_type``, the values in
    
  233.         ``data`` will be transmitted with a content type of
    
  234.         :mimetype:`multipart/form-data`. In this case, the key-value pairs in
    
  235.         ``data`` will be encoded as a multipart message and used to create the
    
  236.         POST data payload.
    
  237. 
    
  238.         To submit multiple values for a given key -- for example, to specify
    
  239.         the selections for a ``<select multiple>`` -- provide the values as a
    
  240.         list or tuple for the required key. For example, this value of ``data``
    
  241.         would submit three selected values for the field named ``choices``::
    
  242. 
    
  243.             {'choices': ('a', 'b', 'd')}
    
  244. 
    
  245.         Submitting files is a special case. To POST a file, you need only
    
  246.         provide the file field name as a key, and a file handle to the file you
    
  247.         wish to upload as a value. For example, if your form has fields
    
  248.         ``name`` and ``attachment``, the latter a
    
  249.         :class:`~django.forms.FileField`::
    
  250. 
    
  251.             >>> c = Client()
    
  252.             >>> with open('wishlist.doc', 'rb') as fp:
    
  253.             ...     c.post('/customers/wishes/', {'name': 'fred', 'attachment': fp})
    
  254. 
    
  255.         You may also provide any file-like object (e.g., :class:`~io.StringIO` or
    
  256.         :class:`~io.BytesIO`) as a file handle. If you're uploading to an
    
  257.         :class:`~django.db.models.ImageField`, the object needs a ``name``
    
  258.         attribute that passes the
    
  259.         :data:`~django.core.validators.validate_image_file_extension` validator.
    
  260.         For example::
    
  261. 
    
  262.             >>> from io import BytesIO
    
  263.             >>> img = BytesIO(
    
  264.             ...     b"GIF89a\x01\x00\x01\x00\x00\x00\x00!\xf9\x04\x01\x00\x00\x00"
    
  265.             ...     b"\x00,\x00\x00\x00\x00\x01\x00\x01\x00\x00\x02\x01\x00\x00"
    
  266.             ... )
    
  267.             >>> img.name = "myimage.gif"
    
  268. 
    
  269.         Note that if you wish to use the same file handle for multiple
    
  270.         ``post()`` calls then you will need to manually reset the file
    
  271.         pointer between posts. The easiest way to do this is to
    
  272.         manually close the file after it has been provided to
    
  273.         ``post()``, as demonstrated above.
    
  274. 
    
  275.         You should also ensure that the file is opened in a way that
    
  276.         allows the data to be read. If your file contains binary data
    
  277.         such as an image, this means you will need to open the file in
    
  278.         ``rb`` (read binary) mode.
    
  279. 
    
  280.         The ``extra`` argument acts the same as for :meth:`Client.get`.
    
  281. 
    
  282.         If the URL you request with a POST contains encoded parameters, these
    
  283.         parameters will be made available in the request.GET data. For example,
    
  284.         if you were to make the request::
    
  285. 
    
  286.         >>> c.post('/login/?visitor=true', {'name': 'fred', 'passwd': 'secret'})
    
  287. 
    
  288.         ... the view handling this request could interrogate request.POST
    
  289.         to retrieve the username and password, and could interrogate request.GET
    
  290.         to determine if the user was a visitor.
    
  291. 
    
  292.         If you set ``follow`` to ``True`` the client will follow any redirects
    
  293.         and a ``redirect_chain`` attribute will be set in the response object
    
  294.         containing tuples of the intermediate urls and status codes.
    
  295. 
    
  296.         If you set ``secure`` to ``True`` the client will emulate an HTTPS
    
  297.         request.
    
  298. 
    
  299.     .. method:: Client.head(path, data=None, follow=False, secure=False, **extra)
    
  300. 
    
  301.         Makes a HEAD request on the provided ``path`` and returns a
    
  302.         ``Response`` object. This method works just like :meth:`Client.get`,
    
  303.         including the ``follow``, ``secure`` and ``extra`` arguments, except
    
  304.         it does not return a message body.
    
  305. 
    
  306.     .. method:: Client.options(path, data='', content_type='application/octet-stream', follow=False, secure=False, **extra)
    
  307. 
    
  308.         Makes an OPTIONS request on the provided ``path`` and returns a
    
  309.         ``Response`` object. Useful for testing RESTful interfaces.
    
  310. 
    
  311.         When ``data`` is provided, it is used as the request body, and
    
  312.         a ``Content-Type`` header is set to ``content_type``.
    
  313. 
    
  314.         The ``follow``, ``secure`` and ``extra`` arguments act the same as for
    
  315.         :meth:`Client.get`.
    
  316. 
    
  317.     .. method:: Client.put(path, data='', content_type='application/octet-stream', follow=False, secure=False, **extra)
    
  318. 
    
  319.         Makes a PUT request on the provided ``path`` and returns a
    
  320.         ``Response`` object. Useful for testing RESTful interfaces.
    
  321. 
    
  322.         When ``data`` is provided, it is used as the request body, and
    
  323.         a ``Content-Type`` header is set to ``content_type``.
    
  324. 
    
  325.         The ``follow``, ``secure`` and ``extra`` arguments act the same as for
    
  326.         :meth:`Client.get`.
    
  327. 
    
  328.     .. method:: Client.patch(path, data='', content_type='application/octet-stream', follow=False, secure=False, **extra)
    
  329. 
    
  330.         Makes a PATCH request on the provided ``path`` and returns a
    
  331.         ``Response`` object. Useful for testing RESTful interfaces.
    
  332. 
    
  333.         The ``follow``, ``secure`` and ``extra`` arguments act the same as for
    
  334.         :meth:`Client.get`.
    
  335. 
    
  336.     .. method:: Client.delete(path, data='', content_type='application/octet-stream', follow=False, secure=False, **extra)
    
  337. 
    
  338.         Makes a DELETE request on the provided ``path`` and returns a
    
  339.         ``Response`` object. Useful for testing RESTful interfaces.
    
  340. 
    
  341.         When ``data`` is provided, it is used as the request body, and
    
  342.         a ``Content-Type`` header is set to ``content_type``.
    
  343. 
    
  344.         The ``follow``, ``secure`` and ``extra`` arguments act the same as for
    
  345.         :meth:`Client.get`.
    
  346. 
    
  347.     .. method:: Client.trace(path, follow=False, secure=False, **extra)
    
  348. 
    
  349.         Makes a TRACE request on the provided ``path`` and returns a
    
  350.         ``Response`` object. Useful for simulating diagnostic probes.
    
  351. 
    
  352.         Unlike the other request methods, ``data`` is not provided as a keyword
    
  353.         parameter in order to comply with :rfc:`7231#section-4.3.8`, which
    
  354.         mandates that TRACE requests must not have a body.
    
  355. 
    
  356.         The ``follow``, ``secure``, and ``extra`` arguments act the same as for
    
  357.         :meth:`Client.get`.
    
  358. 
    
  359.     .. method:: Client.login(**credentials)
    
  360. 
    
  361.         If your site uses Django's :doc:`authentication system</topics/auth/index>`
    
  362.         and you deal with logging in users, you can use the test client's
    
  363.         ``login()`` method to simulate the effect of a user logging into the
    
  364.         site.
    
  365. 
    
  366.         After you call this method, the test client will have all the cookies
    
  367.         and session data required to pass any login-based tests that may form
    
  368.         part of a view.
    
  369. 
    
  370.         The format of the ``credentials`` argument depends on which
    
  371.         :ref:`authentication backend <authentication-backends>` you're using
    
  372.         (which is configured by your :setting:`AUTHENTICATION_BACKENDS`
    
  373.         setting). If you're using the standard authentication backend provided
    
  374.         by Django (``ModelBackend``), ``credentials`` should be the user's
    
  375.         username and password, provided as keyword arguments::
    
  376. 
    
  377.             >>> c = Client()
    
  378.             >>> c.login(username='fred', password='secret')
    
  379. 
    
  380.             # Now you can access a view that's only available to logged-in users.
    
  381. 
    
  382.         If you're using a different authentication backend, this method may
    
  383.         require different credentials. It requires whichever credentials are
    
  384.         required by your backend's ``authenticate()`` method.
    
  385. 
    
  386.         ``login()`` returns ``True`` if it the credentials were accepted and
    
  387.         login was successful.
    
  388. 
    
  389.         Finally, you'll need to remember to create user accounts before you can
    
  390.         use this method. As we explained above, the test runner is executed
    
  391.         using a test database, which contains no users by default. As a result,
    
  392.         user accounts that are valid on your production site will not work
    
  393.         under test conditions. You'll need to create users as part of the test
    
  394.         suite -- either manually (using the Django model API) or with a test
    
  395.         fixture. Remember that if you want your test user to have a password,
    
  396.         you can't set the user's password by setting the password attribute
    
  397.         directly -- you must use the
    
  398.         :meth:`~django.contrib.auth.models.User.set_password()` function to
    
  399.         store a correctly hashed password. Alternatively, you can use the
    
  400.         :meth:`~django.contrib.auth.models.UserManager.create_user` helper
    
  401.         method to create a new user with a correctly hashed password.
    
  402. 
    
  403.     .. method:: Client.force_login(user, backend=None)
    
  404. 
    
  405.         If your site uses Django's :doc:`authentication
    
  406.         system</topics/auth/index>`, you can use the ``force_login()`` method
    
  407.         to simulate the effect of a user logging into the site. Use this method
    
  408.         instead of :meth:`login` when a test requires a user be logged in and
    
  409.         the details of how a user logged in aren't important.
    
  410. 
    
  411.         Unlike ``login()``, this method skips the authentication and
    
  412.         verification steps: inactive users (:attr:`is_active=False
    
  413.         <django.contrib.auth.models.User.is_active>`) are permitted to login
    
  414.         and the user's credentials don't need to be provided.
    
  415. 
    
  416.         The user will have its ``backend`` attribute set to the value of the
    
  417.         ``backend`` argument (which should be a dotted Python path string), or
    
  418.         to ``settings.AUTHENTICATION_BACKENDS[0]`` if a value isn't provided.
    
  419.         The :func:`~django.contrib.auth.authenticate` function called by
    
  420.         :meth:`login` normally annotates the user like this.
    
  421. 
    
  422.         This method is faster than ``login()`` since the expensive
    
  423.         password hashing algorithms are bypassed. Also, you can speed up
    
  424.         ``login()`` by :ref:`using a weaker hasher while testing
    
  425.         <speeding-up-tests-auth-hashers>`.
    
  426. 
    
  427.     .. method:: Client.logout()
    
  428. 
    
  429.         If your site uses Django's :doc:`authentication system</topics/auth/index>`,
    
  430.         the ``logout()`` method can be used to simulate the effect of a user
    
  431.         logging out of your site.
    
  432. 
    
  433.         After you call this method, the test client will have all the cookies
    
  434.         and session data cleared to defaults. Subsequent requests will appear
    
  435.         to come from an :class:`~django.contrib.auth.models.AnonymousUser`.
    
  436. 
    
  437. Testing responses
    
  438. -----------------
    
  439. 
    
  440. The ``get()`` and ``post()`` methods both return a ``Response`` object. This
    
  441. ``Response`` object is *not* the same as the ``HttpResponse`` object returned
    
  442. by Django views; the test response object has some additional data useful for
    
  443. test code to verify.
    
  444. 
    
  445. Specifically, a ``Response`` object has the following attributes:
    
  446. 
    
  447. .. class:: Response()
    
  448. 
    
  449.     .. attribute:: client
    
  450. 
    
  451.         The test client that was used to make the request that resulted in the
    
  452.         response.
    
  453. 
    
  454.     .. attribute:: content
    
  455. 
    
  456.         The body of the response, as a bytestring. This is the final page
    
  457.         content as rendered by the view, or any error message.
    
  458. 
    
  459.     .. attribute:: context
    
  460. 
    
  461.         The template ``Context`` instance that was used to render the template that
    
  462.         produced the response content.
    
  463. 
    
  464.         If the rendered page used multiple templates, then ``context`` will be a
    
  465.         list of ``Context`` objects, in the order in which they were rendered.
    
  466. 
    
  467.         Regardless of the number of templates used during rendering, you can
    
  468.         retrieve context values using the ``[]`` operator. For example, the
    
  469.         context variable ``name`` could be retrieved using::
    
  470. 
    
  471.             >>> response = client.get('/foo/')
    
  472.             >>> response.context['name']
    
  473.             'Arthur'
    
  474. 
    
  475.         .. admonition:: Not using Django templates?
    
  476. 
    
  477.             This attribute is only populated when using the
    
  478.             :class:`~django.template.backends.django.DjangoTemplates` backend.
    
  479.             If you're using another template engine,
    
  480.             :attr:`~django.template.response.SimpleTemplateResponse.context_data`
    
  481.             may be a suitable alternative on responses with that attribute.
    
  482. 
    
  483.     .. attribute:: exc_info
    
  484. 
    
  485.         A tuple of three values that provides information about the unhandled
    
  486.         exception, if any, that occurred during the view.
    
  487. 
    
  488.         The values are (type, value, traceback), the same as returned by
    
  489.         Python's :func:`sys.exc_info`. Their meanings are:
    
  490. 
    
  491.         - *type*: The type of the exception.
    
  492.         - *value*: The exception instance.
    
  493.         - *traceback*: A traceback object which encapsulates the call stack at
    
  494.           the point where the exception originally occurred.
    
  495. 
    
  496.         If no exception occurred, then ``exc_info`` will be ``None``.
    
  497. 
    
  498.     .. method:: json(**kwargs)
    
  499. 
    
  500.         The body of the response, parsed as JSON. Extra keyword arguments are
    
  501.         passed to :func:`json.loads`. For example::
    
  502. 
    
  503.             >>> response = client.get('/foo/')
    
  504.             >>> response.json()['name']
    
  505.             'Arthur'
    
  506. 
    
  507.         If the ``Content-Type`` header is not ``"application/json"``, then a
    
  508.         :exc:`ValueError` will be raised when trying to parse the response.
    
  509. 
    
  510.     .. attribute:: request
    
  511. 
    
  512.         The request data that stimulated the response.
    
  513. 
    
  514.     .. attribute:: wsgi_request
    
  515. 
    
  516.         The ``WSGIRequest`` instance generated by the test handler that
    
  517.         generated the response.
    
  518. 
    
  519.     .. attribute:: status_code
    
  520. 
    
  521.         The HTTP status of the response, as an integer. For a full list
    
  522.         of defined codes, see the `IANA status code registry`_.
    
  523. 
    
  524.         .. _IANA status code registry: https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
    
  525. 
    
  526.     .. attribute:: templates
    
  527. 
    
  528.         A list of ``Template`` instances used to render the final content, in
    
  529.         the order they were rendered. For each template in the list, use
    
  530.         ``template.name`` to get the template's file name, if the template was
    
  531.         loaded from a file. (The name is a string such as
    
  532.         ``'admin/index.html'``.)
    
  533. 
    
  534.         .. admonition:: Not using Django templates?
    
  535. 
    
  536.             This attribute is only populated when using the
    
  537.             :class:`~django.template.backends.django.DjangoTemplates` backend.
    
  538.             If you're using another template engine,
    
  539.             :attr:`~django.template.response.SimpleTemplateResponse.template_name`
    
  540.             may be a suitable alternative if you only need the name of the
    
  541.             template used for rendering.
    
  542. 
    
  543.     .. attribute:: resolver_match
    
  544. 
    
  545.         An instance of :class:`~django.urls.ResolverMatch` for the response.
    
  546.         You can use the :attr:`~django.urls.ResolverMatch.func` attribute, for
    
  547.         example, to verify the view that served the response::
    
  548. 
    
  549.             # my_view here is a function based view.
    
  550.             self.assertEqual(response.resolver_match.func, my_view)
    
  551. 
    
  552.             # Class-based views need to compare the view_class, as the
    
  553.             # functions generated by as_view() won't be equal.
    
  554.             self.assertIs(response.resolver_match.func.view_class, MyView)
    
  555. 
    
  556.         If the given URL is not found, accessing this attribute will raise a
    
  557.         :exc:`~django.urls.Resolver404` exception.
    
  558. 
    
  559. As with a normal response, you can also access the headers through
    
  560. :attr:`.HttpResponse.headers`. For example, you could determine the content
    
  561. type of a response using ``response.headers['Content-Type']``.
    
  562. 
    
  563. Exceptions
    
  564. ----------
    
  565. 
    
  566. If you point the test client at a view that raises an exception and
    
  567. ``Client.raise_request_exception`` is ``True``, that exception will be visible
    
  568. in the test case. You can then use a standard ``try ... except`` block or
    
  569. :meth:`~unittest.TestCase.assertRaises` to test for exceptions.
    
  570. 
    
  571. The only exceptions that are not visible to the test client are
    
  572. :class:`~django.http.Http404`,
    
  573. :class:`~django.core.exceptions.PermissionDenied`, :exc:`SystemExit`, and
    
  574. :class:`~django.core.exceptions.SuspiciousOperation`. Django catches these
    
  575. exceptions internally and converts them into the appropriate HTTP response
    
  576. codes. In these cases, you can check ``response.status_code`` in your test.
    
  577. 
    
  578. If ``Client.raise_request_exception`` is ``False``, the test client will return a
    
  579. 500 response as would be returned to a browser. The response has the attribute
    
  580. :attr:`~Response.exc_info` to provide information about the unhandled
    
  581. exception.
    
  582. 
    
  583. Persistent state
    
  584. ----------------
    
  585. 
    
  586. The test client is stateful. If a response returns a cookie, then that cookie
    
  587. will be stored in the test client and sent with all subsequent ``get()`` and
    
  588. ``post()`` requests.
    
  589. 
    
  590. Expiration policies for these cookies are not followed. If you want a cookie
    
  591. to expire, either delete it manually or create a new ``Client`` instance (which
    
  592. will effectively delete all cookies).
    
  593. 
    
  594. A test client has attributes that store persistent state information. You can
    
  595. access these properties as part of a test condition.
    
  596. 
    
  597. .. attribute:: Client.cookies
    
  598. 
    
  599.     A Python :class:`~http.cookies.SimpleCookie` object, containing the current
    
  600.     values of all the client cookies. See the documentation of the
    
  601.     :mod:`http.cookies` module for more.
    
  602. 
    
  603. .. attribute:: Client.session
    
  604. 
    
  605.     A dictionary-like object containing session information. See the
    
  606.     :doc:`session documentation</topics/http/sessions>` for full details.
    
  607. 
    
  608.     To modify the session and then save it, it must be stored in a variable
    
  609.     first (because a new ``SessionStore`` is created every time this property
    
  610.     is accessed)::
    
  611. 
    
  612.         def test_something(self):
    
  613.             session = self.client.session
    
  614.             session['somekey'] = 'test'
    
  615.             session.save()
    
  616. 
    
  617. Setting the language
    
  618. --------------------
    
  619. 
    
  620. When testing applications that support internationalization and localization,
    
  621. you might want to set the language for a test client request. The method for
    
  622. doing so depends on whether or not the
    
  623. :class:`~django.middleware.locale.LocaleMiddleware` is enabled.
    
  624. 
    
  625. If the middleware is enabled, the language can be set by creating a cookie with
    
  626. a name of :setting:`LANGUAGE_COOKIE_NAME` and a value of the language code::
    
  627. 
    
  628.     from django.conf import settings
    
  629. 
    
  630.     def test_language_using_cookie(self):
    
  631.         self.client.cookies.load({settings.LANGUAGE_COOKIE_NAME: 'fr'})
    
  632.         response = self.client.get('/')
    
  633.         self.assertEqual(response.content, b"Bienvenue sur mon site.")
    
  634. 
    
  635. or by including the ``Accept-Language`` HTTP header in the request::
    
  636. 
    
  637.     def test_language_using_header(self):
    
  638.         response = self.client.get('/', HTTP_ACCEPT_LANGUAGE='fr')
    
  639.         self.assertEqual(response.content, b"Bienvenue sur mon site.")
    
  640. 
    
  641. .. note::
    
  642. 
    
  643.     When using these methods, ensure to reset the active language at the end of
    
  644.     each test::
    
  645. 
    
  646.         def tearDown(self):
    
  647.             translation.activate(settings.LANGUAGE_CODE)
    
  648. 
    
  649. More details are in :ref:`how-django-discovers-language-preference`.
    
  650. 
    
  651. If the middleware isn't enabled, the active language may be set using
    
  652. :func:`.translation.override`::
    
  653. 
    
  654.     from django.utils import translation
    
  655. 
    
  656.     def test_language_using_override(self):
    
  657.         with translation.override('fr'):
    
  658.             response = self.client.get('/')
    
  659.         self.assertEqual(response.content, b"Bienvenue sur mon site.")
    
  660. 
    
  661. More details are in :ref:`explicitly-setting-the-active-language`.
    
  662. 
    
  663. Example
    
  664. -------
    
  665. 
    
  666. The following is a unit test using the test client::
    
  667. 
    
  668.     import unittest
    
  669.     from django.test import Client
    
  670. 
    
  671.     class SimpleTest(unittest.TestCase):
    
  672.         def setUp(self):
    
  673.             # Every test needs a client.
    
  674.             self.client = Client()
    
  675. 
    
  676.         def test_details(self):
    
  677.             # Issue a GET request.
    
  678.             response = self.client.get('/customer/details/')
    
  679. 
    
  680.             # Check that the response is 200 OK.
    
  681.             self.assertEqual(response.status_code, 200)
    
  682. 
    
  683.             # Check that the rendered context contains 5 customers.
    
  684.             self.assertEqual(len(response.context['customers']), 5)
    
  685. 
    
  686. .. seealso::
    
  687. 
    
  688.     :class:`django.test.RequestFactory`
    
  689. 
    
  690. .. _django-testcase-subclasses:
    
  691. 
    
  692. Provided test case classes
    
  693. ==========================
    
  694. 
    
  695. Normal Python unit test classes extend a base class of
    
  696. :class:`unittest.TestCase`. Django provides a few extensions of this base class:
    
  697. 
    
  698. .. _testcase_hierarchy_diagram:
    
  699. 
    
  700. .. figure:: _images/django_unittest_classes_hierarchy.*
    
  701.    :alt: Hierarchy of Django unit testing classes (TestCase subclasses)
    
  702.    :width: 508
    
  703.    :height: 328
    
  704. 
    
  705.    Hierarchy of Django unit testing classes
    
  706. 
    
  707. You can convert a normal :class:`unittest.TestCase` to any of the subclasses:
    
  708. change the base class of your test from ``unittest.TestCase`` to the subclass.
    
  709. All of the standard Python unit test functionality will be available, and it
    
  710. will be augmented with some useful additions as described in each section
    
  711. below.
    
  712. 
    
  713. ``SimpleTestCase``
    
  714. ------------------
    
  715. 
    
  716. .. class:: SimpleTestCase()
    
  717. 
    
  718. A subclass of :class:`unittest.TestCase` that adds this functionality:
    
  719. 
    
  720. * Some useful assertions like:
    
  721. 
    
  722.   * Checking that a callable :meth:`raises a certain exception
    
  723.     <SimpleTestCase.assertRaisesMessage>`.
    
  724.   * Checking that a callable :meth:`triggers a certain warning
    
  725.     <SimpleTestCase.assertWarnsMessage>`.
    
  726.   * Testing form field :meth:`rendering and error treatment
    
  727.     <SimpleTestCase.assertFieldOutput>`.
    
  728.   * Testing :meth:`HTML responses for the presence/lack of a given fragment
    
  729.     <SimpleTestCase.assertContains>`.
    
  730.   * Verifying that a template :meth:`has/hasn't been used to generate a given
    
  731.     response content <SimpleTestCase.assertTemplateUsed>`.
    
  732.   * Verifying that two :meth:`URLs <SimpleTestCase.assertURLEqual>` are equal.
    
  733.   * Verifying an HTTP :meth:`redirect <SimpleTestCase.assertRedirects>` is
    
  734.     performed by the app.
    
  735.   * Robustly testing two :meth:`HTML fragments <SimpleTestCase.assertHTMLEqual>`
    
  736.     for equality/inequality or :meth:`containment <SimpleTestCase.assertInHTML>`.
    
  737.   * Robustly testing two :meth:`XML fragments <SimpleTestCase.assertXMLEqual>`
    
  738.     for equality/inequality.
    
  739.   * Robustly testing two :meth:`JSON fragments <SimpleTestCase.assertJSONEqual>`
    
  740.     for equality.
    
  741. 
    
  742. * The ability to run tests with :ref:`modified settings <overriding-settings>`.
    
  743. * Using the :attr:`~SimpleTestCase.client` :class:`~django.test.Client`.
    
  744. 
    
  745. If your tests make any database queries, use subclasses
    
  746. :class:`~django.test.TransactionTestCase` or :class:`~django.test.TestCase`.
    
  747. 
    
  748. .. attribute:: SimpleTestCase.databases
    
  749. 
    
  750.     :class:`~SimpleTestCase` disallows database queries by default. This
    
  751.     helps to avoid executing write queries which will affect other tests
    
  752.     since each ``SimpleTestCase`` test isn't run in a transaction. If you
    
  753.     aren't concerned about this problem, you can disable this behavior by
    
  754.     setting the ``databases`` class attribute to ``'__all__'`` on your test
    
  755.     class.
    
  756. 
    
  757. .. warning::
    
  758. 
    
  759.     ``SimpleTestCase`` and its subclasses (e.g. ``TestCase``, ...) rely on
    
  760.     ``setUpClass()`` and ``tearDownClass()`` to perform some class-wide
    
  761.     initialization (e.g. overriding settings). If you need to override those
    
  762.     methods, don't forget to call the ``super`` implementation::
    
  763. 
    
  764.         class MyTestCase(TestCase):
    
  765. 
    
  766.             @classmethod
    
  767.             def setUpClass(cls):
    
  768.                 super().setUpClass()
    
  769.                 ...
    
  770. 
    
  771.             @classmethod
    
  772.             def tearDownClass(cls):
    
  773.                 ...
    
  774.                 super().tearDownClass()
    
  775. 
    
  776.     Be sure to account for Python's behavior if an exception is raised during
    
  777.     ``setUpClass()``. If that happens, neither the tests in the class nor
    
  778.     ``tearDownClass()`` are run. In the case of :class:`django.test.TestCase`,
    
  779.     this will leak the transaction created in ``super()``  which results in
    
  780.     various symptoms including a segmentation fault on some platforms (reported
    
  781.     on macOS). If you want to intentionally raise an exception such as
    
  782.     :exc:`unittest.SkipTest` in ``setUpClass()``, be sure to do it before
    
  783.     calling ``super()`` to avoid this.
    
  784. 
    
  785. ``TransactionTestCase``
    
  786. -----------------------
    
  787. 
    
  788. .. class:: TransactionTestCase()
    
  789. 
    
  790. ``TransactionTestCase`` inherits from :class:`~django.test.SimpleTestCase` to
    
  791. add some database-specific features:
    
  792. 
    
  793. * Resetting the database to a known state at the beginning of each test to
    
  794.   ease testing and using the ORM.
    
  795. * Database :attr:`~TransactionTestCase.fixtures`.
    
  796. * Test :ref:`skipping based on database backend features <skipping-tests>`.
    
  797. * The remaining specialized :meth:`assert*
    
  798.   <TransactionTestCase.assertQuerysetEqual>` methods.
    
  799. 
    
  800. Django's :class:`TestCase` class is a more commonly used subclass of
    
  801. ``TransactionTestCase`` that makes use of database transaction facilities
    
  802. to speed up the process of resetting the database to a known state at the
    
  803. beginning of each test. A consequence of this, however, is that some database
    
  804. behaviors cannot be tested within a Django ``TestCase`` class. For instance,
    
  805. you cannot test that a block of code is executing within a transaction, as is
    
  806. required when using
    
  807. :meth:`~django.db.models.query.QuerySet.select_for_update()`. In those cases,
    
  808. you should use ``TransactionTestCase``.
    
  809. 
    
  810. ``TransactionTestCase`` and ``TestCase`` are identical except for the manner
    
  811. in which the database is reset to a known state and the ability for test code
    
  812. to test the effects of commit and rollback:
    
  813. 
    
  814. * A ``TransactionTestCase`` resets the database after the test runs by
    
  815.   truncating all tables. A ``TransactionTestCase`` may call commit and rollback
    
  816.   and observe the effects of these calls on the database.
    
  817. 
    
  818. * A ``TestCase``, on the other hand, does not truncate tables after a test.
    
  819.   Instead, it encloses the test code in a database transaction that is rolled
    
  820.   back at the end of the test. This guarantees that the rollback at the end of
    
  821.   the test restores the database to its initial state.
    
  822. 
    
  823. .. warning::
    
  824. 
    
  825.   ``TestCase`` running on a database that does not support rollback (e.g. MySQL
    
  826.   with the MyISAM storage engine), and all instances of ``TransactionTestCase``,
    
  827.   will roll back at the end of the test by deleting all data from the test
    
  828.   database.
    
  829. 
    
  830.   Apps :ref:`will not see their data reloaded <test-case-serialized-rollback>`;
    
  831.   if you need this functionality (for example, third-party apps should enable
    
  832.   this) you can set ``serialized_rollback = True`` inside the
    
  833.   ``TestCase`` body.
    
  834. 
    
  835. ``TestCase``
    
  836. ------------
    
  837. 
    
  838. .. class:: TestCase()
    
  839. 
    
  840. This is the most common class to use for writing tests in Django. It inherits
    
  841. from :class:`TransactionTestCase` (and by extension :class:`SimpleTestCase`).
    
  842. If your Django application doesn't use a database, use :class:`SimpleTestCase`.
    
  843. 
    
  844. The class:
    
  845. 
    
  846. * Wraps the tests within two nested :func:`~django.db.transaction.atomic`
    
  847.   blocks: one for the whole class and one for each test. Therefore, if you want
    
  848.   to test some specific database transaction behavior, use
    
  849.   :class:`TransactionTestCase`.
    
  850. 
    
  851. * Checks deferrable database constraints at the end of each test.
    
  852. 
    
  853. It also provides an additional method:
    
  854. 
    
  855. .. classmethod:: TestCase.setUpTestData()
    
  856. 
    
  857.     The class-level ``atomic`` block described above allows the creation of
    
  858.     initial data at the class level, once for the whole ``TestCase``. This
    
  859.     technique allows for faster tests as compared to using ``setUp()``.
    
  860. 
    
  861.     For example::
    
  862. 
    
  863.         from django.test import TestCase
    
  864. 
    
  865.         class MyTests(TestCase):
    
  866.             @classmethod
    
  867.             def setUpTestData(cls):
    
  868.                 # Set up data for the whole TestCase
    
  869.                 cls.foo = Foo.objects.create(bar="Test")
    
  870.                 ...
    
  871. 
    
  872.             def test1(self):
    
  873.                 # Some test using self.foo
    
  874.                 ...
    
  875. 
    
  876.             def test2(self):
    
  877.                 # Some other test using self.foo
    
  878.                 ...
    
  879. 
    
  880.     Note that if the tests are run on a database with no transaction support
    
  881.     (for instance, MySQL with the MyISAM engine), ``setUpTestData()`` will be
    
  882.     called before each test, negating the speed benefits.
    
  883. 
    
  884.     Objects assigned to class attributes in ``setUpTestData()`` must support
    
  885.     creating deep copies with :py:func:`copy.deepcopy` in order to isolate them
    
  886.     from alterations performed by each test methods.
    
  887. 
    
  888. .. classmethod:: TestCase.captureOnCommitCallbacks(using=DEFAULT_DB_ALIAS, execute=False)
    
  889. 
    
  890.     Returns a context manager that captures :func:`transaction.on_commit()
    
  891.     <django.db.transaction.on_commit>` callbacks for the given database
    
  892.     connection. It returns a list that contains, on exit of the context, the
    
  893.     captured callback functions. From this list you can make assertions on the
    
  894.     callbacks or call them to invoke their side effects, emulating a commit.
    
  895. 
    
  896.     ``using`` is the alias of the database connection to capture callbacks for.
    
  897. 
    
  898.     If ``execute`` is ``True``, all the callbacks will be called as the context
    
  899.     manager exits, if no exception occurred. This emulates a commit after the
    
  900.     wrapped block of code.
    
  901. 
    
  902.     For example::
    
  903. 
    
  904.         from django.core import mail
    
  905.         from django.test import TestCase
    
  906. 
    
  907. 
    
  908.         class ContactTests(TestCase):
    
  909.             def test_post(self):
    
  910.                 with self.captureOnCommitCallbacks(execute=True) as callbacks:
    
  911.                     response = self.client.post(
    
  912.                         '/contact/',
    
  913.                         {'message': 'I like your site'},
    
  914.                     )
    
  915. 
    
  916.                 self.assertEqual(response.status_code, 200)
    
  917.                 self.assertEqual(len(callbacks), 1)
    
  918.                 self.assertEqual(len(mail.outbox), 1)
    
  919.                 self.assertEqual(mail.outbox[0].subject, 'Contact Form')
    
  920.                 self.assertEqual(mail.outbox[0].body, 'I like your site')
    
  921. 
    
  922.     .. versionchanged:: 4.0
    
  923. 
    
  924.         In older versions, new callbacks added while executing
    
  925.         :func:`.transaction.on_commit` callbacks were not captured.
    
  926. 
    
  927. .. _live-test-server:
    
  928. 
    
  929. ``LiveServerTestCase``
    
  930. ----------------------
    
  931. 
    
  932. .. class:: LiveServerTestCase()
    
  933. 
    
  934. ``LiveServerTestCase`` does basically the same as
    
  935. :class:`~django.test.TransactionTestCase` with one extra feature: it launches a
    
  936. live Django server in the background on setup, and shuts it down on teardown.
    
  937. This allows the use of automated test clients other than the
    
  938. :ref:`Django dummy client <test-client>` such as, for example, the Selenium_
    
  939. client, to execute a series of functional tests inside a browser and simulate a
    
  940. real user's actions.
    
  941. 
    
  942. The live server listens on ``localhost`` and binds to port 0 which uses a free
    
  943. port assigned by the operating system. The server's URL can be accessed with
    
  944. ``self.live_server_url`` during the tests.
    
  945. 
    
  946. To demonstrate how to use ``LiveServerTestCase``, let's write a Selenium test.
    
  947. First of all, you need to install the `selenium package`_ into your Python
    
  948. path:
    
  949. 
    
  950. .. console::
    
  951. 
    
  952.     $ python -m pip install selenium
    
  953. 
    
  954. Then, add a ``LiveServerTestCase``-based test to your app's tests module
    
  955. (for example: ``myapp/tests.py``). For this example, we'll assume you're using
    
  956. the :mod:`~django.contrib.staticfiles` app and want to have static files served
    
  957. during the execution of your tests similar to what we get at development time
    
  958. with ``DEBUG=True``, i.e. without having to collect them using
    
  959. :djadmin:`collectstatic`. We'll use
    
  960. the  :class:`~django.contrib.staticfiles.testing.StaticLiveServerTestCase`
    
  961. subclass which provides that functionality. Replace it with
    
  962. ``django.test.LiveServerTestCase`` if you don't need that.
    
  963. 
    
  964. The code for this test may look as follows::
    
  965. 
    
  966.     from django.contrib.staticfiles.testing import StaticLiveServerTestCase
    
  967.     from selenium.webdriver.common.by import By
    
  968.     from selenium.webdriver.firefox.webdriver import WebDriver
    
  969. 
    
  970.     class MySeleniumTests(StaticLiveServerTestCase):
    
  971.         fixtures = ['user-data.json']
    
  972. 
    
  973.         @classmethod
    
  974.         def setUpClass(cls):
    
  975.             super().setUpClass()
    
  976.             cls.selenium = WebDriver()
    
  977.             cls.selenium.implicitly_wait(10)
    
  978. 
    
  979.         @classmethod
    
  980.         def tearDownClass(cls):
    
  981.             cls.selenium.quit()
    
  982.             super().tearDownClass()
    
  983. 
    
  984.         def test_login(self):
    
  985.             self.selenium.get('%s%s' % (self.live_server_url, '/login/'))
    
  986.             username_input = self.selenium.find_element(By.NAME, "username")
    
  987.             username_input.send_keys('myuser')
    
  988.             password_input = self.selenium.find_element(By.NAME, "password")
    
  989.             password_input.send_keys('secret')
    
  990.             self.selenium.find_element(By.XPATH, '//input[@value="Log in"]').click()
    
  991. 
    
  992. Finally, you may run the test as follows:
    
  993. 
    
  994. .. console::
    
  995. 
    
  996.     $ ./manage.py test myapp.tests.MySeleniumTests.test_login
    
  997. 
    
  998. This example will automatically open Firefox then go to the login page, enter
    
  999. the credentials and press the "Log in" button. Selenium offers other drivers in
    
  1000. case you do not have Firefox installed or wish to use another browser. The
    
  1001. example above is just a tiny fraction of what the Selenium client can do; check
    
  1002. out the `full reference`_ for more details.
    
  1003. 
    
  1004. .. _Selenium: https://www.selenium.dev/
    
  1005. .. _selenium package: https://pypi.org/project/selenium/
    
  1006. .. _full reference: https://selenium-python.readthedocs.io/api.html
    
  1007. .. _Firefox: https://www.mozilla.com/firefox/
    
  1008. 
    
  1009. .. note::
    
  1010. 
    
  1011.     When using an in-memory SQLite database to run the tests, the same database
    
  1012.     connection will be shared by two threads in parallel: the thread in which
    
  1013.     the live server is run and the thread in which the test case is run. It's
    
  1014.     important to prevent simultaneous database queries via this shared
    
  1015.     connection by the two threads, as that may sometimes randomly cause the
    
  1016.     tests to fail. So you need to ensure that the two threads don't access the
    
  1017.     database at the same time. In particular, this means that in some cases
    
  1018.     (for example, just after clicking a link or submitting a form), you might
    
  1019.     need to check that a response is received by Selenium and that the next
    
  1020.     page is loaded before proceeding with further test execution.
    
  1021.     Do this, for example, by making Selenium wait until the ``<body>`` HTML tag
    
  1022.     is found in the response (requires Selenium > 2.13)::
    
  1023. 
    
  1024.         def test_login(self):
    
  1025.             from selenium.webdriver.support.wait import WebDriverWait
    
  1026.             timeout = 2
    
  1027.             ...
    
  1028.             self.selenium.find_element(By.XPATH, '//input[@value="Log in"]').click()
    
  1029.             # Wait until the response is received
    
  1030.             WebDriverWait(self.selenium, timeout).until(
    
  1031.                 lambda driver: driver.find_element(By.TAG_NAME, 'body'))
    
  1032. 
    
  1033.     The tricky thing here is that there's really no such thing as a "page load,"
    
  1034.     especially in modern web apps that generate HTML dynamically after the
    
  1035.     server generates the initial document. So, checking for the presence of
    
  1036.     ``<body>`` in the response might not necessarily be appropriate for all use
    
  1037.     cases. Please refer to the `Selenium FAQ`_ and `Selenium documentation`_
    
  1038.     for more information.
    
  1039. 
    
  1040.     .. _Selenium FAQ: https://web.archive.org/web/20160129132110/http://code.google.com/p/selenium/wiki/FrequentlyAskedQuestions#Q:_WebDriver_fails_to_find_elements_/_Does_not_block_on_page_loa
    
  1041.     .. _Selenium documentation: https://www.selenium.dev/documentation/webdriver/waits/#explicit-wait
    
  1042. 
    
  1043. Test cases features
    
  1044. ===================
    
  1045. 
    
  1046. Default test client
    
  1047. -------------------
    
  1048. 
    
  1049. .. attribute:: SimpleTestCase.client
    
  1050. 
    
  1051. Every test case in a ``django.test.*TestCase`` instance has access to an
    
  1052. instance of a Django test client. This client can be accessed as
    
  1053. ``self.client``. This client is recreated for each test, so you don't have to
    
  1054. worry about state (such as cookies) carrying over from one test to another.
    
  1055. 
    
  1056. This means, instead of instantiating a ``Client`` in each test::
    
  1057. 
    
  1058.     import unittest
    
  1059.     from django.test import Client
    
  1060. 
    
  1061.     class SimpleTest(unittest.TestCase):
    
  1062.         def test_details(self):
    
  1063.             client = Client()
    
  1064.             response = client.get('/customer/details/')
    
  1065.             self.assertEqual(response.status_code, 200)
    
  1066. 
    
  1067.         def test_index(self):
    
  1068.             client = Client()
    
  1069.             response = client.get('/customer/index/')
    
  1070.             self.assertEqual(response.status_code, 200)
    
  1071. 
    
  1072. ...you can refer to ``self.client``, like so::
    
  1073. 
    
  1074.     from django.test import TestCase
    
  1075. 
    
  1076.     class SimpleTest(TestCase):
    
  1077.         def test_details(self):
    
  1078.             response = self.client.get('/customer/details/')
    
  1079.             self.assertEqual(response.status_code, 200)
    
  1080. 
    
  1081.         def test_index(self):
    
  1082.             response = self.client.get('/customer/index/')
    
  1083.             self.assertEqual(response.status_code, 200)
    
  1084. 
    
  1085. Customizing the test client
    
  1086. ---------------------------
    
  1087. 
    
  1088. .. attribute:: SimpleTestCase.client_class
    
  1089. 
    
  1090. If you want to use a different ``Client`` class (for example, a subclass
    
  1091. with customized behavior), use the :attr:`~SimpleTestCase.client_class` class
    
  1092. attribute::
    
  1093. 
    
  1094.     from django.test import Client, TestCase
    
  1095. 
    
  1096.     class MyTestClient(Client):
    
  1097.         # Specialized methods for your environment
    
  1098.         ...
    
  1099. 
    
  1100.     class MyTest(TestCase):
    
  1101.         client_class = MyTestClient
    
  1102. 
    
  1103.         def test_my_stuff(self):
    
  1104.             # Here self.client is an instance of MyTestClient...
    
  1105.             call_some_test_code()
    
  1106. 
    
  1107. .. _topics-testing-fixtures:
    
  1108. 
    
  1109. Fixture loading
    
  1110. ---------------
    
  1111. 
    
  1112. .. attribute:: TransactionTestCase.fixtures
    
  1113. 
    
  1114. A test case for a database-backed website isn't much use if there isn't any
    
  1115. data in the database. Tests are more readable and it's more maintainable to
    
  1116. create objects using the ORM, for example in :meth:`TestCase.setUpTestData`,
    
  1117. however, you can also use fixtures.
    
  1118. 
    
  1119. A fixture is a collection of data that Django knows how to import into a
    
  1120. database. For example, if your site has user accounts, you might set up a
    
  1121. fixture of fake user accounts in order to populate your database during tests.
    
  1122. 
    
  1123. The most straightforward way of creating a fixture is to use the
    
  1124. :djadmin:`manage.py dumpdata <dumpdata>` command. This assumes you
    
  1125. already have some data in your database. See the :djadmin:`dumpdata
    
  1126. documentation<dumpdata>` for more details.
    
  1127. 
    
  1128. Once you've created a fixture and placed it in a ``fixtures`` directory in one
    
  1129. of your :setting:`INSTALLED_APPS`, you can use it in your unit tests by
    
  1130. specifying a ``fixtures`` class attribute on your :class:`django.test.TestCase`
    
  1131. subclass::
    
  1132. 
    
  1133.     from django.test import TestCase
    
  1134.     from myapp.models import Animal
    
  1135. 
    
  1136.     class AnimalTestCase(TestCase):
    
  1137.         fixtures = ['mammals.json', 'birds']
    
  1138. 
    
  1139.         def setUp(self):
    
  1140.             # Test definitions as before.
    
  1141.             call_setup_methods()
    
  1142. 
    
  1143.         def test_fluffy_animals(self):
    
  1144.             # A test that uses the fixtures.
    
  1145.             call_some_test_code()
    
  1146. 
    
  1147. Here's specifically what will happen:
    
  1148. 
    
  1149. * At the start of each test, before ``setUp()`` is run, Django will flush the
    
  1150.   database, returning the database to the state it was in directly after
    
  1151.   :djadmin:`migrate` was called.
    
  1152. 
    
  1153. * Then, all the named fixtures are installed. In this example, Django will
    
  1154.   install any JSON fixture named ``mammals``, followed by any fixture named
    
  1155.   ``birds``. See the :djadmin:`loaddata` documentation for more
    
  1156.   details on defining and installing fixtures.
    
  1157. 
    
  1158. For performance reasons, :class:`TestCase` loads fixtures once for the entire
    
  1159. test class, before :meth:`~TestCase.setUpTestData`, instead of before each
    
  1160. test, and it uses transactions to clean the database before each test. In any case,
    
  1161. you can be certain that the outcome of a test will not be affected by another
    
  1162. test or by the order of test execution.
    
  1163. 
    
  1164. By default, fixtures are only loaded into the ``default`` database. If you are
    
  1165. using multiple databases and set :attr:`TransactionTestCase.databases`,
    
  1166. fixtures will be loaded into all specified databases.
    
  1167. 
    
  1168. URLconf configuration
    
  1169. ---------------------
    
  1170. 
    
  1171. If your application provides views, you may want to include tests that use the
    
  1172. test client to exercise those views. However, an end user is free to deploy the
    
  1173. views in your application at any URL of their choosing. This means that your
    
  1174. tests can't rely upon the fact that your views will be available at a
    
  1175. particular URL. Decorate your test class or test method with
    
  1176. ``@override_settings(ROOT_URLCONF=...)`` for URLconf configuration.
    
  1177. 
    
  1178. .. _testing-multi-db:
    
  1179. 
    
  1180. Multi-database support
    
  1181. ----------------------
    
  1182. 
    
  1183. .. attribute:: TransactionTestCase.databases
    
  1184. 
    
  1185. Django sets up a test database corresponding to every database that is
    
  1186. defined in the :setting:`DATABASES` definition in your settings and referred to
    
  1187. by at least one test through ``databases``.
    
  1188. 
    
  1189. However, a big part of the time taken to run a Django ``TestCase`` is consumed
    
  1190. by the call to ``flush`` that ensures that you have a clean database at the
    
  1191. start of each test run. If you have multiple databases, multiple flushes are
    
  1192. required (one for each database), which can be a time consuming activity --
    
  1193. especially if your tests don't need to test multi-database activity.
    
  1194. 
    
  1195. As an optimization, Django only flushes the ``default`` database at
    
  1196. the start of each test run. If your setup contains multiple databases,
    
  1197. and you have a test that requires every database to be clean, you can
    
  1198. use the ``databases`` attribute on the test suite to request extra databases
    
  1199. to be flushed.
    
  1200. 
    
  1201. For example::
    
  1202. 
    
  1203.     class TestMyViews(TransactionTestCase):
    
  1204.         databases = {'default', 'other'}
    
  1205. 
    
  1206.         def test_index_page_view(self):
    
  1207.             call_some_test_code()
    
  1208. 
    
  1209. This test case will flush the ``default`` and ``other`` test databases before
    
  1210. running ``test_index_page_view``. You can also use ``'__all__'`` to specify
    
  1211. that all of the test databases must be flushed.
    
  1212. 
    
  1213. The ``databases`` flag also controls which databases the
    
  1214. :attr:`TransactionTestCase.fixtures` are loaded into. By default, fixtures are
    
  1215. only loaded into the ``default`` database.
    
  1216. 
    
  1217. Queries against databases not in ``databases`` will give assertion errors to
    
  1218. prevent state leaking between tests.
    
  1219. 
    
  1220. .. attribute:: TestCase.databases
    
  1221. 
    
  1222. By default, only the ``default`` database will be wrapped in a transaction
    
  1223. during a ``TestCase``'s execution and attempts to query other databases will
    
  1224. result in assertion errors to prevent state leaking between tests.
    
  1225. 
    
  1226. Use the ``databases`` class attribute on the test class to request transaction
    
  1227. wrapping against non-``default`` databases.
    
  1228. 
    
  1229. For example::
    
  1230. 
    
  1231.     class OtherDBTests(TestCase):
    
  1232.         databases = {'other'}
    
  1233. 
    
  1234.         def test_other_db_query(self):
    
  1235.             ...
    
  1236. 
    
  1237. This test will only allow queries against the ``other`` database. Just like for
    
  1238. :attr:`SimpleTestCase.databases` and :attr:`TransactionTestCase.databases`, the
    
  1239. ``'__all__'`` constant can be used to specify that the test should allow
    
  1240. queries to all databases.
    
  1241. 
    
  1242. .. _overriding-settings:
    
  1243. 
    
  1244. Overriding settings
    
  1245. -------------------
    
  1246. 
    
  1247. .. warning::
    
  1248. 
    
  1249.     Use the functions below to temporarily alter the value of settings in tests.
    
  1250.     Don't manipulate ``django.conf.settings`` directly as Django won't restore
    
  1251.     the original values after such manipulations.
    
  1252. 
    
  1253. .. method:: SimpleTestCase.settings()
    
  1254. 
    
  1255. For testing purposes it's often useful to change a setting temporarily and
    
  1256. revert to the original value after running the testing code. For this use case
    
  1257. Django provides a standard Python context manager (see :pep:`343`) called
    
  1258. :meth:`~django.test.SimpleTestCase.settings`, which can be used like this::
    
  1259. 
    
  1260.     from django.test import TestCase
    
  1261. 
    
  1262.     class LoginTestCase(TestCase):
    
  1263. 
    
  1264.         def test_login(self):
    
  1265. 
    
  1266.             # First check for the default behavior
    
  1267.             response = self.client.get('/sekrit/')
    
  1268.             self.assertRedirects(response, '/accounts/login/?next=/sekrit/')
    
  1269. 
    
  1270.             # Then override the LOGIN_URL setting
    
  1271.             with self.settings(LOGIN_URL='/other/login/'):
    
  1272.                 response = self.client.get('/sekrit/')
    
  1273.                 self.assertRedirects(response, '/other/login/?next=/sekrit/')
    
  1274. 
    
  1275. This example will override the :setting:`LOGIN_URL` setting for the code
    
  1276. in the ``with`` block and reset its value to the previous state afterward.
    
  1277. 
    
  1278. .. method:: SimpleTestCase.modify_settings()
    
  1279. 
    
  1280. It can prove unwieldy to redefine settings that contain a list of values. In
    
  1281. practice, adding or removing values is often sufficient. Django provides the
    
  1282. :meth:`~django.test.SimpleTestCase.modify_settings` context manager for easier
    
  1283. settings changes::
    
  1284. 
    
  1285.     from django.test import TestCase
    
  1286. 
    
  1287.     class MiddlewareTestCase(TestCase):
    
  1288. 
    
  1289.         def test_cache_middleware(self):
    
  1290.             with self.modify_settings(MIDDLEWARE={
    
  1291.                 'append': 'django.middleware.cache.FetchFromCacheMiddleware',
    
  1292.                 'prepend': 'django.middleware.cache.UpdateCacheMiddleware',
    
  1293.                 'remove': [
    
  1294.                     'django.contrib.sessions.middleware.SessionMiddleware',
    
  1295.                     'django.contrib.auth.middleware.AuthenticationMiddleware',
    
  1296.                     'django.contrib.messages.middleware.MessageMiddleware',
    
  1297.                 ],
    
  1298.             }):
    
  1299.                 response = self.client.get('/')
    
  1300.                 # ...
    
  1301. 
    
  1302. For each action, you can supply either a list of values or a string. When the
    
  1303. value already exists in the list, ``append`` and ``prepend`` have no effect;
    
  1304. neither does ``remove`` when the value doesn't exist.
    
  1305. 
    
  1306. .. function:: override_settings(**kwargs)
    
  1307. 
    
  1308. In case you want to override a setting for a test method, Django provides the
    
  1309. :func:`~django.test.override_settings` decorator (see :pep:`318`). It's used
    
  1310. like this::
    
  1311. 
    
  1312.     from django.test import TestCase, override_settings
    
  1313. 
    
  1314.     class LoginTestCase(TestCase):
    
  1315. 
    
  1316.         @override_settings(LOGIN_URL='/other/login/')
    
  1317.         def test_login(self):
    
  1318.             response = self.client.get('/sekrit/')
    
  1319.             self.assertRedirects(response, '/other/login/?next=/sekrit/')
    
  1320. 
    
  1321. The decorator can also be applied to :class:`~django.test.TestCase` classes::
    
  1322. 
    
  1323.     from django.test import TestCase, override_settings
    
  1324. 
    
  1325.     @override_settings(LOGIN_URL='/other/login/')
    
  1326.     class LoginTestCase(TestCase):
    
  1327. 
    
  1328.         def test_login(self):
    
  1329.             response = self.client.get('/sekrit/')
    
  1330.             self.assertRedirects(response, '/other/login/?next=/sekrit/')
    
  1331. 
    
  1332. .. function:: modify_settings(*args, **kwargs)
    
  1333. 
    
  1334. Likewise, Django provides the :func:`~django.test.modify_settings`
    
  1335. decorator::
    
  1336. 
    
  1337.     from django.test import TestCase, modify_settings
    
  1338. 
    
  1339.     class MiddlewareTestCase(TestCase):
    
  1340. 
    
  1341.         @modify_settings(MIDDLEWARE={
    
  1342.             'append': 'django.middleware.cache.FetchFromCacheMiddleware',
    
  1343.             'prepend': 'django.middleware.cache.UpdateCacheMiddleware',
    
  1344.         })
    
  1345.         def test_cache_middleware(self):
    
  1346.             response = self.client.get('/')
    
  1347.             # ...
    
  1348. 
    
  1349. The decorator can also be applied to test case classes::
    
  1350. 
    
  1351.     from django.test import TestCase, modify_settings
    
  1352. 
    
  1353.     @modify_settings(MIDDLEWARE={
    
  1354.         'append': 'django.middleware.cache.FetchFromCacheMiddleware',
    
  1355.         'prepend': 'django.middleware.cache.UpdateCacheMiddleware',
    
  1356.     })
    
  1357.     class MiddlewareTestCase(TestCase):
    
  1358. 
    
  1359.         def test_cache_middleware(self):
    
  1360.             response = self.client.get('/')
    
  1361.             # ...
    
  1362. 
    
  1363. .. note::
    
  1364. 
    
  1365.     When given a class, these decorators modify the class directly and return
    
  1366.     it; they don't create and return a modified copy of it. So if you try to
    
  1367.     tweak the above examples to assign the return value to a different name
    
  1368.     than ``LoginTestCase`` or ``MiddlewareTestCase``, you may be surprised to
    
  1369.     find that the original test case classes are still equally affected by the
    
  1370.     decorator. For a given class, :func:`~django.test.modify_settings` is
    
  1371.     always applied after :func:`~django.test.override_settings`.
    
  1372. 
    
  1373. .. warning::
    
  1374. 
    
  1375.     The settings file contains some settings that are only consulted during
    
  1376.     initialization of Django internals. If you change them with
    
  1377.     ``override_settings``, the setting is changed if you access it via the
    
  1378.     ``django.conf.settings`` module, however, Django's internals access it
    
  1379.     differently. Effectively, using :func:`~django.test.override_settings` or
    
  1380.     :func:`~django.test.modify_settings` with these settings is probably not
    
  1381.     going to do what you expect it to do.
    
  1382. 
    
  1383.     We do not recommend altering the :setting:`DATABASES` setting. Altering
    
  1384.     the :setting:`CACHES` setting is possible, but a bit tricky if you are
    
  1385.     using internals that make using of caching, like
    
  1386.     :mod:`django.contrib.sessions`. For example, you will have to reinitialize
    
  1387.     the session backend in a test that uses cached sessions and overrides
    
  1388.     :setting:`CACHES`.
    
  1389. 
    
  1390.     Finally, avoid aliasing your settings as module-level constants as
    
  1391.     ``override_settings()`` won't work on such values since they are
    
  1392.     only evaluated the first time the module is imported.
    
  1393. 
    
  1394. You can also simulate the absence of a setting by deleting it after settings
    
  1395. have been overridden, like this::
    
  1396. 
    
  1397.     @override_settings()
    
  1398.     def test_something(self):
    
  1399.         del settings.LOGIN_URL
    
  1400.         ...
    
  1401. 
    
  1402. When overriding settings, make sure to handle the cases in which your app's
    
  1403. code uses a cache or similar feature that retains state even if the setting is
    
  1404. changed. Django provides the :data:`django.test.signals.setting_changed`
    
  1405. signal that lets you register callbacks to clean up and otherwise reset state
    
  1406. when settings are changed.
    
  1407. 
    
  1408. Django itself uses this signal to reset various data:
    
  1409. 
    
  1410. ================================ ========================
    
  1411. Overridden settings              Data reset
    
  1412. ================================ ========================
    
  1413. USE_TZ, TIME_ZONE                Databases timezone
    
  1414. TEMPLATES                        Template engines
    
  1415. SERIALIZATION_MODULES            Serializers cache
    
  1416. LOCALE_PATHS, LANGUAGE_CODE      Default translation and loaded translations
    
  1417. MEDIA_ROOT, DEFAULT_FILE_STORAGE Default file storage
    
  1418. ================================ ========================
    
  1419. 
    
  1420. Isolating apps
    
  1421. --------------
    
  1422. 
    
  1423. .. function:: utils.isolate_apps(*app_labels, attr_name=None, kwarg_name=None)
    
  1424. 
    
  1425.     Registers the models defined within a wrapped context into their own
    
  1426.     isolated :attr:`~django.apps.apps` registry. This functionality is useful
    
  1427.     when creating model classes for tests, as the classes will be cleanly
    
  1428.     deleted afterward, and there is no risk of name collisions.
    
  1429. 
    
  1430.     The app labels which the isolated registry should contain must be passed as
    
  1431.     individual arguments. You can use ``isolate_apps()`` as a decorator or a
    
  1432.     context manager. For example::
    
  1433. 
    
  1434.         from django.db import models
    
  1435.         from django.test import SimpleTestCase
    
  1436.         from django.test.utils import isolate_apps
    
  1437. 
    
  1438.         class MyModelTests(SimpleTestCase):
    
  1439. 
    
  1440.             @isolate_apps("app_label")
    
  1441.             def test_model_definition(self):
    
  1442.                 class TestModel(models.Model):
    
  1443.                     pass
    
  1444.                 ...
    
  1445. 
    
  1446.     … or::
    
  1447. 
    
  1448.         with isolate_apps("app_label"):
    
  1449.             class TestModel(models.Model):
    
  1450.                 pass
    
  1451.             ...
    
  1452. 
    
  1453.     The decorator form can also be applied to classes.
    
  1454. 
    
  1455.     Two optional keyword arguments can be specified:
    
  1456. 
    
  1457.     * ``attr_name``: attribute assigned the isolated registry if used as a
    
  1458.       class decorator.
    
  1459.     * ``kwarg_name``: keyword argument passing the isolated registry if used as
    
  1460.       a function decorator.
    
  1461. 
    
  1462.     The temporary ``Apps`` instance used to isolate model registration can be
    
  1463.     retrieved as an attribute when used as a class decorator by using the
    
  1464.     ``attr_name`` parameter::
    
  1465. 
    
  1466.         @isolate_apps("app_label", attr_name="apps")
    
  1467.         class TestModelDefinition(SimpleTestCase):
    
  1468.             def test_model_definition(self):
    
  1469.                 class TestModel(models.Model):
    
  1470.                     pass
    
  1471.                 self.assertIs(self.apps.get_model("app_label", "TestModel"), TestModel)
    
  1472. 
    
  1473.     … or alternatively as an argument on the test method when used as a method
    
  1474.     decorator by using the ``kwarg_name`` parameter::
    
  1475. 
    
  1476.         class TestModelDefinition(SimpleTestCase):
    
  1477.             @isolate_apps("app_label", kwarg_name="apps")
    
  1478.             def test_model_definition(self, apps):
    
  1479.                 class TestModel(models.Model):
    
  1480.                     pass
    
  1481.                 self.assertIs(apps.get_model("app_label", "TestModel"), TestModel)
    
  1482. 
    
  1483. .. _emptying-test-outbox:
    
  1484. 
    
  1485. Emptying the test outbox
    
  1486. ------------------------
    
  1487. 
    
  1488. If you use any of Django's custom ``TestCase`` classes, the test runner will
    
  1489. clear the contents of the test email outbox at the start of each test case.
    
  1490. 
    
  1491. For more detail on email services during tests, see `Email services`_ below.
    
  1492. 
    
  1493. .. _assertions:
    
  1494. 
    
  1495. Assertions
    
  1496. ----------
    
  1497. 
    
  1498. As Python's normal :class:`unittest.TestCase` class implements assertion methods
    
  1499. such as :meth:`~unittest.TestCase.assertTrue` and
    
  1500. :meth:`~unittest.TestCase.assertEqual`, Django's custom :class:`TestCase` class
    
  1501. provides a number of custom assertion methods that are useful for testing web
    
  1502. applications:
    
  1503. 
    
  1504. The failure messages given by most of these assertion methods can be customized
    
  1505. with the ``msg_prefix`` argument. This string will be prefixed to any failure
    
  1506. message generated by the assertion. This allows you to provide additional
    
  1507. details that may help you to identify the location and cause of a failure in
    
  1508. your test suite.
    
  1509. 
    
  1510. .. method:: SimpleTestCase.assertRaisesMessage(expected_exception, expected_message, callable, *args, **kwargs)
    
  1511.             SimpleTestCase.assertRaisesMessage(expected_exception, expected_message)
    
  1512. 
    
  1513.     Asserts that execution of ``callable`` raises ``expected_exception`` and
    
  1514.     that ``expected_message`` is found in the exception's message. Any other
    
  1515.     outcome is reported as a failure. It's a simpler version of
    
  1516.     :meth:`unittest.TestCase.assertRaisesRegex` with the difference that
    
  1517.     ``expected_message`` isn't treated as a regular expression.
    
  1518. 
    
  1519.     If only the ``expected_exception`` and ``expected_message`` parameters are
    
  1520.     given, returns a context manager so that the code being tested can be
    
  1521.     written inline rather than as a function::
    
  1522. 
    
  1523.         with self.assertRaisesMessage(ValueError, 'invalid literal for int()'):
    
  1524.             int('a')
    
  1525. 
    
  1526. .. method:: SimpleTestCase.assertWarnsMessage(expected_warning, expected_message, callable, *args, **kwargs)
    
  1527.             SimpleTestCase.assertWarnsMessage(expected_warning, expected_message)
    
  1528. 
    
  1529.     Analogous to :meth:`SimpleTestCase.assertRaisesMessage` but for
    
  1530.     :meth:`~unittest.TestCase.assertWarnsRegex` instead of
    
  1531.     :meth:`~unittest.TestCase.assertRaisesRegex`.
    
  1532. 
    
  1533. .. method:: SimpleTestCase.assertFieldOutput(fieldclass, valid, invalid, field_args=None, field_kwargs=None, empty_value='')
    
  1534. 
    
  1535.     Asserts that a form field behaves correctly with various inputs.
    
  1536. 
    
  1537.     :param fieldclass: the class of the field to be tested.
    
  1538.     :param valid: a dictionary mapping valid inputs to their expected cleaned
    
  1539.         values.
    
  1540.     :param invalid: a dictionary mapping invalid inputs to one or more raised
    
  1541.         error messages.
    
  1542.     :param field_args: the args passed to instantiate the field.
    
  1543.     :param field_kwargs: the kwargs passed to instantiate the field.
    
  1544.     :param empty_value: the expected clean output for inputs in ``empty_values``.
    
  1545. 
    
  1546.     For example, the following code tests that an ``EmailField`` accepts
    
  1547.     ``[email protected]`` as a valid email address, but rejects ``aaa`` with a reasonable
    
  1548.     error message::
    
  1549. 
    
  1550.         self.assertFieldOutput(EmailField, {'[email protected]': '[email protected]'}, {'aaa': ['Enter a valid email address.']})
    
  1551. 
    
  1552. .. method:: SimpleTestCase.assertFormError(form, field, errors, msg_prefix='')
    
  1553. 
    
  1554.     Asserts that a field on a form raises the provided list of errors.
    
  1555. 
    
  1556.     ``form`` is a ``Form`` instance. The form must be
    
  1557.     :ref:`bound <ref-forms-api-bound-unbound>` but not necessarily
    
  1558.     validated (``assertFormError()`` will automatically call ``full_clean()``
    
  1559.     on the form).
    
  1560. 
    
  1561.     ``field`` is the name of the field on the form to check. To check the form's
    
  1562.     :meth:`non-field errors <django.forms.Form.non_field_errors>`, use
    
  1563.     ``field=None``.
    
  1564. 
    
  1565.     ``errors`` is a list of all the error strings that the field is expected to
    
  1566.     have. You can also pass a single error string if you only expect one error
    
  1567.     which means that ``errors='error message'`` is the same as
    
  1568.     ``errors=['error message']``.
    
  1569. 
    
  1570.     .. versionchanged:: 4.1
    
  1571. 
    
  1572.         In older versions, using an empty error list with ``assertFormError()``
    
  1573.         would always pass, regardless of whether the field had any errors or
    
  1574.         not. Starting from Django 4.1, using ``errors=[]`` will only pass if
    
  1575.         the field actually has no errors.
    
  1576. 
    
  1577.         Django 4.1 also changed the behavior of ``assertFormError()`` when a
    
  1578.         field has multiple errors. In older versions, if a field had multiple
    
  1579.         errors and you checked for only some of them, the test would pass.
    
  1580.         Starting from Django 4.1, the error list must be an exact match to the
    
  1581.         field's actual errors.
    
  1582. 
    
  1583.     .. deprecated:: 4.1
    
  1584. 
    
  1585.         Support for passing a response object and a form name to
    
  1586.         ``assertFormError()`` is deprecated and will be removed in Django 5.0.
    
  1587.         Use the form instance directly instead.
    
  1588. 
    
  1589. .. method:: SimpleTestCase.assertFormsetError(formset, form_index, field, errors, msg_prefix='')
    
  1590. 
    
  1591.     Asserts that the ``formset`` raises the provided list of errors when
    
  1592.     rendered.
    
  1593. 
    
  1594.     ``formset`` is a ``Formset`` instance. The formset must be bound but not
    
  1595.     necessarily validated (``assertFormsetError()`` will automatically call the
    
  1596.     ``full_clean()`` on the formset).
    
  1597. 
    
  1598.     ``form_index`` is the number of the form within the ``Formset`` (starting
    
  1599.     from 0). Use ``form_index=None`` to check the formset's non-form errors,
    
  1600.     i.e. the errors you get when calling ``formset.non_form_errors()``. In that
    
  1601.     case you must also use ``field=None``.
    
  1602. 
    
  1603.     ``field`` and ``errors`` have the same meaning as the parameters to
    
  1604.     ``assertFormError()``.
    
  1605. 
    
  1606.     .. deprecated:: 4.1
    
  1607. 
    
  1608.         Support for passing a response object and a formset name to
    
  1609.         ``assertFormsetError()`` is deprecated and will be removed in Django
    
  1610.         5.0. Use the formset instance directly instead.
    
  1611. 
    
  1612. .. method:: SimpleTestCase.assertContains(response, text, count=None, status_code=200, msg_prefix='', html=False)
    
  1613. 
    
  1614.     Asserts that a :class:`response <django.http.HttpResponse>` produced the
    
  1615.     given :attr:`~django.http.HttpResponse.status_code` and that ``text``
    
  1616.     appears in its :attr:`~django.http.HttpResponse.content`. If ``count``
    
  1617.     is provided, ``text`` must occur exactly ``count`` times in the response.
    
  1618. 
    
  1619.     Set ``html`` to ``True`` to handle ``text`` as HTML. The comparison with
    
  1620.     the response content will be based on HTML semantics instead of
    
  1621.     character-by-character equality. Whitespace is ignored in most cases,
    
  1622.     attribute ordering is not significant. See
    
  1623.     :meth:`~SimpleTestCase.assertHTMLEqual` for more details.
    
  1624. 
    
  1625. .. method:: SimpleTestCase.assertNotContains(response, text, status_code=200, msg_prefix='', html=False)
    
  1626. 
    
  1627.     Asserts that a :class:`response <django.http.HttpResponse>` produced the
    
  1628.     given :attr:`~django.http.HttpResponse.status_code` and that ``text`` does
    
  1629.     *not* appear in its :attr:`~django.http.HttpResponse.content`.
    
  1630. 
    
  1631.     Set ``html`` to ``True`` to handle ``text`` as HTML. The comparison with
    
  1632.     the response content will be based on HTML semantics instead of
    
  1633.     character-by-character equality. Whitespace is ignored in most cases,
    
  1634.     attribute ordering is not significant. See
    
  1635.     :meth:`~SimpleTestCase.assertHTMLEqual` for more details.
    
  1636. 
    
  1637. .. method:: SimpleTestCase.assertTemplateUsed(response, template_name, msg_prefix='', count=None)
    
  1638. 
    
  1639.     Asserts that the template with the given name was used in rendering the
    
  1640.     response.
    
  1641. 
    
  1642.     ``response`` must be a response instance returned by the
    
  1643.     :class:`test client <django.test.Response>`.
    
  1644. 
    
  1645.     ``template_name`` should be a string such as ``'admin/index.html'``.
    
  1646. 
    
  1647.     The ``count`` argument is an integer indicating the number of times the
    
  1648.     template should be rendered. Default is ``None``, meaning that the template
    
  1649.     should be rendered one or more times.
    
  1650. 
    
  1651.     You can use this as a context manager, like this::
    
  1652. 
    
  1653.         with self.assertTemplateUsed('index.html'):
    
  1654.             render_to_string('index.html')
    
  1655.         with self.assertTemplateUsed(template_name='index.html'):
    
  1656.             render_to_string('index.html')
    
  1657. 
    
  1658. .. method:: SimpleTestCase.assertTemplateNotUsed(response, template_name, msg_prefix='')
    
  1659. 
    
  1660.     Asserts that the template with the given name was *not* used in rendering
    
  1661.     the response.
    
  1662. 
    
  1663.     You can use this as a context manager in the same way as
    
  1664.     :meth:`~SimpleTestCase.assertTemplateUsed`.
    
  1665. 
    
  1666. .. method:: SimpleTestCase.assertURLEqual(url1, url2, msg_prefix='')
    
  1667. 
    
  1668.     Asserts that two URLs are the same, ignoring the order of query string
    
  1669.     parameters except for parameters with the same name. For example,
    
  1670.     ``/path/?x=1&y=2`` is equal to ``/path/?y=2&x=1``, but
    
  1671.     ``/path/?a=1&a=2`` isn't equal to ``/path/?a=2&a=1``.
    
  1672. 
    
  1673. .. method:: SimpleTestCase.assertRedirects(response, expected_url, status_code=302, target_status_code=200, msg_prefix='', fetch_redirect_response=True)
    
  1674. 
    
  1675.     Asserts that the :class:`response <django.http.HttpResponse>` returned a
    
  1676.     :attr:`~django.http.HttpResponse.status_code` redirect status, redirected
    
  1677.     to ``expected_url`` (including any ``GET`` data), and that the final page
    
  1678.     was received with ``target_status_code``.
    
  1679. 
    
  1680.     If your request used the ``follow`` argument, the ``expected_url`` and
    
  1681.     ``target_status_code`` will be the url and status code for the final
    
  1682.     point of the redirect chain.
    
  1683. 
    
  1684.     If ``fetch_redirect_response`` is ``False``, the final page won't be
    
  1685.     loaded. Since the test client can't fetch external URLs, this is
    
  1686.     particularly useful if ``expected_url`` isn't part of your Django app.
    
  1687. 
    
  1688.     Scheme is handled correctly when making comparisons between two URLs. If
    
  1689.     there isn't any scheme specified in the location where we are redirected to,
    
  1690.     the original request's scheme is used. If present, the scheme in
    
  1691.     ``expected_url`` is the one used to make the comparisons to.
    
  1692. 
    
  1693. .. method:: SimpleTestCase.assertHTMLEqual(html1, html2, msg=None)
    
  1694. 
    
  1695.     Asserts that the strings ``html1`` and ``html2`` are equal. The comparison
    
  1696.     is based on HTML semantics. The comparison takes following things into
    
  1697.     account:
    
  1698. 
    
  1699.     * Whitespace before and after HTML tags is ignored.
    
  1700.     * All types of whitespace are considered equivalent.
    
  1701.     * All open tags are closed implicitly, e.g. when a surrounding tag is
    
  1702.       closed or the HTML document ends.
    
  1703.     * Empty tags are equivalent to their self-closing version.
    
  1704.     * The ordering of attributes of an HTML element is not significant.
    
  1705.     * Boolean attributes (like ``checked``) without an argument are equal to
    
  1706.       attributes that equal in name and value (see the examples).
    
  1707.     * Text, character references, and entity references that refer to the same
    
  1708.       character are equivalent.
    
  1709. 
    
  1710.     The following examples are valid tests and don't raise any
    
  1711.     ``AssertionError``::
    
  1712. 
    
  1713.         self.assertHTMLEqual(
    
  1714.             '<p>Hello <b>&#x27;world&#x27;!</p>',
    
  1715.             '''<p>
    
  1716.                 Hello   <b>&#39;world&#39;! </b>
    
  1717.             </p>'''
    
  1718.         )
    
  1719.         self.assertHTMLEqual(
    
  1720.             '<input type="checkbox" checked="checked" id="id_accept_terms" />',
    
  1721.             '<input id="id_accept_terms" type="checkbox" checked>'
    
  1722.         )
    
  1723. 
    
  1724.     ``html1`` and ``html2`` must contain HTML. An ``AssertionError`` will be
    
  1725.     raised if one of them cannot be parsed.
    
  1726. 
    
  1727.     Output in case of error can be customized with the ``msg`` argument.
    
  1728. 
    
  1729.     .. versionchanged:: 4.0
    
  1730. 
    
  1731.         In older versions, any attribute (not only boolean attributes) without
    
  1732.         a value was considered equal to an attribute with the same name and
    
  1733.         value.
    
  1734. 
    
  1735. .. method:: SimpleTestCase.assertHTMLNotEqual(html1, html2, msg=None)
    
  1736. 
    
  1737.     Asserts that the strings ``html1`` and ``html2`` are *not* equal. The
    
  1738.     comparison is based on HTML semantics. See
    
  1739.     :meth:`~SimpleTestCase.assertHTMLEqual` for details.
    
  1740. 
    
  1741.     ``html1`` and ``html2`` must contain HTML. An ``AssertionError`` will be
    
  1742.     raised if one of them cannot be parsed.
    
  1743. 
    
  1744.     Output in case of error can be customized with the ``msg`` argument.
    
  1745. 
    
  1746. .. method:: SimpleTestCase.assertXMLEqual(xml1, xml2, msg=None)
    
  1747. 
    
  1748.     Asserts that the strings ``xml1`` and ``xml2`` are equal. The
    
  1749.     comparison is based on XML semantics. Similarly to
    
  1750.     :meth:`~SimpleTestCase.assertHTMLEqual`, the comparison is
    
  1751.     made on parsed content, hence only semantic differences are considered, not
    
  1752.     syntax differences. When invalid XML is passed in any parameter, an
    
  1753.     ``AssertionError`` is always raised, even if both strings are identical.
    
  1754. 
    
  1755.     XML declaration, document type, processing instructions, and comments are
    
  1756.     ignored. Only the root element and its children are compared.
    
  1757. 
    
  1758.     Output in case of error can be customized with the ``msg`` argument.
    
  1759. 
    
  1760. .. method:: SimpleTestCase.assertXMLNotEqual(xml1, xml2, msg=None)
    
  1761. 
    
  1762.     Asserts that the strings ``xml1`` and ``xml2`` are *not* equal. The
    
  1763.     comparison is based on XML semantics. See
    
  1764.     :meth:`~SimpleTestCase.assertXMLEqual` for details.
    
  1765. 
    
  1766.     Output in case of error can be customized with the ``msg`` argument.
    
  1767. 
    
  1768. .. method:: SimpleTestCase.assertInHTML(needle, haystack, count=None, msg_prefix='')
    
  1769. 
    
  1770.     Asserts that the HTML fragment ``needle`` is contained in the ``haystack``
    
  1771.     once.
    
  1772. 
    
  1773.     If the ``count`` integer argument is specified, then additionally the number
    
  1774.     of ``needle`` occurrences will be strictly verified.
    
  1775. 
    
  1776.     Whitespace in most cases is ignored, and attribute ordering is not
    
  1777.     significant. See :meth:`~SimpleTestCase.assertHTMLEqual` for more details.
    
  1778. 
    
  1779. .. method:: SimpleTestCase.assertJSONEqual(raw, expected_data, msg=None)
    
  1780. 
    
  1781.     Asserts that the JSON fragments ``raw`` and ``expected_data`` are equal.
    
  1782.     Usual JSON non-significant whitespace rules apply as the heavyweight is
    
  1783.     delegated to the :mod:`json` library.
    
  1784. 
    
  1785.     Output in case of error can be customized with the ``msg`` argument.
    
  1786. 
    
  1787. .. method:: SimpleTestCase.assertJSONNotEqual(raw, expected_data, msg=None)
    
  1788. 
    
  1789.     Asserts that the JSON fragments ``raw`` and ``expected_data`` are *not* equal.
    
  1790.     See :meth:`~SimpleTestCase.assertJSONEqual` for further details.
    
  1791. 
    
  1792.     Output in case of error can be customized with the ``msg`` argument.
    
  1793. 
    
  1794. .. method:: TransactionTestCase.assertQuerysetEqual(qs, values, transform=None, ordered=True, msg=None)
    
  1795. 
    
  1796.     Asserts that a queryset ``qs`` matches a particular iterable of values
    
  1797.     ``values``.
    
  1798. 
    
  1799.     If ``transform`` is provided, ``values`` is compared to a list produced by
    
  1800.     applying ``transform`` to each member of ``qs``.
    
  1801. 
    
  1802.     By default, the comparison is also ordering dependent. If ``qs`` doesn't
    
  1803.     provide an implicit ordering, you can set the ``ordered`` parameter to
    
  1804.     ``False``, which turns the comparison into a ``collections.Counter`` comparison.
    
  1805.     If the order is undefined (if the given ``qs`` isn't ordered and the
    
  1806.     comparison is against more than one ordered value), a ``ValueError`` is
    
  1807.     raised.
    
  1808. 
    
  1809.     Output in case of error can be customized with the ``msg`` argument.
    
  1810. 
    
  1811. .. method:: TransactionTestCase.assertNumQueries(num, func, *args, **kwargs)
    
  1812. 
    
  1813.     Asserts that when ``func`` is called with ``*args`` and ``**kwargs`` that
    
  1814.     ``num`` database queries are executed.
    
  1815. 
    
  1816.     If a ``"using"`` key is present in ``kwargs`` it is used as the database
    
  1817.     alias for which to check the number of queries::
    
  1818. 
    
  1819.         self.assertNumQueries(7, using='non_default_db')
    
  1820. 
    
  1821.     If you wish to call a function with a ``using`` parameter you can do it by
    
  1822.     wrapping the call with a ``lambda`` to add an extra parameter::
    
  1823. 
    
  1824.         self.assertNumQueries(7, lambda: my_function(using=7))
    
  1825. 
    
  1826.     You can also use this as a context manager::
    
  1827. 
    
  1828.         with self.assertNumQueries(2):
    
  1829.             Person.objects.create(name="Aaron")
    
  1830.             Person.objects.create(name="Daniel")
    
  1831. 
    
  1832. .. _topics-tagging-tests:
    
  1833. 
    
  1834. Tagging tests
    
  1835. -------------
    
  1836. 
    
  1837. You can tag your tests so you can easily run a particular subset. For example,
    
  1838. you might label fast or slow tests::
    
  1839. 
    
  1840.     from django.test import tag
    
  1841. 
    
  1842.     class SampleTestCase(TestCase):
    
  1843. 
    
  1844.         @tag('fast')
    
  1845.         def test_fast(self):
    
  1846.             ...
    
  1847. 
    
  1848.         @tag('slow')
    
  1849.         def test_slow(self):
    
  1850.             ...
    
  1851. 
    
  1852.         @tag('slow', 'core')
    
  1853.         def test_slow_but_core(self):
    
  1854.             ...
    
  1855. 
    
  1856. You can also tag a test case::
    
  1857. 
    
  1858.     @tag('slow', 'core')
    
  1859.     class SampleTestCase(TestCase):
    
  1860.         ...
    
  1861. 
    
  1862. Subclasses inherit tags from superclasses, and methods inherit tags from their
    
  1863. class. Given::
    
  1864. 
    
  1865.     @tag('foo')
    
  1866.     class SampleTestCaseChild(SampleTestCase):
    
  1867. 
    
  1868.         @tag('bar')
    
  1869.         def test(self):
    
  1870.             ...
    
  1871. 
    
  1872. ``SampleTestCaseChild.test`` will be labeled with ``'slow'``, ``'core'``,
    
  1873. ``'bar'``, and ``'foo'``.
    
  1874. 
    
  1875. Then you can choose which tests to run. For example, to run only fast tests:
    
  1876. 
    
  1877. .. console::
    
  1878. 
    
  1879.     $ ./manage.py test --tag=fast
    
  1880. 
    
  1881. Or to run fast tests and the core one (even though it's slow):
    
  1882. 
    
  1883. .. console::
    
  1884. 
    
  1885.     $ ./manage.py test --tag=fast --tag=core
    
  1886. 
    
  1887. You can also exclude tests by tag. To run core tests if they are not slow:
    
  1888. 
    
  1889. .. console::
    
  1890. 
    
  1891.     $ ./manage.py test --tag=core --exclude-tag=slow
    
  1892. 
    
  1893. :option:`test --exclude-tag` has precedence over :option:`test --tag`, so if a
    
  1894. test has two tags and you select one of them and exclude the other, the test
    
  1895. won't be run.
    
  1896. 
    
  1897. .. _async-tests:
    
  1898. 
    
  1899. Testing asynchronous code
    
  1900. =========================
    
  1901. 
    
  1902. If you merely want to test the output of your asynchronous views, the standard
    
  1903. test client will run them inside their own asynchronous loop without any extra
    
  1904. work needed on your part.
    
  1905. 
    
  1906. However, if you want to write fully-asynchronous tests for a Django project,
    
  1907. you will need to take several things into account.
    
  1908. 
    
  1909. Firstly, your tests must be ``async def`` methods on the test class (in order
    
  1910. to give them an asynchronous context). Django will automatically detect
    
  1911. any ``async def`` tests and wrap them so they run in their own event loop.
    
  1912. 
    
  1913. If you are testing from an asynchronous function, you must also use the
    
  1914. asynchronous test client. This is available as ``django.test.AsyncClient``,
    
  1915. or as ``self.async_client`` on any test.
    
  1916. 
    
  1917. .. class:: AsyncClient(enforce_csrf_checks=False, raise_request_exception=True, **defaults)
    
  1918. 
    
  1919. ``AsyncClient`` has the same methods and signatures as the synchronous (normal)
    
  1920. test client, with two exceptions:
    
  1921. 
    
  1922. * In the initialization, arbitrary keyword arguments in ``defaults`` are added
    
  1923.   directly into the ASGI scope.
    
  1924. * The ``follow`` parameter is not supported.
    
  1925. * Headers passed as ``extra`` keyword arguments should not have the ``HTTP_``
    
  1926.   prefix required by the synchronous client (see :meth:`Client.get`). For
    
  1927.   example, here is how to set an HTTP ``Accept`` header::
    
  1928. 
    
  1929.     >>> c = AsyncClient()
    
  1930.     >>> c.get(
    
  1931.     ...     '/customers/details/',
    
  1932.     ...     {'name': 'fred', 'age': 7},
    
  1933.     ...     ACCEPT='application/json'
    
  1934.     ... )
    
  1935. 
    
  1936. Using ``AsyncClient`` any method that makes a request must be awaited::
    
  1937. 
    
  1938.     async def test_my_thing(self):
    
  1939.         response = await self.async_client.get('/some-url/')
    
  1940.         self.assertEqual(response.status_code, 200)
    
  1941. 
    
  1942. The asynchronous client can also call synchronous views; it runs through
    
  1943. Django's :doc:`asynchronous request path </topics/async>`, which supports both.
    
  1944. Any view called through the ``AsyncClient`` will get an ``ASGIRequest`` object
    
  1945. for its ``request`` rather than the ``WSGIRequest`` that the normal client
    
  1946. creates.
    
  1947. 
    
  1948. .. warning::
    
  1949. 
    
  1950.     If you are using test decorators, they must be async-compatible to ensure
    
  1951.     they work correctly. Django's built-in decorators will behave correctly, but
    
  1952.     third-party ones may appear to not execute (they will "wrap" the wrong part
    
  1953.     of the execution flow and not your test).
    
  1954. 
    
  1955.     If you need to use these decorators, then you should decorate your test
    
  1956.     methods with :func:`~asgiref.sync.async_to_sync` *inside* of them instead::
    
  1957. 
    
  1958.         from asgiref.sync import async_to_sync
    
  1959.         from django.test import TestCase
    
  1960. 
    
  1961.         class MyTests(TestCase):
    
  1962. 
    
  1963.             @mock.patch(...)
    
  1964.             @async_to_sync
    
  1965.             async def test_my_thing(self):
    
  1966.                 ...
    
  1967. 
    
  1968. .. _topics-testing-email:
    
  1969. 
    
  1970. Email services
    
  1971. ==============
    
  1972. 
    
  1973. If any of your Django views send email using :doc:`Django's email
    
  1974. functionality </topics/email>`, you probably don't want to send email each time
    
  1975. you run a test using that view. For this reason, Django's test runner
    
  1976. automatically redirects all Django-sent email to a dummy outbox. This lets you
    
  1977. test every aspect of sending email -- from the number of messages sent to the
    
  1978. contents of each message -- without actually sending the messages.
    
  1979. 
    
  1980. The test runner accomplishes this by transparently replacing the normal
    
  1981. email backend with a testing backend.
    
  1982. (Don't worry -- this has no effect on any other email senders outside of
    
  1983. Django, such as your machine's mail server, if you're running one.)
    
  1984. 
    
  1985. .. currentmodule:: django.core.mail
    
  1986. 
    
  1987. .. data:: django.core.mail.outbox
    
  1988. 
    
  1989. During test running, each outgoing email is saved in
    
  1990. ``django.core.mail.outbox``. This is a list of all
    
  1991. :class:`~django.core.mail.EmailMessage` instances that have been sent.  The
    
  1992. ``outbox`` attribute is a special attribute that is created *only* when the
    
  1993. ``locmem`` email backend is used. It doesn't normally exist as part of the
    
  1994. :mod:`django.core.mail` module and you can't import it directly. The code below
    
  1995. shows how to access this attribute correctly.
    
  1996. 
    
  1997. Here's an example test that examines ``django.core.mail.outbox`` for length
    
  1998. and contents::
    
  1999. 
    
  2000.     from django.core import mail
    
  2001.     from django.test import TestCase
    
  2002. 
    
  2003.     class EmailTest(TestCase):
    
  2004.         def test_send_email(self):
    
  2005.             # Send message.
    
  2006.             mail.send_mail(
    
  2007.                 'Subject here', 'Here is the message.',
    
  2008.                 '[email protected]', ['[email protected]'],
    
  2009.                 fail_silently=False,
    
  2010.             )
    
  2011. 
    
  2012.             # Test that one message has been sent.
    
  2013.             self.assertEqual(len(mail.outbox), 1)
    
  2014. 
    
  2015.             # Verify that the subject of the first message is correct.
    
  2016.             self.assertEqual(mail.outbox[0].subject, 'Subject here')
    
  2017. 
    
  2018. As noted :ref:`previously <emptying-test-outbox>`, the test outbox is emptied
    
  2019. at the start of every test in a Django ``*TestCase``. To empty the outbox
    
  2020. manually, assign the empty list to ``mail.outbox``::
    
  2021. 
    
  2022.     from django.core import mail
    
  2023. 
    
  2024.     # Empty the test outbox
    
  2025.     mail.outbox = []
    
  2026. 
    
  2027. .. _topics-testing-management-commands:
    
  2028. 
    
  2029. Management Commands
    
  2030. ===================
    
  2031. 
    
  2032. Management commands can be tested with the
    
  2033. :func:`~django.core.management.call_command` function. The output can be
    
  2034. redirected into a ``StringIO`` instance::
    
  2035. 
    
  2036.     from io import StringIO
    
  2037.     from django.core.management import call_command
    
  2038.     from django.test import TestCase
    
  2039. 
    
  2040.     class ClosepollTest(TestCase):
    
  2041.         def test_command_output(self):
    
  2042.             out = StringIO()
    
  2043.             call_command('closepoll', stdout=out)
    
  2044.             self.assertIn('Expected output', out.getvalue())
    
  2045. 
    
  2046. .. _skipping-tests:
    
  2047. 
    
  2048. Skipping tests
    
  2049. ==============
    
  2050. 
    
  2051. .. currentmodule:: django.test
    
  2052. 
    
  2053. The unittest library provides the :func:`@skipIf <unittest.skipIf>` and
    
  2054. :func:`@skipUnless <unittest.skipUnless>` decorators to allow you to skip tests
    
  2055. if you know ahead of time that those tests are going to fail under certain
    
  2056. conditions.
    
  2057. 
    
  2058. For example, if your test requires a particular optional library in order to
    
  2059. succeed, you could decorate the test case with :func:`@skipIf
    
  2060. <unittest.skipIf>`. Then, the test runner will report that the test wasn't
    
  2061. executed and why, instead of failing the test or omitting the test altogether.
    
  2062. 
    
  2063. To supplement these test skipping behaviors, Django provides two
    
  2064. additional skip decorators. Instead of testing a generic boolean,
    
  2065. these decorators check the capabilities of the database, and skip the
    
  2066. test if the database doesn't support a specific named feature.
    
  2067. 
    
  2068. The decorators use a string identifier to describe database features.
    
  2069. This string corresponds to attributes of the database connection
    
  2070. features class. See
    
  2071. :source:`django.db.backends.base.features.BaseDatabaseFeatures class
    
  2072. <django/db/backends/base/features.py>` for a full list of database features
    
  2073. that can be used as a basis for skipping tests.
    
  2074. 
    
  2075. .. function:: skipIfDBFeature(*feature_name_strings)
    
  2076. 
    
  2077. Skip the decorated test or ``TestCase`` if all of the named database features
    
  2078. are supported.
    
  2079. 
    
  2080. For example, the following test will not be executed if the database
    
  2081. supports transactions (e.g., it would *not* run under PostgreSQL, but
    
  2082. it would under MySQL with MyISAM tables)::
    
  2083. 
    
  2084.     class MyTests(TestCase):
    
  2085.         @skipIfDBFeature('supports_transactions')
    
  2086.         def test_transaction_behavior(self):
    
  2087.             # ... conditional test code
    
  2088.             pass
    
  2089. 
    
  2090. .. function:: skipUnlessDBFeature(*feature_name_strings)
    
  2091. 
    
  2092. Skip the decorated test or ``TestCase`` if any of the named database features
    
  2093. are *not* supported.
    
  2094. 
    
  2095. For example, the following test will only be executed if the database
    
  2096. supports transactions (e.g., it would run under PostgreSQL, but *not*
    
  2097. under MySQL with MyISAM tables)::
    
  2098. 
    
  2099.     class MyTests(TestCase):
    
  2100.         @skipUnlessDBFeature('supports_transactions')
    
  2101.         def test_transaction_behavior(self):
    
  2102.             # ... conditional test code
    
  2103.             pass