Jump to >

This documentation covers the in-development release of Djblets. You can see the latest stable docs or all previous versions.

djblets.testing.testcases

Base class for test cases in Django-based applications.

class TestCase(methodName='runTest')[source]

Base class for test cases.

Individual tests on this TestCase can use the add_fixtures() decorator to add or replace the fixtures used for the test.

shortDescription()[source]

Returns the description of the current test.

This changes the default behavior to replace all newlines with spaces, allowing a test description to span lines. It should still be kept short, though.

siteconfig_settings(settings)[source]

Temporarily sets siteconfig settings for a test.

Subclasses should override this if they want to run a method like apply_django_settings() before and after each test.

Parameters

settings (dict) – The new siteconfig settings to set.

Context

The current site configuration will contain the new settings for this test.

assertAttrsEqual(obj, attrs, msg=None)[source]

Assert that attributes on an object match expected values.

This will compare each attribute defined in attrs against the corresponding attribute on obj. If the attribute value does not match, or the attribute is missing, this will assert.

Parameters
  • obj (object) – The object to compare attribute values to.

  • attrs (dict) – A dictionary of expected attribute names and values.

  • msg (unicode, optional) – A custom message to include if there’s a failure.

Raises

AssertionError – An attribute was not found or the value did not match.

assertRaisesValidationError(expected_messages, *args, **kwargs)[source]

Assert that a ValidationError is raised with the given message(s).

This is a wrapper around assertRaisesMessage() with a ValidationError that handles converting the expected messages into a list (if it isn’t already) and then converting that into a string representation, which is what assertRaisesMessage() will be checking against.

Parameters
  • expected_messages (list or unicode) – The expected messages as either a list of strings or a single string.

  • args – Additional arguments to pass to assertRaisesMessage().

  • kwargs – Additional keyword arguments to pass to assertRaisesMessage().

assertRaisesMessage(expected_exception, expected_message, *args, **kwargs)[source]

Assert that an exception is raised with a given message.

This is a replacement for Django’s assertRaisesMessage that behaves well with a design change in Python 2.7.9/10, without crashing.

assertWarns(cls=<class 'DeprecationWarning'>, message=None)[source]

Assert that a warning is generated with a given message.

This method only supports code which generates a single warning. Tests which make use of code generating multiple warnings will need to manually catch their warnings.

Parameters
  • cls (type, optional) – The expected warning type.

  • message (unicode, optional) – The expected error message, if any.

Context

The test to run.

assertNoWarnings()[source]

Assert that a warning is not generated.

Context

The test to run.

assertQueries(queries, num_statements=None)[source]

Assert the number and complexity of queries.

This provides advanced checking of queries, allowing the caller to match filtering, JOINs, ordering, selected fields, and more.

This takes a list of dictionaries with query information. Each contains the following:

Keys:
model (type):

The model representing the results that would be returned or altered by the query.

annotations (dict, optional):

A dictionary containing applied annotations.

Keys are destination attribute names, and values are the annotation instances.

The default is empty.

distinct (bool, optional):

Whether django.db.models.query.QuerySet.distinct() was used.

The default is False.

distinct_fields (tuple of str, optional):

A list of fields passed to django.db.models.query.QuerySet.distinct().

The default is empty.

extra (dict, optional):

State passed in calls to django.db.models.query.QuerySet.extra() when using select and select_params.

Each key maps to a key in select, and each value is a tuple containing the value in select and the corresponding value (if any) in select_params.

The default is empty.

extra_order_by (list of str, optional):

State passed in calls to django.db.models.query.QuerySet.extra() when using order_by.

The default is empty.

extra_tables (list of str, optional):

State passed in calls to django.db.models.query.QuerySet.extra() when using tables.

The default is empty.

group_by (bool or tuple, optional):

Whether no fields will be grouped (None), all fields will be grouped (True), or specific expressions/field names are grouped (a tuple).

This is influenced by using django.db.models.query.QuerySet.annotate().

The default is None.

num_joins (int, optional):

The number of tables JOINed.

The default is 0.

only_fields (set of str, optional);

The specific fields being fetched, or None if fetching all fields.

The default is None.

order_by (tuple of str, optional):

The ordering criteria.

The default is empty.

select_related (set of str, optional):

The table names involved in a django.db.models.query.QuerySet.select_related().

subquery (bool, optional):

Whether this is considered a subquery of another query.

The default is False.

tables (set of str, optional):

The tables involved in the query.

The default is the model’s table name.

type (str, optional):

The query type. This would be one of DELETE, INSERT, SELECT, or UPDATE.

The default is SELECT.

where (django.db.models.Q, optional):

The query expression objects used to represent the filter on the query.

New in version 3.0.

Parameters
  • queries (list of dict) – The list of query dictionaries to compare executed queries against.

  • num_statements (int, optional) –

    The numbre of SQL statements executed.

    This defaults to the length of queries, but callers may need to provide an explicit number, as some operations may add additional database-specific statements (such as transaction-related SQL) that won’t be covered in queries.

Raises

AssertionError – The parameters passed, or the queries compared, failed expectations.

class TestModelsLoaderMixin[source]

Allows unit test modules to provide models to test against.

This allows a unit test file to provide models that will be synced to the database and flushed after tests. These can be tested against in any unit tests.

Typically, Django requires any test directories to be pre-added to INSTALLED_APPS in order for models to be created in the test database.

This mixin works around this by dynamically adding the module to INSTALLED_APPS and forcing the database to be synced. It also will generate a fake ‘models’ module to satisfy Django’s requirement, if one doesn’t already exist.

By default, this will assume that the test class’s module is the one that should be added to INSTALLED_APPS. This can be changed by overriding tests_app.

class FixturesCompilerMixin[source]

Compiles and efficiently loads fixtures into a test suite.

Unlike Django’s standard fixture support, this doesn’t re-discover and re-deserialize the referenced fixtures every time they’re needed. Instead, it precompiles the fixtures the first time they’re found and reuses their objects for future tests.

However, also unlike Django’s, this does not accept compressed or non-JSON fixtures.

load_fixtures(fixtures, db='default')[source]

Load fixtures for the current test.

This is called for every fixture in the test case’s fixtures list. It can also be called by an individual test to add additional fixtures on top of that.

Parameters
  • fixtures (list of unicode) – The list of fixtures to load.

  • db (unicode) – The database name to load fixture data on.

class TagTest(methodName='runTest')[source]

Base testing setup for custom template tags

setUp()[source]

Hook method for setting up the test fixture before exercising it.

class StoppableWSGIServer(*args, ipv6=False, allow_reuse_address=True, **kwargs)[source]

WSGIServer with short timeout, so that server thread can stop this server.

server_bind()[source]

Sets timeout to 1 second.

get_request()[source]

Checks for timeout when getting request.

class WSGIRequestHandler(request, client_address, server)[source]

A custom WSGIRequestHandler that logs all output to stdout.

Normally, WSGIRequestHandler will color-code messages and log them to stderr. It also filters out admin and favicon.ico requests. We don’t need any of this, and certainly don’t want it in stderr, as we’d like to only show it on failure.

log_message(format, *args)[source]

Log an arbitrary message.

This is used by all other logging functions. Override it if you have specific logging wishes.

The first argument, FORMAT, is a format string for the message to be logged. If the format string contains any % escapes requiring parameters, they should be specified as subsequent arguments (it’s just like printf!).

The client ip and current date/time are prefixed to every message.

class TestServerThread(address, port)[source]

Thread for running a http server while tests are running.

run()[source]

Sets up test server and database and loops over handling http requests.

join(timeout=None)[source]

Stop the thread and wait for it to finish.