djblets.testing.testcases¶
Base class for test cases in Django-based applications.
- class StubNodeList(default_text)¶
Bases:
Node
- __init__(default_text)¶
- render(context)¶
Return the node rendered as a string.
- __annotations__ = {}¶
- class StubParser(default_text)¶
Bases:
object
- __init__(default_text)¶
- parse(until)¶
- delete_first_token()¶
- class ExpectedWarning¶
Bases:
TypedDict
An expected warning from an assertion.
This is used for
TestCase.assertWarnings()
.New in version 3.2.
- message: Optional[str]¶
The expected message for the warning.
If not provided, messages won’t be compared.
- Type:
- __annotations__ = {'cls': ForwardRef('Type[Warning]', module='djblets.testing.testcases'), 'message': ForwardRef('NotRequired[Optional[str]]', module='djblets.testing.testcases')}¶
- __closed__ = False¶
- __extra_items__ = None¶
- __mutable_keys__ = frozenset({'cls', 'message'})¶
- __optional_keys__ = frozenset({})¶
- __orig_bases__ = (<function TypedDict>,)¶
- __readonly_keys__ = frozenset({})¶
- __required_keys__ = frozenset({'cls', 'message'})¶
- __total__ = True¶
- class TestCase(methodName='runTest')¶
Bases:
TestCase
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.- ws_re = re.compile('\\s+')¶
- __call__(*args, **kwargs)¶
Wrapper around default __call__ method to perform common Django test set up. This means that user-defined Test Cases aren’t required to include a call to super().setUp().
- shortDescription()¶
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)¶
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)¶
Assert that attributes on an object match expected values.
This will compare each attribute defined in
attrs
against the corresponding attribute onobj
. If the attribute value does not match, or the attribute is missing, this will assert.- Parameters:
- Raises:
AssertionError – An attribute was not found or the value did not match.
- assertRaisesValidationError(expected_messages, *args, **kwargs)¶
Assert that a ValidationError is raised with the given message(s).
This is a wrapper around
assertRaisesMessage()
with aValidationError
that handles converting the expected messages into a list (if it isn’t already) and then converting that into a string representation, which is whatassertRaisesMessage()
will be checking against.- Parameters:
expected_messages (
list
orunicode
) – 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)¶
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: ~typing.Type[Warning] = <class 'DeprecationWarning'>, message: ~typing.Optional[str] = None) Iterator[None] ¶
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.
If not provided, this defaults to a
DeprecationWarning
.message (
unicode
, optional) – The expected error message, if any.
- Context:
The test to run.
- assertWarnings(warning_list: List[ExpectedWarning]) Iterator[None] ¶
Assert that multiple warnings were generated.
This method accepts a sequence of warnings that must be matched in order. Each item must be an instance of a warning with a message. The type and messages of the warnings must match.
New in version 3.2.
- Parameters:
warning_list (
list
ofdict
, optional) –The list of expected warnings, in order.
Each item is a dictionary in the format described in
ExpectedWarning
.- Context:
The test to run.
- assertNoWarnings()¶
Assert that a warning is not generated.
- Context:
The test to run.
- assertQueries(queries: Sequence[Union[ExpectedQuery, Dict[str, Any]]], num_statements: Optional[int] = None, *, with_tracebacks: bool = False, traceback_size: int = 15, check_join_types: bool = True, check_subqueries: bool = True) Iterator[None] ¶
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 keys in
ExpectedQuery
.Changed in version 5.0:
Turned on
check_subqueries
andcheck_join_types
by default.
Changed in version 3.4:
Added
with_tracebacks
,tracebacks_size
,check_join_types
, andcheck_subqueries
arguments.Added support for type hints for expected queries.
Query output can now show notes (when populating
ExpectedQuery.__note__
) to ease debugging.The
where
queries are now normalized for easier comparison.The assertion output now shows the executed queries on the left-hand side and the expected queries on the right-hand side, like most other assertion functions.
The number of expected and executed queries no longer need to be exact in order to see results.
New in version 3.0.
- Parameters:
queries (
list
ofExpectedQuery
) – 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 inqueries
.with_tracebacks (
bool
, optional) –If enabled, tracebacks for queries will be included in results.
New in version 3.4.
tracebacks_size (
int
, optional) –The size of any tracebacks, in number of lines.
The default is 15.
New in version 3.4.
check_join_types (
bool
, optional) –Whether to check join types.
If enabled, table join types (
join_types
on queries) will be checked. This is currently disabled by default, in order to avoid breaking tests, but will be enabled by default in Djblets 5.New in version 3.4.
check_subqueries (
bool
, optional) –Whether to check subqueries.
If enabled,
inner_query
on queries with subqueries will be checked. This is currently disabled by default, in order to avoid breaking tests, but will be enabled by default in Djblets 5.New in version 3.4.
- Raises:
AssertionError – The parameters passed, or the queries compared, failed expectations.
- class TestModelsLoaderMixin¶
Bases:
object
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
.- tests_app = None¶
- classmethod setUpClass()¶
- classmethod tearDownClass()¶
- class FixturesCompilerMixin¶
Bases:
object
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')¶
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.
- __getattribute__(name)¶
Return getattr(self, name).
- class TagTest(methodName='runTest')¶
Bases:
TestCase
Base testing setup for custom template tags
- setUp()¶
Hook method for setting up the test fixture before exercising it.
- getContentText()¶
- __annotations__ = {}¶
- class StoppableWSGIServer(*args, ipv6=False, allow_reuse_address=True, **kwargs)¶
Bases:
WSGIServer
WSGIServer with short timeout, so that server thread can stop this server.
- server_bind()¶
Sets timeout to 1 second.
- get_request()¶
Checks for timeout when getting request.
- class WSGIRequestHandler(request, client_address, server)¶
Bases:
WSGIRequestHandler
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)¶
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.
Unicode control characters are replaced with escaped hex before writing the output to stderr.
- class TestServerThread(address, port)¶
Bases:
Thread
Thread for running a http server while tests are running.
- __init__(address, port)¶
This constructor should always be called with keyword arguments. Arguments are:
group should be None; reserved for future extension when a ThreadGroup class is implemented.
target is the callable object to be invoked by the run() method. Defaults to None, meaning nothing is called.
name is the thread name. By default, a unique name is constructed of the form “Thread-N” where N is a small decimal number.
args is a list or tuple of arguments for the target invocation. Defaults to ().
kwargs is a dictionary of keyword arguments for the target invocation. Defaults to {}.
If a subclass overrides the constructor, it must make sure to invoke the base class constructor (Thread.__init__()) before doing anything else to the thread.
- run()¶
Sets up test server and database and loops over handling http requests.
- join(timeout=None)¶
Stop the thread and wait for it to finish.