File: testing.rst

package info (click to toggle)
litestar 2.19.0-2
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 12,500 kB
  • sloc: python: 70,169; makefile: 254; javascript: 105; sh: 60
file content (517 lines) | stat: -rw-r--r-- 15,739 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
Testing
=======

Testing is a first class citizen in Litestar, which offers several powerful testing utilities out of the box.


Test Client
-----------

Litestar's test client is built on top of
the `httpx <https://github.com/encode/httpx>`_ library. To use the test client you should pass to it an
instance of Litestar as the ``app`` kwarg.

Let's say we have a very simple app with a health check endpoint:

.. code-block:: python
    :caption: ``my_app/main.py``

    from litestar import Litestar, MediaType, get


    @get(path="/health-check", media_type=MediaType.TEXT)
    def health_check() -> str:
        return "healthy"


    app = Litestar(route_handlers=[health_check])


We would then test it using the test client like so:

.. tab-set::

    .. tab-item:: Sync
        :sync: sync

        .. code-block:: python
            :caption: ``tests/test_health_check.py``

            from litestar.status_codes import HTTP_200_OK
            from litestar.testing import TestClient

            from my_app.main import app

            app.debug = True


            def test_health_check():
                with TestClient(app=app) as client:
                    response = client.get("/health-check")
                    assert response.status_code == HTTP_200_OK
                    assert response.text == "healthy"

    .. tab-item:: Async
        :sync: async

        .. code-block:: python
            :caption: ``tests/test_health_check.py``

            from litestar.status_codes import HTTP_200_OK
            from litestar.testing import AsyncTestClient

            from my_app.main import app

            app.debug = True


            async def test_health_check():
                async with AsyncTestClient(app=app) as client:
                    response = await client.get("/health-check")
                    assert response.status_code == HTTP_200_OK
                    assert response.text == "healthy"


Since we would probably need to use the client in multiple places, it's better to make it into a pytest fixture:


.. tab-set::

    .. tab-item:: Sync
        :sync: sync

        .. code-block:: python
            :caption: ``tests/conftest.py``

            from typing import TYPE_CHECKING, Iterator

            import pytest

            from litestar.testing import TestClient

            from my_app.main import app

            if TYPE_CHECKING:
                from litestar import Litestar

            app.debug = True


            @pytest.fixture(scope="function")
            def test_client() -> Iterator[TestClient[Litestar]]:
                with TestClient(app=app) as client:
                    yield client


    .. tab-item:: Async
        :sync: async

        .. code-block:: python
            :caption: ``tests/conftest.py``

            from typing import TYPE_CHECKING, AsyncIterator

            import pytest

            from litestar.testing import AsyncTestClient

            from my_app.main import app

            if TYPE_CHECKING:
                from litestar import Litestar

            app.debug = True


            @pytest.fixture(scope="function")
            async def test_client() -> AsyncIterator[AsyncTestClient[Litestar]]:
                async with AsyncTestClient(app=app) as client:
                    yield client


We would then be able to rewrite our test like so:

.. tab-set::

    .. tab-item:: Sync
        :sync: sync

        .. literalinclude:: /examples/testing/test_health_check_sync.py
            :caption: ``tests/test_health_check.py``
            :language: python


    .. tab-item:: Async
        :sync: async

        .. literalinclude:: /examples/testing/test_health_check_async.py
            :caption: ``tests/test_health_check.py``
            :language: python

Testing websockets
++++++++++++++++++

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>`
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:

For more information, see also the :class:`WebSocket <litestar.connection.WebSocket>` class in the API documentation and the :ref:`websocket <usage/websockets:websockets>` documentation.

    .. literalinclude:: /examples/testing/test_websocket.py
        :language: python


Using sessions
++++++++++++++

If you are using :ref:`session middleware <usage/middleware/builtin-middleware:session middleware>` for session persistence
across requests, then you might want to inject or inspect session data outside a request. For this,
:class:`TestClient <.testing.TestClient>` provides two methods:

* :meth:`set_session_data <litestar.testing.TestClient.set_session_data>`
* :meth:`get_session_data <litestar.testing.TestClient.get_session_data>`

.. attention::

    - The Session Middleware must be enabled in Litestar app provided to the TestClient to use sessions.
    - If you are using the
      :class:`ClientSideSessionBackend <litestar.middleware.session.client_side.ClientSideSessionBackend>` you need to
      install the ``cryptography`` package. You can do so by installing ``litestar``:

    .. tab-set::

        .. tab-item:: pip

            .. code-block:: bash
                :caption: Using pip

                python3 -m pip install 'litestar[cryptography]'

        .. tab-item:: pipx

            .. code-block:: bash
                :caption: Using `pipx <https://pypa.github.io/pipx/>`_

                pipx install 'litestar[cryptography]'

        .. tab-item:: pdm

            .. code-block:: bash
                :caption: Using `PDM <https://pdm.fming.dev/>`_

                pdm add 'litestar[cryptography]'

        .. tab-item:: poetry

            .. code-block:: bash
                :caption: Using `poetry <https://python-poetry.org/>`_

                poetry add 'litestar[cryptography]'

        .. tab-item:: uv

            .. code-block:: bash
                :caption: Using `uv <https://docs.astral.sh/uv/>`_

                uv add 'litestar[cryptography]'

