Skip to main content

SimpleTestCase

This class provides a base for functional testing without database access, extending the standard unit testing framework with specialized assertions for web applications. It includes a built-in test client for simulating requests, utilities for validating templates and forms, and tools for comparing HTML, XML, and JSON content. Additionally, it enforces database isolation by preventing unauthorized database queries during test execution.

Attributes

AttributeTypeDescription
client_classclass = ClientThe class we'll use for the test client self.client.
async_client_classclass = AsyncClientThe class used to instantiate the asynchronous test client available as self.async_client.
databasesset or string = set()A set of database aliases that the test is allowed to access, or the string "all" to allow all.

Constructor

Signature

def SimpleTestCase(
methodName: str = "runTest"
)

Parameters

NameTypeDescription
methodNamestr = "runTest"The name of the specific test method to be executed.

Methods


setUpClass()

@classmethod
def setUpClass()

Initializes the test class by applying overridden settings, configuring database failure mocks, and registering cleanup tasks.


ensure_connection_patch_method()

@classmethod
def ensure_connection_patch_method() - > function

Returns a patched version of the database connection method that enforces database access restrictions for the test case.

Returns

TypeDescription
functionA wrapper function that checks database permissions before allowing a connection

debug()

@classmethod
def debug()

Perform the same as call(), without catching the exception.


settings()

@classmethod
def settings(
**kwargs: any
) - > contextmanager

A context manager that temporarily sets a setting and reverts to the original value when exiting the context.

Parameters

NameTypeDescription
**kwargsanySetting names and their temporary values

Returns

TypeDescription
contextmanagerA context manager for overriding Django settings

modify_settings()

@classmethod
def modify_settings(
**kwargs: any
) - > contextmanager

A context manager that temporarily applies changes to a list setting and reverts back to the original value when exiting the context.

Parameters

NameTypeDescription
**kwargsanySetting names and the modifications to apply

Returns

TypeDescription
contextmanagerA context manager for appending, prepending, or removing items from list-based settings

assertRedirects()

@classmethod
def assertRedirects(
response: [HttpResponse](../../http/response/httpresponse.md?sid=django_http_response_httpresponse),
expected_url: string,
status_code: integer,
target_status_code: integer,
msg_prefix: string,
fetch_redirect_response: boolean
)

Assert that a response redirected to a specific URL and that the redirect URL can be loaded.

Parameters

NameTypeDescription
response[HttpResponse](../../http/response/httpresponse.md?sid=django_http_response_httpresponse)The response object to check for redirection
expected_urlstringThe URL path the response is expected to redirect to
status_codeintegerThe expected HTTP status code of the redirect response (default 302)
target_status_codeintegerThe expected HTTP status code of the final destination URL (default 200)
msg_prefixstringA prefix to prepend to the failure message
fetch_redirect_responsebooleanWhether to use the test client to fetch the destination URL and verify its status code

assertURLEqual()

@classmethod
def assertURLEqual(
url1: string,
url2: string,
msg_prefix: string
)

Assert that two URLs are the same, ignoring the order of query string parameters except for parameters with the same name.

Parameters

NameTypeDescription
url1stringThe first URL to compare
url2stringThe second URL to compare
msg_prefixstringA prefix to prepend to the failure message

assertContains()

@classmethod
def assertContains(
response: [HttpResponse](../../http/response/httpresponse.md?sid=django_http_response_httpresponse),
text: string|bytes,
count: integer|null,
status_code: integer,
msg_prefix: string,
html: boolean
)

Assert that a response indicates that some content was retrieved successfully, (i.e., the HTTP status code was as expected) and that text occurs count times in the content of the response.

Parameters

NameTypeDescription
response[HttpResponse](../../http/response/httpresponse.md?sid=django_http_response_httpresponse)The response to check
text`stringbytes`
count`integernull`
status_codeintegerThe expected HTTP status code (default 200)
msg_prefixstringPrefix for the failure message
htmlbooleanIf true, performs a semantic HTML comparison instead of a literal string search

assertNotContains()

@classmethod
def assertNotContains(
response: [HttpResponse](../../http/response/httpresponse.md?sid=django_http_response_httpresponse),
text: string|bytes,
status_code: integer,
msg_prefix: string,
html: boolean
)

Assert that a response indicates that some content was retrieved successfully, (i.e., the HTTP status code was as expected) and that text doesn't occur in the content of the response.

Parameters

NameTypeDescription
response[HttpResponse](../../http/response/httpresponse.md?sid=django_http_response_httpresponse)The response to check
text`stringbytes`
status_codeintegerThe expected HTTP status code (default 200)
msg_prefixstringPrefix for the failure message
htmlbooleanIf true, performs a semantic HTML comparison

assertFormError()

@classmethod
def assertFormError(
form: [Form](../../forms/forms/form.md?sid=django_forms_forms_form),
field: string|null,
errors: string|list,
msg_prefix: string
)

Assert that a field named "field" on the given form object has specific errors.

Parameters

NameTypeDescription
form[Form](../../forms/forms/form.md?sid=django_forms_forms_form)The form instance to validate
field`stringnull`
errors`stringlist`
msg_prefixstringPrefix for the failure message

assertFormSetError()

@classmethod
def assertFormSetError(
formset: [BaseFormSet](../../forms/formsets/baseformset.md?sid=django_forms_formsets_baseformset),
form_index: integer|null,
field: string|null,
errors: string|list,
msg_prefix: string
)

Similar to assertFormError() but for formsets.

Parameters

NameTypeDescription
formset[BaseFormSet](../../forms/formsets/baseformset.md?sid=django_forms_formsets_baseformset)The formset instance to validate
form_index`integernull`
field`stringnull`
errors`stringlist`
msg_prefixstringPrefix for the failure message

