<commit_before>=============
Testing tools
=============

.. currentmodule:: django.test

Django provides a small set of tools that come in handy when writing tests.

.. _test-client:

The test client
---------------

The test client is a Python class that acts as a dummy Web browser, allowing
you to test your views and interact with your Django-powered application
programmatically.

Some of the things you can do with the test client are:

* Simulate GET and POST requests on a URL and observe the response --
  everything from low-level HTTP (result headers and status codes) to
  page content.

* See the chain of redirects (if any) and check the URL and status code at
  each step.

* Test that a given request is rendered by a given Django template, with
  a template context that contains certain values.

Note that the test client is not intended to be a replacement for Selenium_ or
other "in-browser" frameworks. Django's test client has a different focus. In
short:

* Use Django's test client to establish that the correct template is being
  rendered and that the template is passed the correct context data.

* Use in-browser frameworks like Selenium_ to test *rendered* HTML and the
  *behavior* of Web pages, namely JavaScript functionality. Django also
  provides special support for those frameworks; see the section on
  :class:`~django.test.LiveServerTestCase` for more details.

A comprehensive test suite should use a combination of both test types.

Overview and a quick example
~~~~~~~~~~~~~~~~~~~~~~~~~~~~

To use the test client, instantiate ``django.test.Client`` and retrieve
Web pages::

    >>> from django.test import Client
    >>> c = Client()
    >>> response = c.post('/login/', {'username': 'john', 'password': '<PASSWORD>'})
    >>> response.status_code
    200
    >>> response = c.get('/customer/details/')
    >>> response.content
    '<!DOCTYPE html...'

As this example suggests, you can instantiate ``Client`` from within a session
of the Python interactive interpreter.

Note a few important things about how the test client works:

* The test client does *not* require the Web server to be running. In fact,
  it will run just fine with no Web server running at all! That's because
  it avoids the overhead of HTTP and deals directly with the Django
  framework. This helps make the unit tests run quickly.

* When retrieving pages, remember to specify the *path* of the URL, not the
  whole domain. For example, this is correct::

      >>> c.get('/login/')

  This is incorrect::

      >>> c.get('http://www.example.com/login/')

  The test client is not capable of retrieving Web pages that are not
  powered by your Django project. If you need to retrieve other Web pages,
  use a Python standard library module such as :mod:`urllib`.

* To resolve URLs, the test client uses whatever URLconf is pointed-to by
  your :setting:`ROOT_URLCONF` setting.

* Although the above example would work in the Python interactive
  interpreter, some of the test client's functionality, notably the
  template-related functionality, is only available *while tests are
  running*.

  The reason for this is that Django's test runner performs a bit of black
  magic in order to determine which template was loaded by a given view.
  This black magic (essentially a patching of Django's template system in
  memory) only happens during test running.

* By default, the test client will disable any CSRF checks
  performed by your site.

  If, for some reason, you *want* the test client to perform CSRF
  checks, you can create an instance of the test client that
  enforces CSRF checks. To do this, pass in the
  ``enforce_csrf_checks`` argument when you construct your
  client::

      >>> from django.test import Client
      >>> csrf_client = Client(enforce_csrf_checks=True)

Making requests
~~~~~~~~~~~~~~~

Use the ``django.test.Client`` class to make requests.

