| 1 |
Testing |
| 2 |
======= |
| 3 |
|
| 4 |
Testing is a first class citizen in Litestar, which offers several powerful testing utilities out of the box. |
| 5 |
|
| 6 |
|
| 7 |
Test Client |
| 8 |
----------- |
| 9 |
|
| 10 |
Litestar's test client is built on top of |
| 11 |
the `httpx <https://github.com/encode/httpx>`_ library. To use the test client you should pass to it an |
| 12 |
instance of Litestar as the ``app`` kwarg. |
| 13 |
|
| 14 |
Let's say we have a very simple app with a health check endpoint: |
| 15 |
|
| 16 |
.. code-block:: python |
| 17 |
:caption: ``my_app/main.py`` |
| 18 |
|
| 19 |
from litestar import Litestar, MediaType, get |
| 20 |
|
| 21 |
|
| 22 |
@get(path="/health-check", media_type=MediaType.TEXT) |
| 23 |
def health_check() -> str: |
| 24 |
return "healthy" |
| 25 |
|
| 26 |
|
| 27 |
app = Litestar(route_handlers=[health_check]) |
| 28 |
|
| 29 |
|
| 30 |
We would then test it using the test client like so: |
| 31 |
|
| 32 |
.. tab-set:: |
| 33 |
|
| 34 |
.. tab-item:: Sync |
| 35 |
:sync: sync |
| 36 |
|
| 37 |
.. code-block:: python |
| 38 |
:caption: ``tests/test_health_check.py`` |
| 39 |
|
| 40 |
from litestar.status_codes import HTTP_200_OK |
| 41 |
from litestar.testing import TestClient |
| 42 |
|
| 43 |
from my_app.main import app |
| 44 |
|
| 45 |
app.debug = True |
| 46 |
|
| 47 |
|
| 48 |
def test_health_check(): |
| 49 |
with TestClient(app=app) as client: |
| 50 |
response = client.get("/health-check") |
| 51 |
assert response.status_code == HTTP_200_OK |
| 52 |
assert response.text == "healthy" |
| 53 |
|
| 54 |
.. tab-item:: Async |
| 55 |
:sync: async |
| 56 |
|
| 57 |
.. code-block:: python |
| 58 |
:caption: ``tests/test_health_check.py`` |
| 59 |
|
| 60 |
from litestar.status_codes import HTTP_200_OK |
| 61 |
from litestar.testing import AsyncTestClient |
| 62 |
|
| 63 |
from my_app.main import app |
| 64 |
|
| 65 |
app.debug = True |
| 66 |
|
| 67 |
|
| 68 |
async def test_health_check(): |
| 69 |
async with AsyncTestClient(app=app) as client: |
| 70 |
response = await client.get("/health-check") |
| 71 |
assert response.status_code == HTTP_200_OK |
| 72 |
assert response.text == "healthy" |
| 73 |
|
| 74 |
|
| 75 |
Since we would probably need to use the client in multiple places, it's better to make it into a pytest fixture: |
| 76 |
|
| 77 |
|
| 78 |
.. tab-set:: |
| 79 |
|
| 80 |
.. tab-item:: Sync |
| 81 |
:sync: sync |
| 82 |
|
| 83 |
.. code-block:: python |
| 84 |
:caption: ``tests/conftest.py`` |
| 85 |
|
| 86 |
from typing import TYPE_CHECKING, Iterator |
| 87 |
|
| 88 |
import pytest |
| 89 |
|
| 90 |
from litestar.testing import TestClient |
| 91 |
|
| 92 |
from my_app.main import app |
| 93 |
|
| 94 |
if TYPE_CHECKING: |
| 95 |
from litestar import Litestar |
| 96 |
|
| 97 |
app.debug = True |
| 98 |
|
| 99 |
|
| 100 |
@pytest.fixture(scope="function") |
| 101 |
def test_client() -> Iterator[TestClient[Litestar]]: |
| 102 |
with TestClient(app=app) as client: |
| 103 |
yield client |
| 104 |
|
| 105 |
|
| 106 |
.. tab-item:: Async |
| 107 |
:sync: async |
| 108 |
|
| 109 |
.. code-block:: python |
| 110 |
:caption: ``tests/conftest.py`` |
| 111 |
|
| 112 |
from typing import TYPE_CHECKING, AsyncIterator |
| 113 |
|
| 114 |
import pytest |
| 115 |
|
| 116 |
from litestar.testing import AsyncTestClient |
| 117 |
|
| 118 |
from my_app.main import app |
| 119 |
|
| 120 |
if TYPE_CHECKING: |
| 121 |
from litestar import Litestar |
| 122 |
|
| 123 |
app.debug = True |
| 124 |
|
| 125 |
|
| 126 |
@pytest.fixture(scope="function") |
| 127 |
async def test_client() -> AsyncIterator[AsyncTestClient[Litestar]]: |
| 128 |
async with AsyncTestClient(app=app) as client: |
| 129 |
yield client |
| 130 |
|
| 131 |
|
| 132 |
We would then be able to rewrite our test like so: |
| 133 |
|
| 134 |
.. tab-set:: |
| 135 |
|
| 136 |
.. tab-item:: Sync |
| 137 |
:sync: sync |
| 138 |
|
| 139 |
.. literalinclude:: /examples/testing/test_health_check_sync.py |
| 140 |
:caption: ``tests/test_health_check.py`` |
| 141 |
:language: python |
| 142 |
|
| 143 |
|
| 144 |
.. tab-item:: Async |
| 145 |
:sync: async |
| 146 |
|
| 147 |
.. literalinclude:: /examples/testing/test_health_check_async.py |
| 148 |
:caption: ``tests/test_health_check.py`` |
| 149 |
:language: python |
| 150 |
|
| 151 |
Testing websockets |
| 152 |
++++++++++++++++++ |
| 153 |
|
| 154 |
Litestar's test client enhances the httpx client to support websockets. To test a websocket endpoint, you can use the :meth:`websocket_connect <litestar.testing.TestClient.websocket_connect>` |
| 155 |
method on the test client. The method returns a websocket connection object that you can use to send and receive messages, see an example below for json: |
| 156 |
|
| 157 |
For more information, see also the :class:`WebSocket <litestar.connection.WebSocket>` class in the API documentation and the :ref:`websocket <usage/websockets:websockets>` documentation. |
| 158 |
|
| 159 |
.. literalinclude:: /examples/testing/test_websocket.py |
| 160 |
:language: python |
| 161 |
|
| 162 |
|
| 163 |
Using sessions |
| 164 |
++++++++++++++ |
| 165 |
|
| 166 |
If you are using :ref:`session middleware <usage/middleware/builtin-middleware:session middleware>` for session persistence |
| 167 |
across requests, then you might want to inject or inspect session data outside a request. For this, |
| 168 |
:class:`TestClient <.testing.TestClient>` provides two methods: |
| 169 |
|
| 170 |
* :meth:`set_session_data <litestar.testing.TestClient.set_session_data>` |
| 171 |
* :meth:`get_session_data <litestar.testing.TestClient.get_session_data>` |
| 172 |
|
| 173 |
.. attention:: |
| 174 |
|
| 175 |
- The Session Middleware must be enabled in Litestar app provided to the TestClient to use sessions. |
| 176 |
- If you are using the |
| 177 |
:class:`ClientSideSessionBackend <litestar.middleware.session.client_side.ClientSideSessionBackend>` you need to |
| 178 |
install the ``cryptography`` package. You can do so by installing ``litestar``: |
| 179 |
|
| 180 |
.. tab-set:: |
| 181 |
|
| 182 |
.. tab-item:: pip |
| 183 |
|
| 184 |
.. code-block:: bash |
| 185 |
:caption: Using pip |
| 186 |
|
| 187 |
python3 -m pip install 'litestar[cryptography]' |
| 188 |
|
| 189 |
.. tab-item:: pipx |
| 190 |
|
| 191 |
.. code-block:: bash |
| 192 |
:caption: Using `pipx <https://pypa.github.io/pipx/>`_ |
| 193 |
|
| 194 |
pipx install 'litestar[cryptography]' |
| 195 |
|
| 196 |
.. tab-item:: pdm |
| 197 |
|
| 198 |
.. code-block:: bash |
| 199 |
:caption: Using `PDM <https://pdm.fming.dev/>`_ |
| 200 |
|
| 201 |
pdm add 'litestar[cryptography]' |
| 202 |
|
| 203 |
.. tab-item:: poetry |
| 204 |
|
| 205 |
.. code-block:: bash |
| 206 |
:caption: Using `poetry <https://python-poetry.org/>`_ |
| 207 |
|
| 208 |
poetry add 'litestar[cryptography]' |
| 209 |
|
| 210 |
.. tab-item:: uv |
| 211 |
|
| 212 |
.. code-block:: bash |
| 213 |
:caption: Using `uv <https://docs.astral.sh/uv/>`_ |
| 214 |
|
| 215 |
uv add 'litestar[cryptography]' |
| 216 |
|
| 217 |
.. tab-set:: |
| 218 |
|
| 219 |
.. tab-item:: Sync |
| 220 |
:sync: sync |
| 221 |
|
| 222 |
.. literalinclude:: /examples/testing/test_set_session_data.py |
| 223 |
:caption: Setting session data |
| 224 |
:language: python |
| 225 |
|
| 226 |
|
| 227 |
.. literalinclude:: /examples/testing/test_get_session_data.py |
| 228 |
:caption: Getting session data |
| 229 |
:language: python |
| 230 |
|
| 231 |
.. tab-item:: Async |
| 232 |
:sync: async |
| 233 |
|
| 234 |
.. literalinclude:: /examples/testing/test_set_session_data_async.py |
| 235 |
:caption: Setting session data |
| 236 |
:language: python |
| 237 |
|
| 238 |
|
| 239 |
.. literalinclude:: /examples/testing/test_get_session_data_async.py |
| 240 |
:caption: Getting session data |
| 241 |
:language: python |
| 242 |
|
| 243 |
|
| 244 |
Using a blocking portal |
| 245 |
+++++++++++++++++++++++ |
| 246 |
|
| 247 |
The :class:`TestClient <.testing.TestClient>` uses a feature of `anyio <https://anyio.readthedocs.io/en/stable/>`_ called |
| 248 |
a **Blocking Portal**. |
| 249 |
|
| 250 |
The :class:`anyio.abc.BlockingPortal` allows :class:`TestClient <.testing.TestClient>` |
| 251 |
to execute asynchronous functions using a synchronous call. ``TestClient`` creates a blocking portal to manage |
| 252 |
``Litestar``'s async logic, and it allows ``TestClient``'s API to remain fully synchronous. |
| 253 |
|
| 254 |
Any tests that are using an instance of ``TestClient`` can also make use of the blocking portal to execute asynchronous functions |
| 255 |
without the test itself being asynchronous. |
| 256 |
|
| 257 |
.. literalinclude:: /examples/testing/test_with_portal.py |
| 258 |
:caption: Using a blocking portal |
| 259 |
:language: python |
| 260 |
|
| 261 |
|
| 262 |
Creating a test app |
| 263 |
------------------- |
| 264 |
|
| 265 |
Litestar also offers a helper function called :func:`create_test_client <litestar.testing.create_test_client>` which first creates |
| 266 |
an instance of Litestar and then a test client using it. There are multiple use cases for this helper - when you need to check |
| 267 |
generic logic that is decoupled from a specific Litestar app, or when you want to test endpoints in isolation. |
| 268 |
|
| 269 |
You can pass to this helper all the kwargs accepted by |
| 270 |
the litestar constructor, with the ``route_handlers`` kwarg being **required**. Yet unlike the Litestar app, which |
| 271 |
expects ``route_handlers`` to be a list, here you can also pass individual values. |
| 272 |
|
| 273 |
For example, you can do this: |
| 274 |
|
| 275 |
.. code-block:: python |
| 276 |
:caption: ``my_app/tests/test_health_check.py`` |
| 277 |
|
| 278 |
from litestar.status_codes import HTTP_200_OK |
| 279 |
from litestar.testing import create_test_client |
| 280 |
|
| 281 |
from my_app.main import health_check |
| 282 |
|
| 283 |
|
| 284 |
def test_health_check(): |
| 285 |
with create_test_client(route_handlers=[health_check]) as client: |
| 286 |
response = client.get("/health-check") |
| 287 |
assert response.status_code == HTTP_200_OK |
| 288 |
assert response.text == "healthy" |
| 289 |
|
| 290 |
But also this: |
| 291 |
|
| 292 |
.. code-block:: python |
| 293 |
:caption: ``my_app/tests/test_health_check.py`` |
| 294 |
|
| 295 |
from litestar.status_codes import HTTP_200_OK |
| 296 |
from litestar.testing import create_test_client |
| 297 |
|
| 298 |
from my_app.main import health_check |
| 299 |
|
| 300 |
|
| 301 |
def test_health_check(): |
| 302 |
with create_test_client(route_handlers=health_check) as client: |
| 303 |
response = client.get("/health-check") |
| 304 |
assert response.status_code == HTTP_200_OK |
| 305 |
assert response.text == "healthy" |
| 306 |
|
| 307 |
|
| 308 |
Running a live server |
| 309 |
--------------------- |
| 310 |
|
| 311 |
The test clients make use of HTTPX's ability to directly call into an ASGI app, without |
| 312 |
having to run an actual server. In most cases this is sufficient but there are some |
| 313 |
exceptions where this won't work, due to the limitations of the emulated client-server |
| 314 |
communication. |
| 315 |
|
| 316 |
For example, when using server-sent events with an infinite generator, it will lock up |
| 317 |
the test client, since HTTPX tries to consume the full response before returning a |
| 318 |
request. |
| 319 |
|
| 320 |
Litestar offers two helper functions, |
| 321 |
:func:`litestar.testing.subprocess_sync_client` and |
| 322 |
:func:`litestar.testing.subprocess_async_client` that will |
| 323 |
launch a Litestar instance with in a subprocess and set up an httpx client for running |
| 324 |
tests. You can either load your actual app file or create subsets from it as you would |
| 325 |
with the regular test client setup: |
| 326 |
|
| 327 |
.. literalinclude:: /examples/testing/subprocess_sse_app.py |
| 328 |
:language: python |
| 329 |
|
| 330 |
.. literalinclude:: /examples/testing/test_subprocess_sse.py |
| 331 |
:language: python |
| 332 |
|
| 333 |
By default, the subprocess client will capture all output from the litestar instance. To discard output in the main (testing) process, set the ``capture_output`` argument to ``False`` when creating the client: |
| 334 |
|
| 335 |
.. code-block:: python |
| 336 |
|
| 337 |
@pytest.fixture(name="async_client") |
| 338 |
async def fx_async_client() -> AsyncIterator[httpx.AsyncClient]: |
| 339 |
async with subprocess_async_client(workdir=ROOT, app="subprocess_sse_app:app", capture_output=False) as client: |
| 340 |
yield client |
| 341 |
|
| 342 |
|
| 343 |
RequestFactory |
| 344 |
-------------- |
| 345 |
|
| 346 |
Another helper is the :class:`RequestFactory <litestar.testing.RequestFactory>` class, which creates instances of |
| 347 |
:class:`litestar.connection.request.Request <litestar.connection.request.Request>`. The use case for this helper is when |
| 348 |
you need to test logic that expects to receive a request object. |
| 349 |
|
| 350 |
For example, lets say we wanted to unit test a *guard* function in isolation, to which end we'll reuse the examples |
| 351 |
from the :doc:`route guards </usage/security/guards>` documentation: |
| 352 |
|
| 353 |
|
| 354 |
.. code-block:: python |
| 355 |
:caption: ``my_app/guards.py`` |
| 356 |
|
| 357 |
from litestar import Request |
| 358 |
from litestar.exceptions import NotAuthorizedException |
| 359 |
from litestar.handlers.base import BaseRouteHandler |
| 360 |
|
| 361 |
|
| 362 |
def secret_token_guard(request: Request, route_handler: BaseRouteHandler) -> None: |
| 363 |
if ( |
| 364 |
route_handler.opt.get("secret") |
| 365 |
and not request.headers.get("Secret-Header", "") == route_handler.opt["secret"] |
| 366 |
): |
| 367 |
raise NotAuthorizedException() |
| 368 |
|
| 369 |
We already have our route handler in place: |
| 370 |
|
| 371 |
.. code-block:: python |
| 372 |
:caption: ``my_app/secret.py`` |
| 373 |
|
| 374 |
from os import environ |
| 375 |
|
| 376 |
from litestar import get |
| 377 |
|
| 378 |
from my_app.guards import secret_token_guard |
| 379 |
|
| 380 |
|
| 381 |
@get(path="/secret", guards=[secret_token_guard], opt={"secret": environ.get("SECRET")}) |
| 382 |
def secret_endpoint() -> None: ... |
| 383 |
|
| 384 |
We could thus test the guard function like so: |
| 385 |
|
| 386 |
.. code-block:: python |
| 387 |
:caption: ``tests/guards/test_secret_token_guard.py`` |
| 388 |
|
| 389 |
import pytest |
| 390 |
|
| 391 |
from litestar.exceptions import NotAuthorizedException |
| 392 |
from litestar.testing import RequestFactory |
| 393 |
|
| 394 |
from my_app.guards import secret_token_guard |
| 395 |
from my_app.secret import secret_endpoint |
| 396 |
|
| 397 |
request = RequestFactory().get("/") |
| 398 |
|
| 399 |
|
| 400 |
def test_secret_token_guard_failure_scenario(): |
| 401 |
copied_endpoint_handler = secret_endpoint.copy() |
| 402 |
copied_endpoint_handler.opt["secret"] = None |
| 403 |
with pytest.raises(NotAuthorizedException): |
| 404 |
secret_token_guard(request=request, route_handler=copied_endpoint_handler) |
| 405 |
|
| 406 |
|
| 407 |
def test_secret_token_guard_success_scenario(): |
| 408 |
copied_endpoint_handler = secret_endpoint.copy() |
| 409 |
copied_endpoint_handler.opt["secret"] = "super-secret" |
| 410 |
secret_token_guard(request=request, route_handler=copied_endpoint_handler) |
| 411 |
|
| 412 |
|
| 413 |
Using polyfactory |
| 414 |
------------------------ |
| 415 |
|
| 416 |
`Polyfactory <https://github.com/litestar-org/polyfactory>`__ offers an easy |
| 417 |
and powerful way to generate mock data from pydantic models and dataclasses. |
| 418 |
|
| 419 |
Let's say we have an API that talks to an external service and retrieves some data: |
| 420 |
|
| 421 |
.. code-block:: python |
| 422 |
:caption: ``main.py`` |
| 423 |
|
| 424 |
from typing import Protocol, runtime_checkable |
| 425 |
|
| 426 |
from polyfactory.factories.pydantic import BaseModel |
| 427 |
from litestar import get |
| 428 |
|
| 429 |
|
| 430 |
class Item(BaseModel): |
| 431 |
name: str |
| 432 |
|
| 433 |
|
| 434 |
@runtime_checkable |
| 435 |
class Service(Protocol): |
| 436 |
def get(self) -> Item: ... |
| 437 |
|
| 438 |
|
| 439 |
@get(path="/item") |
| 440 |
def get_item(service: Service) -> Item: |
| 441 |
return service.get() |
| 442 |
|
| 443 |
|
| 444 |
We could test the ``/item`` route like so: |
| 445 |
|
| 446 |
.. code-block:: python |
| 447 |
:caption: ``tests/conftest.py`` |
| 448 |
|
| 449 |
import pytest |
| 450 |
|
| 451 |
from litestar.di import Provide |
| 452 |
from litestar.status_codes import HTTP_200_OK |
| 453 |
from litestar.testing import create_test_client |
| 454 |
|
| 455 |
from my_app.main import Service, Item, get_item |
| 456 |
|
| 457 |
|
| 458 |
@pytest.fixture() |
| 459 |
def item(): |
| 460 |
return Item(name="Chair") |
| 461 |
|
| 462 |
|
| 463 |
def test_get_item(item: Item): |
| 464 |
class MyService(Service): |
| 465 |
def get_one(self) -> Item: |
| 466 |
return item |
| 467 |
|
| 468 |
with create_test_client( |
| 469 |
route_handlers=get_item, dependencies={"service": Provide(lambda: MyService())} |
| 470 |
) as client: |
| 471 |
response = client.get("/item") |
| 472 |
assert response.status_code == HTTP_200_OK |
| 473 |
assert response.json() == item.dict() |
| 474 |
|
| 475 |
While we can define the test data manually, as is done in the above, this can be quite cumbersome. That's |
| 476 |
where `polyfactory <https://github.com/litestar-org/polyfactory>`_ library comes in. It generates mock data for |
| 477 |
pydantic models and dataclasses based on type annotations. With it, we could rewrite the above example like so: |
| 478 |
|
| 479 |
|
| 480 |
.. code-block:: python |
| 481 |
:caption: ``main.py`` |
| 482 |
|
| 483 |
from typing import Protocol, runtime_checkable |
| 484 |
|
| 485 |
import pytest |
| 486 |
from pydantic import BaseModel |
| 487 |
from polyfactory.factories.pydantic_factory import ModelFactory |
| 488 |
from litestar.status_codes import HTTP_200_OK |
| 489 |
from litestar import get |
| 490 |
from litestar.di import Provide |
| 491 |
from litestar.testing import create_test_client |
| 492 |
|
| 493 |
|
| 494 |
class Item(BaseModel): |
| 495 |
name: str |
| 496 |
|
| 497 |
|
| 498 |
@runtime_checkable |
| 499 |
class Service(Protocol): |
| 500 |
def get_one(self) -> Item: ... |
| 501 |
|
| 502 |
|
| 503 |
@get(path="/item") |
| 504 |
def get_item(service: Service) -> Item: |
| 505 |
return service.get_one() |
| 506 |
|
| 507 |
|
| 508 |
class ItemFactory(ModelFactory[Item]): |
| 509 |
model = Item |
| 510 |
|
| 511 |
|
| 512 |
@pytest.fixture() |
| 513 |
def item(): |
| 514 |
return ItemFactory.build() |
| 515 |
|
| 516 |
|
| 517 |
def test_get_item(item: Item): |
| 518 |
class MyService(Service): |
| 519 |
def get_one(self) -> Item: |
| 520 |
return item |
| 521 |
|
| 522 |
with create_test_client( |
| 523 |
route_handlers=get_item, dependencies={"service": Provide(lambda: MyService())} |
| 524 |
) as client: |
| 525 |
response = client.get("/item") |
| 526 |
assert response.status_code == HTTP_200_OK |
| 527 |
assert response.json() == item.dict() |