assertTemplateUsed()

@classmethod
def assertTemplateUsed(
response: HttpResponse|null,
template_name: string|null,
msg_prefix: string,
count: integer|null
) - > contextmanager|null

Assert that the template with the provided name was used in rendering the response. Also usable as context manager.

Parameters

NameTypeDescription
response`HttpResponsenull`
template_name`stringnull`
msg_prefixstringPrefix for the failure message
count`integernull`

Returns

TypeDescription
`contextmanagernull`

assertTemplateNotUsed()

@classmethod
def assertTemplateNotUsed(
response: HttpResponse|null,
template_name: string|null,
msg_prefix: string
) - > contextmanager|null

Assert that the template with the provided name was NOT used in rendering the response. Also usable as context manager.

Parameters

NameTypeDescription
response`HttpResponsenull`
template_name`stringnull`
msg_prefixstringPrefix for the failure message

Returns

TypeDescription
`contextmanagernull`

assertRaisesMessage()

@classmethod
def assertRaisesMessage(
expected_exception: type,
expected_message: string,
*args: any,
**kwargs: any
) - > contextmanager|null

Assert that expected_message is found in the message of a raised exception.

Parameters

NameTypeDescription
expected_exceptiontypeException class expected to be raised.
expected_messagestringexpected error message string value.
*argsanyFunction to be called and extra positional args.
**kwargsanyExtra kwargs.

Returns

TypeDescription
`contextmanagernull`

assertWarnsMessage()

@classmethod
def assertWarnsMessage(
expected_warning: type,
expected_message: string,
*args: any,
**kwargs: any
) - > contextmanager|null

Same as assertRaisesMessage but for assertWarns() instead of assertRaises().

Parameters

NameTypeDescription
expected_warningtypeThe warning class expected to be triggered
expected_messagestringThe expected warning message string
*argsanyFunction to be called and extra positional args
**kwargsanyExtra kwargs

Returns

TypeDescription
`contextmanagernull`

assertFieldOutput()

@classmethod
def assertFieldOutput(
fieldclass: type,
valid: dict,
invalid: dict,
field_args: list|null,
field_kwargs: dict|null,
empty_value: any
)

Assert that a form field behaves correctly with various inputs.

Parameters

NameTypeDescription
fieldclasstypethe class of the field to be tested.
validdicta dictionary mapping valid inputs to their expected cleaned values.
invaliddicta dictionary mapping invalid inputs to one or more raised error messages.
field_args`listnull`
field_kwargs`dictnull`
empty_valueanythe expected clean output for inputs in empty_values

assertHTMLEqual()

@classmethod
def assertHTMLEqual(
html1: string,
html2: string,
msg: string|null
)

Assert that two HTML snippets are semantically the same. Whitespace in most cases is ignored, and attribute ordering is not significant. The arguments must be valid HTML.

Parameters

NameTypeDescription
html1stringThe first HTML snippet to compare
html2stringThe second HTML snippet to compare
msg`stringnull`

assertHTMLNotEqual()

@classmethod
def assertHTMLNotEqual(
html1: string,
html2: string,
msg: string|null
)

Assert that two HTML snippets are not semantically equivalent.

Parameters

NameTypeDescription
html1stringThe first HTML snippet
html2stringThe second HTML snippet
msg`stringnull`

assertInHTML()

@classmethod
def assertInHTML(
needle: string,
haystack: string,
count: integer|null,
msg_prefix: string
)

Asserts that a specific HTML fragment (needle) is present within a larger HTML string (haystack) a specific number of times.

Parameters

NameTypeDescription
needlestringThe HTML fragment to search for
haystackstringThe HTML content to search within
count`integernull`
msg_prefixstringPrefix for the failure message

assertNotInHTML()

@classmethod
def assertNotInHTML(
needle: string,
haystack: string,
msg_prefix: string
)

Asserts that a specific HTML fragment is not present within the provided HTML content.

Parameters

NameTypeDescription
needlestringThe HTML fragment that should be absent
haystackstringThe HTML content to search within
msg_prefixstringPrefix for the failure message

assertJSONEqual()

@classmethod
def assertJSONEqual(
raw: string,
expected_data: string|dict|list,
msg: string|null
)

Assert that the JSON fragments raw and expected_data are equal. Usual JSON non-significant whitespace rules apply as the heavyweight is delegated to the json library.

Parameters

NameTypeDescription
rawstringThe raw JSON string to validate
expected_data`stringdict
msg`stringnull`

assertJSONNotEqual()

@classmethod
def assertJSONNotEqual(
raw: string,
expected_data: string|dict|list,
msg: string|null
)

Assert that the JSON fragments raw and expected_data are not equal. Usual JSON non-significant whitespace rules apply as the heavyweight is delegated to the json library.

Parameters

NameTypeDescription
rawstringThe raw JSON string to validate
expected_data`stringdict
msg`stringnull`

assertXMLEqual()

@classmethod
def assertXMLEqual(
xml1: string,
xml2: string,
msg: string|null
)

Assert that two XML snippets are semantically the same. Whitespace in most cases is ignored and attribute ordering is not significant. The arguments must be valid XML.

Parameters

NameTypeDescription
xml1stringThe first XML snippet to compare
xml2stringThe second XML snippet to compare
msg`stringnull`

assertXMLNotEqual()

@classmethod
def assertXMLNotEqual(
xml1: string,
xml2: string,
msg: string|null
)

Assert that two XML snippets are not semantically equivalent. Whitespace in most cases is ignored and attribute ordering is not significant. The arguments must be valid XML.

Parameters

NameTypeDescription
xml1stringThe first XML snippet
xml2stringThe second XML snippet
msg`stringnull`