.. class:: Client(enforce_csrf_checks=False, **defaults)

    It requires no arguments at time of construction. However, you can use
    keywords arguments to specify some default headers. For example, this will
    send a ``User-Agent`` HTTP header in each request::

        >>> c = Client(HTTP_USER_AGENT='Mozilla/5.0')

    The values from the ``extra`` keywords arguments passed to
    :meth:`~django.test.Client.get()`,
    :meth:`~django.test.Client.post()`, etc. have precedence over
    the defaults passed to the class constructor.

    The ``enforce_csrf_checks`` argument can be used to test CSRF
    protection (see above).

    Once you have a ``Client`` instance, you can call any of the following
    methods:

    .. method:: Client.get(path, data=None, follow=False, secure=False, **extra)

        .. versionadded:: 1.7

            The ``secure`` argument was added.

        Makes a GET request on the provided ``path`` and returns a ``Response``
        object, which is documented below.

        The key-value pairs in the ``data`` dictionary are used to create a GET
        data payload. For example::

            >>> c = Client()
            >>> c.get('/customers/details/', {'name': 'fred', 'age': 7})

        ...will result in the evaluation of a GET request equivalent to::

            /customers/details/?name=fred&age=7

        The ``extra`` keyword arguments parameter can be used to specify
        headers to be sent in the request. For example::

            >>> c = Client()
            >>> c.get('/customers/details/', {'name': 'fred', 'age': 7},
            ...       HTTP_X_REQUESTED_WITH='XMLHttpRequest')

        ...will send the HTTP header ``HTTP_X_REQUESTED_WITH`` to the
        details view, which is a good way to test code paths that use the
        :meth:`django.http.HttpRequest.is_ajax()` method.

        .. admonition:: CGI specification

            The headers sent via ``**extra`` should follow CGI_ specification.
            For example, emulating a different "Host" header as sent in the
            HTTP request from the browser to the server should be passed
            as ``HTTP_HOST``.

            .. _CGI: http://www.w3.org/CGI/

        If you already have the GET arguments in URL-encoded form, you can
        use that encoding instead of using the data argument. For example,
        the previous GET request could also be posed as::

        >>> c = Client()
        >>> c.get('/customers/details/?name=fred&age=7')

        If you provide a URL with both an encoded GET data and a data argument,
        the data argument will take precedence.

        If you set ``follow`` to ``True`` the client will follow any redirects
        and a ``redirect_chain`` attribute will be set in the response object
        containing tuples of the intermediate urls and status codes.

        If you had a URL ``/redirect_me/`` that redirected to ``/next/``, that
        redirected to ``/final/``, this is what you'd see::

            >>> response = c.get('/redirect_me/', follow=True)
            >>> response.redirect_chain
            [('http://testserver/next/', 302), ('http://testserver/final/', 302)]

        If you set ``secure`` to ``True`` the client will emulate an HTTPS
        request.

    .. method:: Client.post(path, data=None, content_type=MULTIPART_CONTENT, follow=False, secure=False, **extra)

        Makes a POST request on the provided ``path`` and returns a
        ``Response`` object, which is documented below.

        The key-value pairs in the ``data`` dictionary are used to submit POST
        data. For example::

            >>> c = Client()
            >>> c.post('/login/', {'name': 'fred', 'passwd': '<PASSWORD>'})

        ...will result in the evaluation of a POST request to this URL::

            /login/

        ...with this POST data::

            name=fred&passwd=<PASSWORD>

        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 don't provide a value for ``content_type``, the values in
        ``data`` will be transmitted with a content type of
        :mimetype:`multipart/form-data`. In this case, the key-value pairs in
        ``data`` will be encoded as a multipart message and used to create the
        POST data payload.

        To submit multiple values for a given key -- for example, to specify
        the selections for a ``<select multiple>`` -- provide the values as a
        list or tuple for the required key. For example, this value of ``data``
        would submit three selected values for the field named ``choices``::

            {'choices': ('a', 'b', 'd')}

        Submitting files is a special case. To POST a file, you need only
        provide the file field name as a key, and a file handle to the file you
        wish to upload as a value. For example::

            >>> c = Client()
            >>> with open('wishlist.doc') as fp:
            ...     c.post('/customers/wishes/', {'name': 'fred', 'attachment': fp})

        (The name ``attachment`` here is not relevant; use whatever name your
        file-processing code expects.)

        You may also provide any file-like object (e.g., :class:`~io.StringIO` or
        :class:`~io.BytesIO`) as a file handle.

        .. versionadded:: 1.8

            The ability to use a file-like object was added.

        Note that if you wish to use the same file handle for multiple
        ``post()`` calls then you will need to manually reset the file
        pointer between posts. The easiest way to do this is to
        manually close the file after it has been provided to
        ``post()``, as demonstrated above.

        You should also ensure that the file is opened in a way that
        allows the data to be read. If your file contains binary data
        such as an image, this means you will need to open the file in
        ``rb`` (read binary) mode.

        The ``extra`` argument acts the same as for :meth:`Client.get`.

        If the URL you request with a POST contains encoded parameters, these
        parameters will be made available in the request.GET data. For example,
        if you were to make the request::

        >>> c.post('/login/?visitor=true', {'name': 'fred', 'passwd': '<PASSWORD>'})

        ... the view handling this request could interrogate request.POST
        to retrieve the username and password, and could interrogate request.GET
        to determine if the user was a visitor.

        If you set ``follow`` to ``True`` the client will follow any redirects
        and a ``redirect_chain`` attribute will be set in the response object
        containing tuples of the intermediate urls and status codes.

        If you set ``secure`` to ``True`` the client will emulate an HTTPS
        request.

    .. method:: Client.head(path, data=None, follow=False, secure=False, **extra)

        Makes a HEAD request on the provided ``path`` and returns a
        ``Response`` object. This method works just like :meth:`Client.get`,
        including the ``follow``, ``secure`` and ``extra`` arguments, except
        it does not return a message body.

    .. method:: Client.options(path, data='', content_type='application/octet-stream', follow=False, secure=False, **extra)

        Makes an OPTIONS request on the provided ``path`` and returns a
        ``Response`` object. Useful for testing RESTful interfaces.

        When ``data`` is provided, it is used as the request body, and
        a ``Content-Type`` header is set to ``content_type``.

        The ``follow``, ``secure`` and ``extra`` arguments act the same as for
        :meth:`Client.get`.

    .. method:: Client.put(path, data='', content_type='application/octet-stream', follow=False, secure=False, **extra)

        Makes a PUT request on the provided ``path`` and returns a
        ``Response`` object. Useful for testing RESTful interfaces.

        When ``data`` is provided, it is used as the request body, and
        a ``Content-Type`` header is set to ``content_type``.

        The ``follow``, ``secure`` and ``extra`` arguments act the same as for
        :meth:`Client.get`.

    .. method:: Client.patch(path, data='', content_type='application/octet-stream', follow=False, secure=False, **extra)

        Makes a PATCH request on the provided ``path`` and returns a
        ``Response`` object. Useful for testing RESTful interfaces.

        The ``follow``, ``secure`` and ``extra`` arguments act the same as for
        :meth:`Client.get`.

    .. method:: Client.delete(path, data='', content_type='application/octet-stream', follow=False, secure=False, **extra)

        Makes an DELETE request on the provided ``path`` and returns a
        ``Response`` object. Useful for testing RESTful interfaces.

        When ``data`` is provided, it is used as the request body, and
        a ``Content-Type`` header is set to ``content_type``.

        The ``follow``, ``secure`` and ``extra`` arguments act the same as for
        :meth:`Client.get`.

    .. method:: Client.trace(path, follow=False, secure=False, **extra)

        .. versionadded:: 1.8

        Makes a TRACE request on the provided ``path`` and returns a
        ``Response`` object. Useful for simulating diagnostic probes.

        Unlike the other request methods, ``data`` is not provided as a keyword
        parameter in order to comply with :rfc:`2616`, which mandates that
        TRACE requests should not have an entity-body.

        The ``follow``, ``secure``, and ``extra`` arguments act the same as for
        :meth:`Client.get`.

    .. method:: Client.login(**credentials)

        If your site uses Django's :doc:`authentication system</topics/auth/index>`
        and you deal with logging in users, you can use the test client's
        ``login()`` method to simulate the effect of a user logging into the
        site.

        After you call this method, the test client will have all the cookies
        and session data required to pass any login-based tests that may form
        part of a view.

        The format of the ``credentials`` argument depends on which
        :ref:`authentication backend <authentication-backends>` you're using
        (which is configured by your :setting:`AUTHENTICATION_BACKENDS`
        setting). If you're using the standard authentication backend provided
        by Django (``ModelBackend``), ``credentials`` should be the user's
        username and password, provided as keyword arguments::

            >>> c = Client()
            >>> c.login(username='fred', password='<PASSWORD>')

            # Now you can access a view that's only available to logged-in users.

        If you're using a different authentication backend, this method may
        require different credentials. It requires whichever credentials are
        required by your backend's ``authenticate()`` method.

        ``login()`` returns ``True`` if it the credentials were accepted and
        login was successful.

        Finally, you'll need to remember to create user accounts before you can
        use this method. As we explained above, the test runner is executed
        using a test database, which contains no users by default. As a result,
        user accounts that are valid on your production site will not work
        under test conditions. You'll need to create users as part of the test
        suite -- either manually (using the Django model API) or with a test
        fixture. Remember that if you want your test user to have a password,
        you can't set the user's password by setting the password attribute
        directly -- you must use the
        :meth:`~django.contrib.auth.models.User.set_password()` function to
        store a correctly hashed password. Alternatively, you can use the
        :meth:`~django.contrib.auth.models.UserManager.create_user` helper
        method to create a new user with a correctly hashed password.

    .. method:: Client.logout()

        If your site uses Django's :doc:`authentication system</topics/auth/index>`,
        the ``logout()`` method can be used to simulate the effect of a user
        logging out of your site.

        After you call this method, the test client will have all the cookies
        and session data cleared to defaults. Subsequent requests will appear
        to come from an :class:`~django.contrib.auth.models.AnonymousUser`.

