Skip to content

API reference

test_plus.test

TestCase

Bases: TestCase, BaseTestCase

Django TestCase with helpful additional features

BaseTestCase

Bases: StatusCodeAssertionMixin

Django TestCase with helpful additional features

print_form_errors(response_or_form=None)

A utility method for quickly debugging responses with form errors.

request(method_name, url_name, *args, **kwargs)

Request url by name using reverse() through method

If reverse raises NoReverseMatch attempt to use it as a URL.

response_200(response=None, msg=None)

Given response has status_code 200

response_201(response=None, msg=None)

Given response has status_code 201

response_204(response=None, msg=None)

Given response has status_code 204

response_301(response=None, msg=None)

Given response has status_code 301

response_302(response=None, msg=None)

Given response has status_code 302

response_400(response=None, msg=None)

Given response has status_code 400

response_401(response=None, msg=None)

Given response has status_code 401

response_403(response=None, msg=None)

Given response has status_code 403

response_404(response=None, msg=None)

Given response has status_code 404

response_405(response=None, msg=None)

Given response has status_code 405

response_409(response=None, msg=None)

Given response has status_code 409

response_410(response=None, msg=None)

Given response has status_code 410

get_check_200(url, *args, **kwargs)

Test that we can GET a page and it returns a 200

assertLoginRequired(url, *args, method='get', **kwargs)

Ensure login is required to access this URL via (default GET)

url may be a url name or a plain URL, matching what request() accepts.

login(*args, **credentials)

Login a user

reverse(name, *args, **kwargs)

Reverse a url, convenience to avoid having to import reverse in tests

make_user(username='testuser', password='password', perms=None) classmethod

Build a user with and password of 'password' for testing purposes.

assertGoodView(url_name, *args, verbose=False, **kwargs)

Quick-n-dirty testing of a given url name. Ensures URL returns a 200 status and that generates less than 50 database queries.

assertResponseContains(text, response=None, html=True, **kwargs)

Convenience wrapper for assertContains

assertResponseNotContains(text, response=None, html=True, **kwargs)

Convenience wrapper for assertNotContains

assertResponseTemplateUsed(template_name, response=None, **kwargs)

Convenience wrapper for assertTemplateUsed

assertResponseTemplateNotUsed(template_name, response=None, **kwargs)

Convenience wrapper for assertTemplateNotUsed

assertResponseHeaders(headers, response=None)

Check that the headers in the response are as expected.

Only headers defined in headers are compared, other keys present on the response will be ignored.

Parameters:

Name Type Description Default
headers :class:`collections.Mapping`

Mapping of header names to expected values

required
response :class:`django.http.response.HttpResponse`

Response to check headers against

None

assertResponseMessages(expected_messages, response=None, ordered=True)

Convenience wrapper for assertMessages that uses the last response by default.

Tests that the messages in the response match the expected messages.

Parameters:

Name Type Description Default
expected_messages

List of Message objects to compare against

required
response

Response to check messages against (defaults to last_response)

None
ordered

If True, messages must match in order (default: True)

True

CBVTestCase

Bases: TestCase

Directly calls class-based generic view methods, bypassing the Django test Client.

This process bypasses middleware invocation and URL resolvers.

Example usage:

from myapp.views import MyClass

class MyClassTest(CBVTestCase):

    def test_special_method(self):
        request = RequestFactory().get('/')
        instance = self.get_instance(MyClass, request=request)

        # invoke a MyClass method
        result = instance.special_method()

        # make assertions
        self.assertTrue(result)

get_instance(view_cls, *args, **kwargs) staticmethod

Returns a decorated instance of a class-based generic view class.

Use initkwargs to set expected class attributes. For example, set the object attribute on MyDetailView class:

instance = self.get_instance(MyDetailView, initkwargs={'object': obj}, request)

because SingleObjectMixin (part of generic.DetailView) expects self.object to be set before invoking get_context_data().