.. tab-set::

    .. tab-item:: Sync
        :sync: sync

        .. literalinclude:: /examples/testing/test_set_session_data.py
            :caption: Setting session data
            :language: python


        .. literalinclude:: /examples/testing/test_get_session_data.py
            :caption: Getting session data
            :language: python

    .. tab-item:: Async
        :sync: async

        .. literalinclude:: /examples/testing/test_set_session_data_async.py
            :caption: Setting session data
            :language: python


        .. literalinclude:: /examples/testing/test_get_session_data_async.py
            :caption: Getting session data
            :language: python


Using a blocking portal
+++++++++++++++++++++++

The :class:`TestClient <.testing.TestClient>` uses a feature of `anyio <https://anyio.readthedocs.io/en/stable/>`_ called
a **Blocking Portal**.

The :class:`anyio.abc.BlockingPortal` allows :class:`TestClient <.testing.TestClient>`
to execute asynchronous functions using a synchronous call. ``TestClient`` creates a blocking portal to manage
``Litestar``'s async logic, and it allows ``TestClient``'s API to remain fully synchronous.

Any tests that are using an instance of ``TestClient`` can also make use of the blocking portal to execute asynchronous functions
without the test itself being asynchronous.

.. literalinclude:: /examples/testing/test_with_portal.py
   :caption: Using a blocking portal
   :language: python


Creating a test app
-------------------

Litestar also offers a helper function called :func:`create_test_client <litestar.testing.create_test_client>` which first creates
an instance of Litestar and then a test client using it. There are multiple use cases for this helper - when you need to check
generic logic that is decoupled from a specific Litestar app, or when you want to test endpoints in isolation.

You can pass to this helper all the kwargs accepted by
the litestar constructor, with the ``route_handlers`` kwarg being **required**. Yet unlike the Litestar app, which
expects ``route_handlers`` to be a list, here you can also pass individual values.

For example, you can do this:

.. code-block:: python
    :caption: ``my_app/tests/test_health_check.py``

    from litestar.status_codes import HTTP_200_OK
    from litestar.testing import create_test_client

    from my_app.main import health_check


    def test_health_check():
        with create_test_client(route_handlers=[health_check]) as client:
            response = client.get("/health-check")
            assert response.status_code == HTTP_200_OK
            assert response.text == "healthy"

But also this:

.. code-block:: python
    :caption: ``my_app/tests/test_health_check.py``

    from litestar.status_codes import HTTP_200_OK
    from litestar.testing import create_test_client

    from my_app.main import health_check


    def test_health_check():
        with create_test_client(route_handlers=health_check) as client:
            response = client.get("/health-check")
            assert response.status_code == HTTP_200_OK
            assert response.text == "healthy"


Running a live server
---------------------

The test clients make use of HTTPX's ability to directly call into an ASGI app, without
having to run an actual server. In most cases this is sufficient but there are some
exceptions where this won't work, due to the limitations of the emulated client-server
communication.

For example, when using server-sent events with an infinite generator, it will lock up
the test client, since HTTPX tries to consume the full response before returning a
request.

Litestar offers two helper functions,
:func:`litestar.testing.subprocess_sync_client` and
:func:`litestar.testing.subprocess_async_client` that will
launch a Litestar instance with in a subprocess and set up an httpx client for running
tests. You can either load your actual app file or create subsets from it as you would
with the regular test client setup:

.. literalinclude:: /examples/testing/subprocess_sse_app.py
    :language: python

.. literalinclude:: /examples/testing/test_subprocess_sse.py
    :language: python

RequestFactory
--------------

Another helper is the :class:`RequestFactory <litestar.testing.RequestFactory>` class, which creates instances of
:class:`litestar.connection.request.Request <litestar.connection.request.Request>`. The use case for this helper is when
you need to test logic that expects to receive a request object.

