Testing
Flaxon provides comprehensive testing utilities including synchronous and asynchronous test clients, WebSocket testing, fixtures, and assertions.
Installation
pip install flaxon[dev]
Basic Test Client
from flaxon import Flaxon
from flaxon.testing import TestClient
def test_basic_route():
app = Flaxon("test-app")
@app.get("/")
async def home():
return {"message": "Hello"}
client = TestClient(app)
response = client.get("/")
assert response.status_code == 200
assert response.json() == {"message": "Hello"}
Async Test Client
import pytest
from flaxon.testing import AsyncTestClient
@pytest.mark.asyncio
async def test_async_route():
app = Flaxon("test-app")
@app.get("/")
async def home():
return {"message": "Hello"}
client = AsyncTestClient(app)
response = await client.get("/")
assert response.status_code == 200
assert response.json() == {"message": "Hello"}
Testing Request Body
def test_request_body():
app = Flaxon("test-app")
@app.post("/users")
async def create_user(request):
data = await request.json()
return {"received": data}
client = TestClient(app)
response = client.post("/users", json_data={"name": "Alice", "age": 30})
assert response.status_code == 200
assert response.json()["received"] == {"name": "Alice", "age": 30}
Testing WebSockets
import pytest
from flaxon.testing import AsyncWebSocketClient
@pytest.mark.asyncio
async def test_websocket():
app = Flaxon("test-app")
@app.websocket("/ws/echo")
async def echo(socket):
await socket.accept()
async for message in socket.iter_json():
await socket.send_json({"echo": message})
client = AsyncWebSocketClient(app)
await client.connect("/ws/echo")
await client.send_json({"message": "Hello"})
response = await client.receive_json()
assert response == {"echo": {"message": "Hello"}}
await client.disconnect()
Using Assertions
from flaxon.testing import Assertions
def test_assertions():
app = Flaxon("test-app")
@app.get("/users")
async def get_users():
return [{"id": 1, "name": "Alice"}]
client = TestClient(app)
response = client.get("/users")
Assertions.assert_status(response, 200)
data = Assertions.assert_json(response)
assert data[0]["name"] == "Alice"
Tip
Use pytest with pytest-asyncio for async tests.