Testing responses
~~~~~~~~~~~~~~~~~

The ``get()`` and ``post()`` methods both return a ``Response`` object. This
``Response`` object is *not* the same as the ``HttpResponse`` object returned
Django views; the test response object has some additional data useful for
test code to verify.

Specifically, a ``Response`` object has the following attributes:

.. class:: Response()

    .. attribute:: client

        The test client that was used to make the request that resulted in the
        response.

    .. attribute:: content

        The body of the response, as a string. This is the final page content as
        rendered by the view, or any error message.

    .. attribute:: context

        The template ``Context`` instance that was used to render the template that
        produced the response content.

        If the rendered page used multiple templates, then ``context`` will be a<commit_msg>Fixed a typo in the test responses docs.<commit_after>=============
Testing tools
=============

.. currentmodule:: django.test

Django provides a small set of tools that come in handy when writing tests.

.. _test-client:

The test client
---------------

The test client is a Python class that acts as a dummy Web browser, allowing
you to test your views and interact with your Django-powered application
programmatically.

Some of the things you can do with the test client are:

* Simulate GET and POST requests on a URL and observe the response --
  everything from low-level HTTP (result headers and status codes) to
  page content.

* See the chain of redirects (if any) and check the URL and status code at
  each step.

* Test that a given request is rendered by a given Django template, with
  a template context that contains certain values.

