Sanic Testing

24.6.0 · active · verified Thu Apr 16

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.

Common errors

Warnings

Install

Imports

Quickstart

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.

import pytest
from sanic import Sanic, response
from sanic_testing import TestManager

@pytest.fixture
def app():
    sanic_app = Sanic("TestSanic")
    TestManager(sanic_app) # Attaches test clients to the app instance

    @sanic_app.get("/")
    async def basic(request):
        return response.text("foo")

    return sanic_app

def test_basic_sync_client(app):
    # Use the sync test client available via app.test_client
    request, response = app.test_client.get("/")
    assert request.method.lower() == "get"
    assert response.body == b"foo"
    assert response.status == 200

@pytest.mark.asyncio
async def test_basic_asgi_client(app):
    # Use the async ASGI client available via app.asgi_client
    request, response = await app.asgi_client.get("/")
    assert request.method.lower() == "get"
    assert response.body == b"foo"
    assert response.status == 200

view raw JSON →