Sanic Testing provides core testing utilities and clients for Sanic applications. This package externalizes the testing functionality previously integrated directly into the main Sanic framework. It is actively maintained, with releases typically aligning with the Sanic release cycle. The current version is 24.6.0.
pip install sanic-testingVerified import paths — ran on the pinned version, not inferred.
This quickstart demonstrates how to set up a Sanic application for testing with `sanic-testing` using `pytest`. It shows both the synchronous `app.test_client` and the asynchronous `app.asgi_client` for making requests against your Sanic application. Remember to install `pytest-asyncio` for async tests.
Install `sanic-testing` via `pip install sanic-testing` and update your import statements from `from sanic.testing import ...` to `from sanic_testing import TestManager`.
Upgrade your Python environment to 3.8 or newer. Consider using Python 3.10+ for optimal support.
When mocking `httpx` for outgoing requests in your Sanic application, ensure your mock selectively bypasses or handles calls made to the internal test server (e.g., `127.0.0.1`) to allow `sanic-testing`'s client to function correctly. A common pattern is to inspect the URL in your mock.
Initialize your Sanic apps with unique names (e.g., `Sanic(str(uuid.uuid4()))`). In `sanic-testing` (Sanic 21.3+), `TestManager` helps manage this. For older Sanic versions, setting `Sanic.test_mode = True` or the environment variable `SANIC_REGISTER=False` can also resolve the issue.
Review any tests that directly inspect the ASGI scope (`request.scope`) when using the `asgi_client` and adjust for the presence of `raw_path`.