Note that the test client is not intended to be a replacement for Selenium_ or
other "in-browser" frameworks. Django's test client has a different focus. In
short:

* Use Django's test client to establish that the correct template is being
  rendered and that the template is passed the correct context data.

* Use in-browser frameworks like Selenium_ to test *rendered* HTML and the
  *behavior* of Web pages, namely JavaScript functionality. Django also
  provides special support for those frameworks; see the section on
  :class:`~django.test.LiveServerTestCase` for more details.

A comprehensive test suite should use a combination of both test types.

Overview and a quick example
~~~~~~~~~~~~~~~~~~~~~~~~~~~~

To use the test client, instantiate ``django.test.Client`` and retrieve
Web pages::

    >>> from django.test import Client
    >>> c = Client()
    >>> response = c.post('/login/', {'username': 'john', 'password': '<PASSWORD>'})
    >>> response.status_code
    200
    >>> response = c.get('/customer/details/')
    >>> response.content
    '<!DOCTYPE html...'

As this example suggests, you can instantiate ``Client`` from within a session
of the Python interactive interpreter.

Note a few important things about how the test client works:

* The test client does *not* require the Web server to be running. In fact,
  it will run just fine with no Web server running at all! That's because
  it avoids the overhead of HTTP and deals directly with the Django
  framework. This helps make the unit tests run quickly.

* When retrieving pages, remember to specify the *path* of the URL, not the
  whole domain. For example, this is correct::

      >>> c.get('/login/')

  This is incorrect::

      >>> c.get('http://www.example.com/login/')

  The test client is not capable of retrieving Web pages that are not
  powered by your Django project. If you need to retrieve other Web pages,
  use a Python standard library module such as :mod:`urllib`.