Pass a "request" kwarg in order for your tests to have particular request attributes.

get(view_cls, *args, **kwargs)

Calls view_cls.get() method after instantiating view class. Renders view templates and sets context if appropriate.

post(view_cls, *args, **kwargs)

Calls view_cls.post() method after instantiating view class. Renders view templates and sets context if appropriate.

get_response(request, view_func)

Obtain response from view class method (typically get or post).

No middleware is invoked, but templates are rendered and context saved if appropriate.

get_check_200(url, *args, **kwargs)

Test that we can GET a page and it returns a 200

assertGoodView(url_name, *args, **kwargs)

Quick-n-dirty testing of a given view. Ensures view returns a 200 status and that generates less than 50 database queries.

APITestCase

Bases: TestCase

NoPreviousResponse

Bases: Exception

test_plus.status_codes.StatusCodeAssertionMixin

The following assert_http_###_status_name methods were intentionally added statically instead of dynamically so that code completion in IDEs like PyCharm would work. They are the preferred spelling, but the response_XXX methods are supported permanently and are not deprecated. The assert methods contain both the number and the status name slug so that people that remember them best by their numeric code and people that remember best by their name will be able to easily find the assertion they need. This was also directly patterned off of what the Django Rest Framework uses <https://github.com/encode/django-rest-framework/blob/main/rest_framework/status.py>_.

assert_http_100_continue(response=None, msg=None)

Server has received request headers and client should proceed to send request body.

assert_http_101_switching_protocols(response=None, msg=None)

Server is switching protocols as requested by the client.

assert_http_102_processing(response=None, msg=None)

Server has received the request and is still processing it (WebDAV).

assert_http_103_early_hints(response=None, msg=None)

Used to return some response headers before final HTTP message.

assert_http_200_ok(response=None, msg=None)

Request succeeded.

assert_http_201_created(response=None, msg=None)

Request succeeded and a new resource was created.

assert_http_202_accepted(response=None, msg=None)

Request received but not yet acted upon.

assert_http_203_non_authoritative_information(response=None, msg=None)

Returned metadata is not from the origin server but from a third party.

assert_http_204_no_content(response=None, msg=None)

Request succeeded but no content to send back.

assert_http_205_reset_content(response=None, msg=None)

Request succeeded and client should reset the document view.

assert_http_206_partial_content(response=None, msg=None)

Request succeeded and body contains requested ranges of data.

assert_http_207_multi_status(response=None, msg=None)

Response conveys information about multiple resources (WebDAV).

assert_http_208_already_reported(response=None, msg=None)

Members of a DAV binding have already been enumerated (WebDAV).

assert_http_226_im_used(response=None, msg=None)

Server has fulfilled a request for the resource with instance manipulations applied.

assert_http_300_multiple_choices(response=None, msg=None)

Request has multiple possible responses.

assert_http_301_moved_permanently(response=None, msg=None, url=None)

URL of requested resource has been changed permanently.

assert_http_302_found(response=None, msg=None, url=None)

Resource temporarily located at a different URI.

assert_http_303_see_other(response=None, msg=None)

Server redirects to get the requested resource at another URI.

assert_http_304_not_modified(response=None, msg=None)

Response has not been modified, client can use cached version.

assert_http_305_use_proxy(response=None, msg=None)

Response must be accessed through a proxy (deprecated).

assert_http_306_reserved(response=None, msg=None)

No longer used, reserved for future use.

assert_http_307_temporary_redirect(response=None, msg=None)

Resource temporarily located at a different URI, method must not change.

assert_http_308_permanent_redirect(response=None, msg=None)

Resource permanently located at a different URI, method must not change.

assert_http_400_bad_request(response=None, msg=None)

Server cannot process request due to client error.

assert_http_401_unauthorized(response=None, msg=None)

Request requires user authentication.

assert_http_402_payment_required(response=None, msg=None)

Reserved for future use in digital payment systems.

