• Get Review Board
  • What's New
  • Products
  • Review Board Code review, image review, and document review
  • Documentation
  • Release Notes
  • Power Pack Enterprise integrations, reports, and enhanced document review
  • Try for 60 Days
  • Purchase
  • RBCommons Review Board as a Service, hosted by us
  • Pricing
  • RBTools Command line tools and Python API for Review Board
  • Documentation
  • Release Notes
  • Review Bot Automated code review, connecting tools you already use
  • Documentation
  • Release Notes
  • RB Gateway Manage Git and Mercurial repositories in your network
  • Documentation
  • Release Notes
  • Learn and Explore
  • What is Code Review?
  • Documentation
  • Frequently Asked Questions
  • Support Options
  • Third-Party Integrations
  • Demo
  • Review Board RBTools Power Pack Review Bot Djblets RB Gateway
    1. Djblets 5.x
    2. Version 5.x
    3. Version 4.x
    4. Version 3.x
    5. Version 2.x
    6. Version 2.0
    7. Version 1.0
    8. Version 0.9
    9. Djblets Documentation
    10. Module and Class References
    11. djblets.testing.testcases
  • Home
  • Guides
  • Avatar Services Guides
  • Writing Avatar Services
  • Extension Guides
  • Writing Extensions
  • Testing Extensions
  • Feature Checks Guides
  • Introduction to Feature Checks
  • Writing Features
  • Writing Feature Checkers
  • Testing with Feature Checks
  • Integration Guides
  • Supporting Integrations
  • Writing Integrations
  • Privacy Compliance Guides
  • Getting and Checking Consent
  • Working with Personally Identifiable Information
  • Service Integrations
  • reCAPTCHA Guides
  • Using reCAPTCHA
  • Registries Guides
  • Writing Registries
  • Web API Guides
  • Writing Web API Resources
  • Adding OAuth2 Support
  • Module and Class References
  • djblets
  • djblets.deprecation
  • djblets.auth.forms
  • djblets.auth.ratelimit
  • djblets.auth.signals
  • djblets.auth.util
  • djblets.auth.views
  • djblets.avatars.errors
  • djblets.avatars.forms
  • djblets.avatars.registry
  • djblets.avatars.services
  • djblets.avatars.services.base
  • djblets.avatars.services.fallback
  • djblets.avatars.services.file_upload
  • djblets.avatars.services.gravatar
  • djblets.avatars.services.url
  • djblets.avatars.settings
  • djblets.cache.backend
  • djblets.cache.backend_compat
  • djblets.cache.context_processors
  • djblets.cache.errors
  • djblets.cache.forwarding_backend
  • djblets.cache.serials
  • djblets.cache.synchronizer
  • djblets.conditions
  • djblets.conditions.choices
  • djblets.conditions.conditions
  • djblets.conditions.errors
  • djblets.conditions.operators
  • djblets.conditions.values
  • djblets.configforms.forms
  • djblets.configforms.mixins
  • djblets.configforms.pages
  • djblets.configforms.registry
  • djblets.configforms.views
  • djblets.datagrid.grids
  • djblets.db.backends.mysql.base
  • djblets.db.fields
  • djblets.db.fields.base64_field
  • djblets.db.fields.comma_separated_values_field
  • djblets.db.fields.counter_field
  • djblets.db.fields.json_field
  • djblets.db.fields.modification_timestamp_field
  • djblets.db.fields.relation_counter_field
  • djblets.db.managers
  • djblets.db.query
  • djblets.db.query_catcher
  • djblets.db.query_comparator
  • djblets.db.validators
  • djblets.extensions.admin
  • djblets.extensions.errors
  • djblets.extensions.extension
  • djblets.extensions.forms
  • djblets.extensions.hooks
  • djblets.extensions.loaders
  • djblets.extensions.manager
  • djblets.extensions.middleware
  • djblets.extensions.models
  • djblets.extensions.packaging
  • djblets.extensions.resources
  • djblets.extensions.settings
  • djblets.extensions.signals
  • djblets.extensions.staticfiles
  • djblets.extensions.testing
  • djblets.extensions.testing.testcases
  • djblets.extensions.urls
  • djblets.extensions.views
  • djblets.extensions.templatetags.djblets_extensions
  • djblets.features
  • djblets.features.checkers
  • djblets.features.decorators
  • djblets.features.errors
  • djblets.features.feature
  • djblets.features.level
  • djblets.features.registry
  • djblets.features.testing
  • djblets.features.templatetags.features
  • djblets.forms.fields
  • djblets.forms.fieldsets
  • djblets.forms.forms
  • djblets.forms.forms.key_value_form
  • djblets.forms.widgets
  • djblets.gravatars
  • djblets.gravatars.templatetags.gravatars
  • djblets.http.middleware
  • djblets.http.responses
  • djblets.integrations.errors
  • djblets.integrations.forms
  • djblets.integrations.hooks
  • djblets.integrations.integration
  • djblets.integrations.manager
  • djblets.integrations.mixins
  • djblets.integrations.models
  • djblets.integrations.urls
  • djblets.integrations.views
  • djblets.log
  • djblets.log.middleware
  • djblets.log.siteconfig
  • djblets.log.urls
  • djblets.log.views
  • djblets.mail.dmarc
  • djblets.mail.message
  • djblets.mail.testing
  • djblets.mail.utils
  • djblets.markdown
  • djblets.markdown.extensions.escape_html
  • djblets.markdown.extensions.wysiwyg
  • djblets.markdown.extensions.wysiwyg_email
  • djblets.pipeline.compilers.es6
  • djblets.pipeline.compilers.less
  • djblets.pipeline.compilers.mixins
  • djblets.pipeline.compilers.rollup
  • djblets.pipeline.compilers.typescript
  • djblets.pipeline.settings
  • djblets.privacy.consent
  • djblets.privacy.consent.base
  • djblets.privacy.consent.common
  • djblets.privacy.consent.errors
  • djblets.privacy.consent.forms
  • djblets.privacy.consent.hooks
  • djblets.privacy.consent.registry
  • djblets.privacy.consent.tracker
  • djblets.privacy.models
  • djblets.privacy.pii
  • djblets.privacy.templatetags.djblets_privacy
  • djblets.recaptcha.mixins
  • djblets.recaptcha.siteconfig
  • djblets.recaptcha.templatetags.djblets_recaptcha
  • djblets.recaptcha.widgets
  • djblets.registries
  • djblets.registries.errors
  • djblets.registries.importer
  • djblets.registries.mixins
  • djblets.registries.registry
  • djblets.registries.signals
  • djblets.secrets
  • djblets.secrets.crypto
  • djblets.secrets.token_generators
  • djblets.secrets.token_generators.base
  • djblets.secrets.token_generators.legacy_sha1
  • djblets.secrets.token_generators.registry
  • djblets.secrets.token_generators.vendor_checksum
  • djblets.siteconfig
  • djblets.siteconfig.admin
  • djblets.siteconfig.context_processors
  • djblets.siteconfig.django_settings
  • djblets.siteconfig.forms
  • djblets.siteconfig.managers
  • djblets.siteconfig.middleware
  • djblets.siteconfig.models
  • djblets.siteconfig.signals
  • djblets.siteconfig.views
  • djblets.template.caches
  • djblets.template.context
  • djblets.template.loaders.conditional_cached
  • djblets.template.loaders.namespaced_app_dirs
  • djblets.testing.decorators
  • djblets.testing.testcases
  • djblets.testing.testrunners
  • djblets.urls.context_processors
  • djblets.urls.decorators
  • djblets.urls.patterns
  • djblets.urls.resolvers
  • djblets.urls.root
  • djblets.urls.staticfiles
  • djblets.util.compat.django.core.cache
  • djblets.util.compat.python.past
  • djblets.util.contextmanagers
  • djblets.util.dates
  • djblets.util.decorators
  • djblets.util.filesystem
  • djblets.util.functional
  • djblets.util.html
  • djblets.util.http
  • djblets.util.humanize
  • djblets.util.json_utils
  • djblets.util.properties
  • djblets.util.serializers
  • djblets.util.symbols
  • djblets.util.templatetags.djblets_deco
  • djblets.util.templatetags.djblets_email
  • djblets.util.templatetags.djblets_forms
  • djblets.util.templatetags.djblets_images
  • djblets.util.templatetags.djblets_js
  • djblets.util.templatetags.djblets_utils
  • djblets.util.typing
  • djblets.util.views
  • djblets.views.generic.base
  • djblets.views.generic.etag
  • djblets.webapi.auth
  • djblets.webapi.auth.backends
  • djblets.webapi.auth.backends.api_tokens
  • djblets.webapi.auth.backends.base
  • djblets.webapi.auth.backends.basic
  • djblets.webapi.auth.backends.oauth2_tokens
  • djblets.webapi.auth.views
  • djblets.webapi.decorators
  • djblets.webapi.encoders
  • djblets.webapi.errors
  • djblets.webapi.fields
  • djblets.webapi.managers
  • djblets.webapi.models
  • djblets.webapi.oauth2_scopes
  • djblets.webapi.resources
  • djblets.webapi.resources.base
  • djblets.webapi.resources.group
  • djblets.webapi.resources.registry
  • djblets.webapi.resources.root
  • djblets.webapi.resources.user
  • djblets.webapi.resources.mixins.api_tokens
  • djblets.webapi.resources.mixins.forms
  • djblets.webapi.resources.mixins.oauth2_tokens
  • djblets.webapi.resources.mixins.queries
  • djblets.webapi.responses
  • djblets.webapi.signals
  • djblets.webapi.testing
  • djblets.webapi.testing.decorators
  • djblets.webapi.testing.testcases
  • General Index
  • Python Module Index
  • Release Notes
  • djblets.testing.testcases¶

    Base class for test cases in Django-based applications.

    class StubNodeList(default_text)[source]¶

    Bases: Node

    __init__(default_text)[source]¶
    render(context)[source]¶

    Return the node rendered as a string.

    __annotations__ = {}¶
    class StubParser(default_text)[source]¶

    Bases: object

    __init__(default_text)[source]¶
    parse(until)[source]¶
    delete_first_token()[source]¶
    class ExpectedWarning[source]¶

    Bases: TypedDict

    An expected warning from an assertion.

    This is used for TestCase.assertWarnings().

    New in version 3.2.

    cls: Type[Warning]¶

    The expected class for the warning.

    Type:

    type

    message: Optional[str]¶

    The expected message for the warning.

    If not provided, messages won’t be compared.

    Type:

    str

    __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')[source]¶

    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+')[source]¶
    __call__(*args, **kwargs)[source]¶

    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()[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: ~typing.Type[Warning] = <class 'DeprecationWarning'>, message: ~typing.Optional[str] = None) → Iterator[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.

      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][source]¶

    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 of dict, 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()[source]¶

    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][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 keys in ExpectedQuery.

    Changed in version 5.0:

    • Turned on check_subqueries and check_join_types by default.

    Changed in version 3.4:

    • Added with_tracebacks, tracebacks_size, check_join_types, and check_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 of ExpectedQuery) – 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.

    • 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[source]¶

    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[source]¶
    classmethod setUpClass()[source]¶
    classmethod tearDownClass()[source]¶
    class FixturesCompilerMixin[source]¶

    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')[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.

    __getattribute__(name)[source]¶

    Return getattr(self, name).

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

    Bases: TestCase

    Base testing setup for custom template tags

    setUp()[source]¶

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

    getContentText()[source]¶
    __annotations__ = {}¶
    class StoppableWSGIServer(*args, ipv6=False, allow_reuse_address=True, **kwargs)[source]¶

    Bases: WSGIServer

    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]¶

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

    Unicode control characters are replaced with escaped hex before writing the output to stderr.

    class TestServerThread(address, port)[source]¶

    Bases: Thread

    Thread for running a http server while tests are running.

    __init__(address, port)[source]¶

    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()[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.

    Keep up with the latest Review Board releases, security updates, and helpful information.

    About
    News
    Demo
    RBCommons Hosting
    Integrations
    Happy Users
    Support Options
    Documentation
    FAQ
    User Manual
    RBTools
    Administration Guide
    Power Pack
    Release Notes
    Downloads
    Review Board
    RBTools
    Djblets
    Power Pack
    Package Store
    PGP Signatures
    Contributing
    Bug Tracker
    Submit Patches
    Development Setup
    Wiki
    Follow Us
    Mailing Lists
    Reddit
    Twitter
    Mastodon
    Facebook
    YouTube

    Copyright © 2006-2025 Beanbag, Inc. All rights reserved.

    Terms of Service — Privacy Policy — AI Ethics Policy — Branding

    On this page

    • [Top]
    • StubNodeList
      • StubNodeList.__init__()
      • StubNodeList.render()
      • StubNodeList.__annotations__
    • StubParser
      • StubParser.__init__()
      • StubParser.parse()
      • StubParser.delete_first_token()
    • ExpectedWarning
      • ExpectedWarning.cls
      • ExpectedWarning.message
      • ExpectedWarning.__annotations__
      • ExpectedWarning.__closed__
      • ExpectedWarning.__extra_items__
      • ExpectedWarning.__mutable_keys__
      • ExpectedWarning.__optional_keys__
      • ExpectedWarning.__orig_bases__
      • ExpectedWarning.__readonly_keys__
      • ExpectedWarning.__required_keys__
      • ExpectedWarning.__total__
    • TestCase
      • TestCase.ws_re
      • TestCase.__call__()
      • TestCase.shortDescription()
      • TestCase.siteconfig_settings()
      • TestCase.assertAttrsEqual()
      • TestCase.assertRaisesValidationError()
      • TestCase.assertRaisesMessage()
      • TestCase.assertWarns()
      • TestCase.assertWarnings()
      • TestCase.assertNoWarnings()
      • TestCase.assertQueries()
    • TestModelsLoaderMixin
      • TestModelsLoaderMixin.tests_app
      • TestModelsLoaderMixin.setUpClass()
      • TestModelsLoaderMixin.tearDownClass()
    • FixturesCompilerMixin
      • FixturesCompilerMixin.load_fixtures()
      • FixturesCompilerMixin.__getattribute__()
    • TagTest
      • TagTest.setUp()
      • TagTest.getContentText()
      • TagTest.__annotations__
    • StoppableWSGIServer
      • StoppableWSGIServer.server_bind()
      • StoppableWSGIServer.get_request()
    • WSGIRequestHandler
      • WSGIRequestHandler.log_message()
    • TestServerThread
      • TestServerThread.__init__()
      • TestServerThread.run()
      • TestServerThread.join()