* To resolve URLs, the test client uses whatever URLconf is pointed-to by
  your :setting:`ROOT_URLCONF` setting.

* Although the above example would work in the Python interactive
  interpreter, some of the test client's functionality, notably the
  template-related functionality, is only available *while tests are
  running*.

  The reason for this is that Django's test runner performs a bit of black
  magic in order to determine which template was loaded by a given view.
  This black magic (essentially a patching of Django's template system in
  memory) only happens during test running.

* By default, the test client will disable any CSRF checks
  performed by your site.

  If, for some reason, you *want* the test client to perform CSRF
  checks, you can create an instance of the test client that
  enforces CSRF checks. To do this, pass in the
  ``enforce_csrf_checks`` argument when you construct your
  client::

      >>> from django.test import Client
      >>> csrf_client = Client(enforce_csrf_checks=True)

Making requests
~~~~~~~~~~~~~~~

Use the ``django.test.Client`` class to make requests.

.. class:: Client(enforce_csrf_checks=False, **defaults)

    It requires no arguments at time of construction. However, you can use
    keywords arguments to specify some default headers. For example, this will
    send a ``User-Agent`` HTTP header in each request::

        >>> c = Client(HTTP_USER_AGENT='Mozilla/5.0')

    The values from the ``extra`` keywords arguments passed to
    :meth:`~django.test.Client.get()`,
    :meth:`~django.test.Client.post()`, etc. have precedence over
    the defaults passed to the class constructor.

    The ``enforce_csrf_checks`` argument can be used to test CSRF
    protection (see above).

    Once you have a ``Client`` instance, you can call any of the following
    methods:

    .. method:: Client.get(path, data=None, follow=False, secure=False, **extra)

        .. versionadded:: 1.7

            The ``secure`` argument was added.

        Makes a GET request on the provided ``path`` and returns a ``Response``
        object, which is documented below.

        The key-value pairs in the ``data`` dictionary are used to create a GET
        data payload. For example::

            >>> c = Client()
            >>> c.get('/customers/details/', {'name': 'fred', 'age': 7})

        ...will result in the evaluation of a GET request equivalent to::

            /customers/details/?name=fred&age=7

        The ``extra`` keyword arguments parameter can be used to specify
        headers to be sent in the request. For example::

            >>> c = Client()
            >>> c.get('/customers/details/', {'name': 'fred', 'age': 7},
            ...       HTTP_X_REQUESTED_WITH='XMLHttpRequest')

        ...will send the HTTP header ``HTTP_X_REQUESTED_WITH`` to the
        details view, which is a good way to test code paths that use the
        :meth:`django.http.HttpRequest.is_ajax()` method.

        .. admonition:: CGI specification

            The headers sent via ``**extra`` should follow CGI_ specification.
            For example, emulating a different "Host" header as sent in the
            HTTP request from the browser to the server should be passed
            as ``HTTP_HOST``.

            .. _CGI: http://www.w3.org/CGI/

        If you already have the GET arguments in URL-encoded form, you can
        use that encoding instead of using the data argument. For example,
        the previous GET request could also be posed as::

        >>> c = Client()
        >>> c.get('/customers/details/?name=fred&age=7')

        If you provide a URL with both an encoded GET data and a data argument,
        the data argument will take precedence.

        If you set ``follow`` to ``True`` the client will follow any redirects
        and a ``redirect_chain`` attribute will be set in the response object
        containing tuples of the intermediate urls and status codes.

        If you had a URL ``/redirect_me/`` that redirected to ``/next/``, that
        redirected to ``/final/``, this is what you'd see::

            >>> response = c.get('/redirect_me/', follow=True)
            >>> response.redirect_chain
            [('http://testserver/next/', 302), ('http://testserver/final/', 302)]

        If you set ``secure`` to ``True`` the client will emulate an HTTPS
        request.

    .. method:: Client.post(path, data=None, content_type=MULTIPART_CONTENT, follow=False, secure=False, **extra)

        Makes a POST request on the provided ``path`` and returns a
        ``Response`` object, which is documented below.

        The key-value pairs in the ``data`` dictionary are used to submit POST
        data. For example::

            >>> c = Client()
            >>> c.post('/login/', {'name': 'fred', 'passwd': '<PASSWORD>'})

        ...will result in the evaluation of a POST request to this URL::

            /login/

        ...with this POST data::

            name=fred&passwd=<PASSWORD>

        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 don't provide a value for ``content_type``, the values in
        ``data`` will be transmitted with a content type of
        :mimetype:`multipart/form-data`. In this case, the key-value pairs in
        ``data`` will be encoded as a multipart message and used to create the
        POST data payload.

        To submit multiple values for a given key -- for example, to specify
        the selections for a ``<select multiple>`` -- provide the values as a
        list or tuple for the required key. For example, this value of ``data``
        would submit three selected values for the field named ``choices``::

            {'choices': ('a', 'b', 'd')}

        Submitting files is a special case. To POST a file, you need only
        provide the file field name as a key, and a file handle to the file you
        wish to upload as a value. For example::

            >>> c = Client()
            >>> with open('wishlist.doc') as fp:
            ...     c.post('/customers/wishes/', {'name': 'fred', 'attachment': fp})

        (The name ``attachment`` here is not relevant; use whatever name your
        file-processing code expects.)

        You may also provide any file-like object (e.g., :class:`~io.StringIO` or
        :class:`~io.BytesIO`) as a file handle.

        .. versionadded:: 1.8

            The ability to use a file-like object was added.

        Note that if you wish to use the same file handle for multiple
        ``post()`` calls then you will need to manually reset the file
        pointer between posts. The easiest way to do this is to
        manually close the file after it has been provided to
        ``post()``, as demonstrated above.

        You should also ensure that the file is opened in a way that
        allows the data to be read. If your file contains binary data
        such as an image, this means you will need to open the file in
        ``rb`` (read binary) mode.

        The ``extra`` argument acts the same as for :meth:`Client.get`.

        If the URL you request with a POST contains encoded parameters, these
        parameters will be made available in the request.GET data. For example,
        if you were to make the request::

        >>> c.post('/login/?visitor=true', {'name': 'fred', 'passwd': '<PASSWORD>'})

        ... the view handling this request could interrogate request.POST
        to retrieve the username and password, and could interrogate request.GET
        to determine if the user was a visitor.

        If you set ``follow`` to ``True`` the client will follow any redirects
        and a ``redirect_chain`` attribute will be set in the response object
        containing tuples of the intermediate urls and status codes.

        If you set ``secure`` to ``True`` the client will emulate an HTTPS
        request.

    .. method:: Client.head(path, data=None, follow=False, secure=False, **extra)

        Makes a HEAD request on the provided ``path`` and returns a
        ``Response`` object. This method works just like :meth:`Client.get`,
        including the ``follow``, ``secure`` and ``extra`` arguments, except
        it does not return a message body.

    .. method:: Client.options(path, data='', content_type='application/octet-stream', follow=False, secure=False, **extra)

        Makes an OPTIONS request on the provided ``path`` and returns a
        ``Response`` object. Useful for testing RESTful interfaces.

        When ``data`` is provided, it is used as the request body, and
        a ``Content-Type`` header is set to ``content_type``.

        The ``follow``, ``secure`` and ``extra`` arguments act the same as for
        :meth:`Client.get`.

    .. method:: Client.put(path, data='', content_type='application/octet-stream', follow=False, secure=False, **extra)

        Makes a PUT request on the provided ``path`` and returns a
        ``Response`` object. Useful for testing RESTful interfaces.

        When ``data`` is provided, it is used as the request body, and
        a ``Content-Type`` header is set to ``content_type``.

        The ``follow``, ``secure`` and ``extra`` arguments act the same as for
        :meth:`Client.get`.

    .. method:: Client.patch(path, data='', content_type='application/octet-stream', follow=False, secure=False, **extra)

        Makes a PATCH request on the provided ``path`` and returns a
        ``Response`` object. Useful for testing RESTful interfaces.

        The ``follow``, ``secure`` and ``extra`` arguments act the same as for
        :meth:`Client.get`.

    .. method:: Client.delete(path, data='', content_type='application/octet-stream', follow=False, secure=False, **extra)

        Makes an DELETE request on the provided ``path`` and returns a
        ``Response`` object. Useful for testing RESTful interfaces.

        When ``data`` is provided, it is used as the request body, and
        a ``Content-Type`` header is set to ``content_type``.

        The ``follow``, ``secure`` and ``extra`` arguments act the same as for
        :meth:`Client.get`.

    .. method:: Client.trace(path, follow=False, secure=False, **extra)

        .. versionadded:: 1.8

        Makes a TRACE request on the provided ``path`` and returns a
        ``Response`` object. Useful for simulating diagnostic probes.

        Unlike the other request methods, ``data`` is not provided as a keyword
        parameter in order to comply with :rfc:`2616`, which mandates that
        TRACE requests should not have an entity-body.

        The ``follow``, ``secure``, and ``extra`` arguments act the same as for
        :meth:`Client.get`.

    .. method:: Client.login(**credentials)

        If your site uses Django's :doc:`authentication system</topics/auth/index>`
        and you deal with logging in users, you can use the test client's
        ``login()`` method to simulate the effect of a user logging into the
        site.

        After you call this method, the test client will have all the cookies
        and session data required to pass any login-based tests that may form
        part of a view.

        The format of the ``credentials`` argument depends on which
        :ref:`authentication backend <authentication-backends>` you're using
        (which is configured by your :setting:`AUTHENTICATION_BACKENDS`
        setting). If you're using the standard authentication backend provided
        by Django (``ModelBackend``), ``credentials`` should be the user's
        username and password, provided as keyword arguments::

            >>> c = Client()
            >>> c.login(username='fred', password='<PASSWORD>')

            # Now you can access a view that's only available to logged-in users.

        If you're using a different authentication backend, this method may
        require different credentials. It requires whichever credentials are
        required by your backend's ``authenticate()`` method.

        ``login()`` returns ``True`` if it the credentials were accepted and
        login was successful.

        Finally, you'll need to remember to create user accounts before you can
        use this method. As we explained above, the test runner is executed
        using a test database, which contains no users by default. As a result,
        user accounts that are valid on your production site will not work
        under test conditions. You'll need to create users as part of the test
        suite -- either manually (using the Django model API) or with a test
        fixture. Remember that if you want your test user to have a password,
        you can't set the user's password by setting the password attribute
        directly -- you must use the
        :meth:`~django.contrib.auth.models.User.set_password()` function to
        store a correctly hashed password. Alternatively, you can use the
        :meth:`~django.contrib.auth.models.UserManager.create_user` helper
        method to create a new user with a correctly hashed password.

    .. method:: Client.logout()

        If your site uses Django's :doc:`authentication system</topics/auth/index>`,
        the ``logout()`` method can be used to simulate the effect of a user
        logging out of your site.

        After you call this method, the test client will have all the cookies
        and session data cleared to defaults. Subsequent requests will appear
        to come from an :class:`~django.contrib.auth.models.AnonymousUser`.

Testing responses
~~~~~~~~~~~~~~~~~

The ``get()`` and ``post()`` methods both return a ``Response`` object. This
``Response`` object is *not* the same as the ``HttpResponse`` object returned
by Django views; the test response object has some additional data useful for
test code to verify.

Specifically, a ``Response`` object has the following attributes:

.. class:: Response()

    .. attribute:: client

        The test client that was used to make the request that resulted in the
        response.

    .. attribute:: content

        The body of the response, as a string. This is the final page content as
        rendered by the view, or any error message.

    .. attribute:: context

        The template ``Context`` instance that was used to render the template that
        produced the response content.

        If the rendered page used multiple templates, then ``context`` will be a
{'fraction_non_alphanumeric': 0.09731080848129633, 'fraction_numerical': 0.0014939952881687065, 'mean_word_length': 2.83844287604764, 'pattern_counts': {'":': 0, '<': 23, '<?xml version=': 0, '>': 177, 'https://': 0, 'lorem ipsum': 0, 'www.': 4, 'xml': 2}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2619512', 'n_tokens_mistral': 9051, 'n_tokens_neox': 8566, 'n_words': 4353}