For example, lets say we wanted to unit test a *guard* function in isolation, to which end we'll reuse the examples
from the :doc:`route guards </usage/security/guards>` documentation:


.. code-block:: python
    :caption: ``my_app/guards.py``

    from litestar import Request
    from litestar.exceptions import NotAuthorizedException
    from litestar.handlers.base import BaseRouteHandler


    def secret_token_guard(request: Request, route_handler: BaseRouteHandler) -> None:
        if (
            route_handler.opt.get("secret")
            and not request.headers.get("Secret-Header", "") == route_handler.opt["secret"]
        ):
            raise NotAuthorizedException()

We already have our route handler in place:

.. code-block:: python
    :caption: ``my_app/secret.py``

    from os import environ

    from litestar import get

    from my_app.guards import secret_token_guard


    @get(path="/secret", guards=[secret_token_guard], opt={"secret": environ.get("SECRET")})
    def secret_endpoint() -> None: ...

We could thus test the guard function like so:

.. code-block:: python
    :caption: ``tests/guards/test_secret_token_guard.py``

    import pytest

    from litestar.exceptions import NotAuthorizedException
    from litestar.testing import RequestFactory

    from my_app.guards import secret_token_guard
    from my_app.secret import secret_endpoint

    request = RequestFactory().get("/")


    def test_secret_token_guard_failure_scenario():
        copied_endpoint_handler = secret_endpoint.copy()
        copied_endpoint_handler.opt["secret"] = None
        with pytest.raises(NotAuthorizedException):
            secret_token_guard(request=request, route_handler=copied_endpoint_handler)


    def test_secret_token_guard_success_scenario():
        copied_endpoint_handler = secret_endpoint.copy()
        copied_endpoint_handler.opt["secret"] = "super-secret"
        secret_token_guard(request=request, route_handler=copied_endpoint_handler)


Using polyfactory
------------------------

`Polyfactory <https://github.com/litestar-org/polyfactory>`__ offers an easy
and powerful way to generate mock data from pydantic models and dataclasses.

Let's say we have an API that talks to an external service and retrieves some data:

.. code-block:: python
    :caption: ``main.py``

    from typing import Protocol, runtime_checkable

    from polyfactory.factories.pydantic import BaseModel
    from litestar import get


    class Item(BaseModel):
        name: str


    @runtime_checkable
    class Service(Protocol):
        def get(self) -> Item: ...


    @get(path="/item")
    def get_item(service: Service) -> Item:
        return service.get()


We could test the ``/item`` route like so:

.. code-block:: python
    :caption: ``tests/conftest.py``

    import pytest

    from litestar.di import Provide
    from litestar.status_codes import HTTP_200_OK
    from litestar.testing import create_test_client

    from my_app.main import Service, Item, get_item


    @pytest.fixture()
    def item():
        return Item(name="Chair")


    def test_get_item(item: Item):
        class MyService(Service):
            def get_one(self) -> Item:
                return item

        with create_test_client(
            route_handlers=get_item, dependencies={"service": Provide(lambda: MyService())}
        ) as client:
            response = client.get("/item")
            assert response.status_code == HTTP_200_OK
            assert response.json() == item.dict()

While we can define the test data manually, as is done in the above, this can be quite cumbersome. That's
where `polyfactory <https://github.com/litestar-org/polyfactory>`_ library comes in. It generates mock data for
pydantic models and dataclasses based on type annotations. With it, we could rewrite the above example like so:


.. code-block:: python
    :caption: ``main.py``

    from typing import Protocol, runtime_checkable

    import pytest
    from pydantic import BaseModel
    from polyfactory.factories.pydantic_factory import ModelFactory
    from litestar.status_codes import HTTP_200_OK
    from litestar import get
    from litestar.di import Provide
    from litestar.testing import create_test_client


    class Item(BaseModel):
        name: str


    @runtime_checkable
    class Service(Protocol):
        def get_one(self) -> Item: ...


    @get(path="/item")
    def get_item(service: Service) -> Item:
        return service.get_one()


    class ItemFactory(ModelFactory[Item]):
        model = Item


    @pytest.fixture()
    def item():
        return ItemFactory.build()


    def test_get_item(item: Item):
        class MyService(Service):
            def get_one(self) -> Item:
                return item

        with create_test_client(
            route_handlers=get_item, dependencies={"service": Provide(lambda: MyService())}
        ) as client:
            response = client.get("/item")
            assert response.status_code == HTTP_200_OK
            assert response.json() == item.dict()