Fixed #29082 -- Allowed the test client to encode JSON request data.

This commit is contained in:
Nick Sarbicki 2018-02-05 10:22:24 +00:00 committed by Tim Graham
parent d968788b57
commit 47268242b0
7 changed files with 86 additions and 6 deletions

View file

@ -109,7 +109,7 @@ Making requests
Use the ``django.test.Client`` class to make requests.
.. class:: Client(enforce_csrf_checks=False, **defaults)
.. class:: Client(enforce_csrf_checks=False, json_encoder=DjangoJSONEncoder, **defaults)
It requires no arguments at time of construction. However, you can use
keywords arguments to specify some default headers. For example, this will
@ -125,6 +125,13 @@ Use the ``django.test.Client`` class to make requests.
The ``enforce_csrf_checks`` argument can be used to test CSRF
protection (see above).
The ``json_encoder`` argument allows setting a custom JSON encoder for
the JSON serialization that's described in :meth:`post`.
.. versionchanged:: 2.1
The ``json_encoder`` argument was added.
Once you have a ``Client`` instance, you can call any of the following
methods:
@ -206,9 +213,23 @@ Use the ``django.test.Client`` class to make requests.
name=fred&passwd=secret
If you provide ``content_type`` (e.g. :mimetype:`text/xml` for an XML
payload), the contents of ``data`` will be sent as-is in the POST
request, using ``content_type`` in the HTTP ``Content-Type`` header.
If you provide ``content_type`` as :mimetype:`application/json`, a
``data`` dictionary is serialized using :func:`json.dumps` with
:class:`~django.core.serializers.json.DjangoJSONEncoder`. You can
change the encoder by providing a ``json_encoder`` argument to
:class:`Client`. This serialization also happens for :meth:`put`,
:meth:`patch`, and :meth:`delete` requests.
.. versionchanged:: 2.1
The JSON serialization described above was added. In older versions,
you can call :func:`json.dumps` on ``data`` before passing it to
``post()`` to achieve the same thing.
If you provide any other ``content_type`` (e.g. :mimetype:`text/xml`
for an XML payload), the contents of ``data`` are sent as-is in the
POST request, using ``content_type`` in the HTTP ``Content-Type``
header.
If you don't provide a value for ``content_type``, the values in
``data`` will be transmitted with a content type of