Testing Reference¶
Module Summary¶
next.testing exposes a test client, signal recorder, registry isolation, action helpers, HTML utilities, rendering helpers, loaders, patching helpers, and dependency context builders.
Public API¶
Client¶
NextClient extends Django’s test client with form-action shortcuts for end to end HTTP tests.
HTTP test client extensions for next-dj.
- class next.testing.client.NextClient(enforce_csrf_checks=False, raise_request_exception=True, *, headers=None, query_params=None, **defaults)[source]¶
Django test client with next-dj form-action shortcuts.
post_action resolves an action name to its URL and POSTs data in a single call. get_action_url returns the URL without dispatching so tests can assert on structure before hitting the view.
Signals¶
SignalRecorder and the capture_signals wrappers capture framework signal payloads inside a context manager.
Signal capture utility for tests.
SignalRecorder is a context manager that connects to one or more Django signals, stores every emission as a SignalEvent, and disconnects on exit. It works with plain Django TestCase, the stdlib unittest.TestCase, and pytest without any framework-specific code.
- class next.testing.signals.SignalEvent(signal: Signal, sender: Any, kwargs: dict[str, Any])[source]¶
Single captured emission of a Django signal.
- signal: Signal¶
- sender: Any¶
- class next.testing.signals.SignalRecorder(*signals: Signal)[source]¶
Record every emission of the given signals until stop is called.
Use as a context manager for scoped capture or call start and stop explicitly when the lifecycle spans multiple helpers.
- events: list[SignalEvent]¶
- __exit__(exc_type: type[BaseException] | None, exc: BaseException | None, tb: TracebackType | None) None[source]¶
Stop recording on context exit.
- __iter__() Iterator[SignalEvent][source]¶
Iterate over captured events in emission order.
- events_for(signal: Signal) list[SignalEvent][source]¶
Return every captured event emitted by the given signal.
- first_for(signal: Signal) SignalEvent[source]¶
Return the first captured event for signal or raise LookupError.
- last_for(signal: Signal) SignalEvent[source]¶
Return the last captured event for signal or raise LookupError.
- next.testing.signals.capture_framework_signals() SignalRecorder[source]¶
Return a recorder connected to every signal in next.signals.__all__.
Handy when a test wants to verify that nothing unexpected fires without wiring each signal by hand.
- next.testing.signals.capture_signals(*signals: Signal) SignalRecorder[source]¶
Return a started SignalRecorder for use as a context manager.
Equivalent to SignalRecorder(*signals).start() but reads like a verb at the call site: with capture_signals(sig) as rec: ….
Isolation¶
reset_registries and its narrower variants clear the framework registries between tests.
Helpers to drop registry state between tests.
Most Django tests expect module-level registrations to persist. These helpers are opt-in and intended for tests that explicitly verify registry behaviour or need to reload backends after swapping settings.
- next.testing.isolation.reset_components() None[source]¶
Drop cached component backends so the next render reloads them.
- next.testing.isolation.reset_form_actions() None[source]¶
Drop cached form-action backends and reload them from settings.
Forms register imperatively at import time, so the manager does not auto-rebuild on settings_reloaded. Tests that swap NEXT_FRAMEWORK[“DEFAULT_FORM_ACTION_BACKENDS”] call this helper to discard the stale backend list and pick the new one up on next use.
Actions¶
resolve_action_url and build_form_for exercise a registered action without crafting POST bodies.
Public helpers for working with form actions in tests.
- next.testing.actions.build_form_for(action_name: str, data: dict[str, Any] | None = None, **form_kwargs: Any) django_forms.Form[source]¶
Instantiate the form class registered for action_name.
Useful for unit-testing form validation without dispatching an HTTP request. Raises KeyError when the action is unknown and LookupError when the action is registered without a form class.
Rendering¶
render_page and render_component_by_name render a single page or component without an HTTP round trip.
Render helpers for next-dj pages and components.
Thin wrappers over page.render and render_component so tests do not need to construct ComponentInfo manually or build an HttpRequest just to exercise a renderer.
- next.testing.rendering.render_component_by_name(name: str, *, at: Path | str, context: Mapping[str, Any] | None = None, request: HttpRequest | None = None) str[source]¶
Resolve component name as seen from at and render it.
at is the template path the component is referenced from. It is used for visibility/scoping by components_manager.get_component. Raises LookupError when no matching visible component is found.
- next.testing.rendering.render_page(file_path: Path | str, request: HttpRequest | None = None, /, **url_kwargs: Any) str[source]¶
Render the page at file_path and return its HTML string.
When request is not provided a minimal HttpRequest is built via RequestFactory().get(“/”). Extra url_kwargs are forwarded to page.render so tests can exercise parametric pages.
Loaders¶
eager_load_components, eager_load_pages, and clear_loaded_dirs force-import or reset the per-directory memoisation of page.py and component.py modules in tests.
Eager page-module loader used in tests.
eager_load_pages walks a pages directory and imports every page.py file so that @context and @forms.action side effects register before a test dispatches HTTP requests. Results are memoised per absolute directory so repeated calls during a pytest session are cheap.
- next.testing.loaders.clear_loaded_dirs() None[source]¶
Drop the memoisation cache so the next call reloads page modules.
Intended for self-tests of the loader. Production test suites do not need to call this because each pytest session gets a fresh interpreter.
- next.testing.loaders.eager_load_components() None[source]¶
Import every registered component.py so decorators register before tests.
- next.testing.loaders.eager_load_pages(base_dir: Path | str) list[Path][source]¶
Import every page.py under base_dir and return loaded paths.
The call is idempotent for the same absolute directory. Non-existent paths raise FileNotFoundError. Importer errors bubble up so that broken page modules fail loudly in test setup rather than producing confusing 404 responses later.
HTML Utilities¶
find_anchor, assert_has_class, and assert_missing_class inspect rendered HTML fragments.
HTML helpers for next-dj tests.
Thin conveniences for the narrow cases that Django’s built-in assertions (assertContains(html=True), assertInHTML, …) do not cover cleanly: picking a specific anchor out of a rendered page and checking class-token membership without regex or BeautifulSoup.
These helpers operate on HTML produced by Django template rendering; they do not try to be a general HTML parser.
- next.testing.html.assert_has_class(fragment: str, token: str) None[source]¶
Raise AssertionError unless the tag’s class attribute has token.
token is matched against whitespace-separated class tokens.
- next.testing.html.assert_missing_class(fragment: str, token: str) None[source]¶
Raise AssertionError when the tag’s class attribute has token.
- next.testing.html.find_anchor(html: str, *, href: str | None = None, text: str | None = None) str[source]¶
Return the first <a>…</a> substring that matches the filters.
href is compared for exact equality with the anchor’s href attribute. text is matched as a substring against the anchor’s stripped inner text. With no filters, returns the first anchor in document order. Raises LookupError when nothing matches.
Patching¶
The override_* context managers and patch_static_collector swap framework wiring for the duration of a block.
Context managers for test-scoped overrides.
Each helper is a plain @contextlib.contextmanager so the public surface does not depend on pytest or unittest.mock. State is restored on exit, including when the block raises.
- class next.testing.patching.StaticCollectorProxy[source]¶
Handle that exposes the collector most recently built inside a patch.
- next.testing.patching.override_component_backends(*configs: dict[str, Any]) Iterator[None][source]¶
Replace DEFAULT_COMPONENT_BACKENDS for the block.
Uses override_next_settings so the settings_reloaded signal rebuilds components_manager’s backends automatically.
- next.testing.patching.override_dependency(name: str, value: Any) Iterator[None][source]¶
Bind Depends(name) to value for the block.
Any previous dependency registered under name is restored on exit.
- next.testing.patching.override_form_action(name: str, handler: Callable[..., Any], *, form_class: Any = None) Iterator[None][source]¶
Register handler as the named form action for the block.
The full action registry is snapshotted on entry and restored on exit, so previously registered actions with the same name survive.
- next.testing.patching.override_next_settings(**overrides: Any) Iterator[None][source]¶
Merge overrides into NEXT_FRAMEWORK for the duration of the block.
The merge is shallow: top-level keys supplied as kwargs replace any values present in the current NEXT_FRAMEWORK. Relies on Django’s override_settings underneath, so the setting_changed → settings_reloaded signal chain fires automatically and framework managers pick up the new values.
- next.testing.patching.override_provider(provider: ParameterProvider) Iterator[None][source]¶
Prepend provider to the resolver’s provider list for the block.
Placing the provider first means it wins over any auto-registered provider that would otherwise handle the same parameter.
- next.testing.patching.patch_static_collector(factory: Callable[[], StaticCollector] | None = None, *, capture: bool = False) Iterator[StaticCollectorProxy | None][source]¶
Replace default_manager.create_collector for the block.
When capture is True a StaticCollectorProxy is yielded. Its .collector attribute is set on each call to the patched factory so tests can inspect emitted styles/scripts without parsing HTML.
Dependencies¶
make_resolution_context and resolve_call build dependency-injection test doubles for provider unit tests.
Dependency-injection helpers for tests.
Unit-testing a next-dj provider or a DI-aware callable usually means building a ResolutionContext with sensible defaults and delegating to the module-level resolver. These helpers wrap that ritual.
- next.testing.deps.make_resolution_context(*, request: HttpRequest | None = None, form: object | None = None, url_kwargs: Mapping[str, Any] | None = None, context_data: Mapping[str, Any] | None = None) ResolutionContext[source]¶
Construct a ResolutionContext with empty defaults.
A fresh DependencyCache is created on every call so tests do not share memoised values by accident.
- next.testing.deps.resolve_call(func: Callable[..., Any], *, request: HttpRequest | None = None, form: object | None = None, url_kwargs: Mapping[str, Any] | None = None, context_data: Mapping[str, Any] | None = None) dict[str, Any][source]¶
Resolve the dependencies of func and return the kwargs mapping.
Thin wrapper over DependencyResolver.resolve that accepts the same loose keyword arguments as make_resolution_context.
See Also¶
See also
Testing for the topic guide. Test a Page With Actions for a recipe.