Testing tools#

Clients and helpers#

class dmr.test.DMRRequestFactory(*, json_encoder=<class 'django.core.serializers.json.DjangoJSONEncoder'>, headers=None, query_params=None, **defaults)[source]#

Test utility for testing apps using django-modern-rest.

Based on django.test.RequestFactory. See their docs for advanced usage: https://docs.djangoproject.com/en/dev/topics/testing/tools

This type, in contrast to a regular RequestFactory, sets content-type as application/json.

Sets WSGI environment.

class dmr.test.DMRAsyncRequestFactory(*, json_encoder=<class 'django.core.serializers.json.DjangoJSONEncoder'>, headers=None, query_params=None, **defaults)[source]#

Version of DMRRequestFactory but for ASGI environment.

Uses the exactly the same API.

wrap(thing)[source]#

Utility method for testing.

Pretends to wrap async controllers into async functions for typing. But in reality does nothing.

This happens due to the fact that View is typed as sync object.

class dmr.test.DMRClient(enforce_csrf_checks=False, raise_request_exception=True, *, headers=None, query_params=None, **defaults)[source]#

Test utility for testing apps using django-modern-rest.

Based on django.test.Client. See their docs for advanced usage: https://docs.djangoproject.com/en/dev/topics/testing/tools/

This type, in contrast to a regular Client, sets content-type as application/json.

class dmr.test.DMRAsyncClient(enforce_csrf_checks=False, raise_request_exception=True, *, headers=None, query_params=None, **defaults)[source]#

Async version of DMRClient.

Uses async API. Requires you to await calls to .get, .post, etc.

Auth#

dmr.test.disabled_auth(controller_cls: type[Controller[BaseSerializer]], *, request: HttpRequest, user: AbstractBaseUser, auth: SyncAuth | AsyncAuth | None = None) → Generator[None][source]#

Temporarily disable all auth for the endpoint for testing.

Parameters:
  • controller_cls – Controller whose endpoint is under test.

  • request – HTTP method of the endpoint to target.

  • user – User to be used for this request.

  • auth – Optional auth instance to be used for this request. It is set as __dmr_auth__ attribute, like our regular auth does. Use dmr.security.request_auth() to get it from request.

Added in version 0.13.0.

Throttling#

dmr.test.reduced_throttling(controller_cls: type[Controller[BaseSerializer]], *, method: HTTPMethod | str, max_requests: int = 2, rate: Rate = Rate.hour, when: Literal['any', 'before_auth', 'after_auth'] = 'any') → Generator[SyncThrottle | AsyncThrottle][source]#

Temporarily lower an endpoint’s first throttle so a test can reach it.

Replaces the first throttle of the chosen when with a copy limited to max_requests, so a few real requests trip it instead of the configured rate. Only the endpoint under test is affected; the original throttling is restored on exit. Yields the reduced throttle, whose max_requests tells you how many allowed requests to send before the next one is rejected.

The copy also has its window widened to rate, because lowering just max_requests is not enough for short windows: a 2/second throttle would reset between the driven requests and the endpoint would never be rejected. With an hour-long window every request a test sends lands inside the same window.

Parameters:
  • controller_cls – Controller whose endpoint is under test.

  • method – HTTP method of the endpoint to target.

  • max_requests – Limit the throttle is lowered to (2 by default). The window is always widened to one hour, see above.

  • rate – Time window to narrow to (hour by default).

  • when – When to run the throttle – 'before_auth' (checked before auth, e.g. by IP), 'after_auth' (per-user, needs an authenticated request), or 'any' (default, the first one checked).

Added in version 0.12.0.

dmr.test.assert_throttled(response: HttpResponse, *, throttle: SyncThrottle | AsyncThrottle | None = None) → None[source]#

Assert that a response was rejected by throttling.

Collapses the repeated 429 status, header and error-body checks into a single call:

# Just the status + `ratelimit` error:
assert_throttled(response)

# Also asserts all the headers from the throttle instance exist:
assert_throttled(response, throttle=your_throttled_instance)
Parameters:
  • response – The response to check.

  • throttle – Throttle that rejected the request. When given, every header its providers report must be present in the response.

throttle instance defines which headers are reported depends on the header provider’s class: XRateLimit, RateLimitIETFDraft, or your own provider.

Added in version 0.12.0.

dmr.test.assert_throttling(controller_cls: type[Controller[BaseSerializer]], request_factory: Callable[[], HttpRequest], *, max_requests: int = 2, rate: Rate = Rate.hour, when: Literal['any', 'before_auth', 'after_auth'] = 'any', success_status: HTTPStatus | None = None) → tuple[HttpResponse, SyncThrottle][source]#

Reduce the first throttle, drive requests, and assert the 429.

Sends max_requests allowed requests, then one that is rejected, and checks it with assert_throttled() – including every header the reduced throttle reports. Returns the 429 response, so you can make further assertions on it.

Parameters when and rate are passed down to reduced_throttling() and assert_throttled().

Added in version 0.12.0.

async dmr.test.assert_async_throttling(controller_cls: type[Controller[BaseSerializer]], request_factory: Callable[[], HttpRequest], *, max_requests: int = 2, rate: Rate = Rate.hour, when: Literal['any', 'before_auth', 'after_auth'] = 'any', success_status: HTTPStatus | None = None) → tuple[HttpResponse, AsyncThrottle][source]#

Async version of assert_throttling().

Added in version 0.12.0.

pytest plugin#

Clients:

dmr_pytest.dmr_client(request: FixtureRequest) → DMRClient[source]#

Customized version of django.test.Client.

dmr_pytest.dmr_async_client(request: FixtureRequest) → DMRAsyncClient[source]#

Customized version of django.test.AsyncClient.

Request factories:

dmr_pytest.dmr_rf() → DMRRequestFactory[source]#

Customized version of django.test.RequestFactory.

dmr_pytest.dmr_async_rf() → DMRAsyncRequestFactory[source]#

Customized version of django.test.AsyncRequestFactory.

Settings:

dmr_pytest.dmr_clean_settings() → Iterator[None][source]#

Cleans settings caches before and after the test.

This fixture shadows the default one from pytest-django:

dmr_pytest.settings(settings: LazySettings, dmr_clean_settings: None) → LazySettings[source]#

Customized version of pytest_django.fixtures.settings().