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