test.Client

class Client(enforce_csrf_checks=False, **defaults) [source]

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 get(), 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:

get(path, data=None, follow=False, secure=False, **extra) [source]

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 django.http.HttpRequest.is_ajax() method.

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.

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.

post(path, data=None, content_type=MULTIPART_CONTENT, follow=False, secure=False, **extra) [source]

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': 'secret'})

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

/login/

...with this POST data:

name=fred&passwd=secret

If you provide content_type (e.g. 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 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., StringIO or BytesIO) as a file handle.

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 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': 'secret'})

... 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.

head(path, data=None, follow=False, secure=False, **extra) [source]

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

options(path, data='', content_type='application/octet-stream', follow=False, secure=False, **extra) [source]

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 Client.get().

put(path, data='', content_type='application/octet-stream', follow=False, secure=False, **extra) [source]

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 Client.get().

patch(path, data='', content_type='application/octet-stream', follow=False, secure=False, **extra) [source]

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 Client.get().

delete(path, data='', content_type='application/octet-stream', follow=False, secure=False, **extra) [source]

Makes a 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 Client.get().

trace(path, follow=False, secure=False, **extra) [source]

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 7231#section-4.3.8, which mandates that TRACE requests must not have a body.

The follow, secure, and extra arguments act the same as for Client.get().

login(**credentials) [source]

If your site uses Django’s authentication system 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 authentication backend you’re using (which is configured by your 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='secret')

# 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 set_password() function to store a correctly hashed password. Alternatively, you can use the create_user() helper method to create a new user with a correctly hashed password.

Changed in Django 1.10:

In previous versions, inactive users (is_active=False) were not permitted to login.

force_login(user, backend=None) [source]
New in Django 1.9.

If your site uses Django’s authentication system, you can use the force_login() method to simulate the effect of a user logging into the site. Use this method instead of login() when a test requires a user be logged in and the details of how a user logged in aren’t important.

Unlike login(), this method skips the authentication and verification steps: inactive users (is_active=False) are permitted to login and the user’s credentials don’t need to be provided.

The user will have its backend attribute set to the value of the backend argument (which should be a dotted Python path string), or to settings.AUTHENTICATION_BACKENDS[0] if a value isn’t provided. The authenticate() function called by login() normally annotates the user like this.

This method is faster than login() since the expensive password hashing algorithms are bypassed. Also, you can speed up login() by using a weaker hasher while testing.

logout() [source]

If your site uses Django’s authentication system, 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 AnonymousUser.

doc_Django
2016-10-09 18:39:54
Comments
Leave a Comment

Please login to continue.