assert_http_403_forbidden(response=None, msg=None)

Server refuses to authorize the request.

assert_http_404_not_found(response=None, msg=None)

Server cannot find the requested resource.

assert_http_405_method_not_allowed(response=None, msg=None)

Request method not supported for the requested resource.

assert_http_406_not_acceptable(response=None, msg=None)

Server cannot produce a response matching the Accept headers.

assert_http_407_proxy_authentication_required(response=None, msg=None)

Client must authenticate with the proxy.

assert_http_408_request_timeout(response=None, msg=None)

Server timed out waiting for the request.

assert_http_409_conflict(response=None, msg=None)

Request conflicts with current state of the server.

assert_http_410_gone(response=None, msg=None)

Requested resource is permanently unavailable.

assert_http_411_length_required(response=None, msg=None)

Server requires Content-Length header in the request.

assert_http_412_precondition_failed(response=None, msg=None)

Client's preconditions in headers are not met.

assert_http_413_request_entity_too_large(response=None, msg=None)

Request payload is larger than server is willing to process.

assert_http_414_request_uri_too_long(response=None, msg=None)

URI requested by client is longer than server can interpret.

assert_http_415_unsupported_media_type(response=None, msg=None)

Media format of request data is not supported.

assert_http_416_requested_range_not_satisfiable(response=None, msg=None)

Range specified in Range header cannot be fulfilled.

assert_http_417_expectation_failed(response=None, msg=None)

Expectation in Expect header cannot be met.

assert_http_418_im_a_teapot(response=None, msg=None)

Server refuses to brew coffee because it is a teapot.

assert_http_421_misdirected_request(response=None, msg=None)

Request was directed to a server unable to produce a response.

assert_http_422_unprocessable_entity(response=None, msg=None)

Request is well-formed but contains semantic errors.

assert_http_423_locked(response=None, msg=None)

Resource being accessed is locked (WebDAV).

assert_http_424_failed_dependency(response=None, msg=None)

Request failed due to failure of a previous request (WebDAV).

assert_http_425_too_early(response=None, msg=None)

Server is unwilling to risk processing a request that might be replayed.

assert_http_426_upgrade_required(response=None, msg=None)

Client should switch to a different protocol.

assert_http_428_precondition_required(response=None, msg=None)

Server requires request to be conditional.

assert_http_429_too_many_requests(response=None, msg=None)

Client has sent too many requests in a given time period.

assert_http_431_request_header_fields_too_large(response=None, msg=None)

Request header fields are too large.

Resource is unavailable due to legal reasons.

assert_http_500_internal_server_error(response=None, msg=None)

Server encountered an unexpected condition.

assert_http_501_not_implemented(response=None, msg=None)

Server does not support the functionality required.

assert_http_502_bad_gateway(response=None, msg=None)

Server received an invalid response from upstream server.

assert_http_503_service_unavailable(response=None, msg=None)

Server is not ready to handle the request.

assert_http_504_gateway_timeout(response=None, msg=None)

Server did not receive timely response from upstream server.

assert_http_505_http_version_not_supported(response=None, msg=None)

HTTP version used in request is not supported by server.

assert_http_506_variant_also_negotiates(response=None, msg=None)

Server has an internal configuration error in content negotiation.

assert_http_507_insufficient_storage(response=None, msg=None)

Server is unable to store the representation needed to complete the request (WebDAV).

assert_http_508_loop_detected(response=None, msg=None)

Server detected an infinite loop while processing the request (WebDAV).

assert_http_509_bandwidth_limit_exceeded(response=None, msg=None)

Bandwidth limit has been exceeded (non-standard).

assert_http_510_not_extended(response=None, msg=None)

Further extensions to the request are required.

assert_http_511_network_authentication_required(response=None, msg=None)

Client needs to authenticate to gain network access.

test_plus.runner.NoLoggingRunner

Bases: DiscoverRunner

run_tests(test_labels, extra_tests=None, **kwargs)