-
Notifications
You must be signed in to change notification settings - Fork 119
Expand file tree
/
Copy pathtest_litestar_guards.py
More file actions
83 lines (71 loc) · 2.1 KB
/
Copy pathtest_litestar_guards.py
File metadata and controls
83 lines (71 loc) · 2.1 KB
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
from collections.abc import AsyncGenerator
from contextlib import asynccontextmanager
from unittest.mock import Mock
import pytest
from asgi_lifespan import LifespanManager
from litestar import Litestar, get
from litestar.connection import ASGIConnection
from litestar.handlers import BaseRouteHandler
from litestar.testing import TestClient
from litestar.types import Guard
from dishka import make_async_container
from dishka.integrations.litestar import (
DishkaRouter,
FromDishka,
inject_asgi,
setup_dishka,
)
from ..common import (
APP_DEP_VALUE,
AppDep,
AppProvider,
)
@asynccontextmanager
async def dishka_app(
guard: Guard, provider: AppProvider) -> AsyncGenerator[TestClient, None]:
@get("/", guards=[guard])
async def endpoint() -> dict:
return {"status": "ok"}
app = Litestar([endpoint], debug=True)
container = make_async_container(provider)
setup_dishka(container, app)
async with LifespanManager(app):
yield TestClient(app)
await container.close()
@asynccontextmanager
async def dishka_auto_app(
guard: Guard, provider: AppProvider) -> AsyncGenerator[TestClient, None]:
@get("/")
async def endpoint() -> dict:
return {"status": "ok"}
router = DishkaRouter("", route_handlers=[endpoint], guards=[guard])
app = Litestar([router], debug=True)
container = make_async_container(provider)
setup_dishka(container, app)
async with LifespanManager(app):
yield TestClient(app)
await container.close()
@inject_asgi
async def guard_with_app(
connection: ASGIConnection,
_: BaseRouteHandler,
a: FromDishka[AppDep],
mock: FromDishka[Mock],
) -> None:
mock(a)
@pytest.mark.asyncio
@pytest.mark.parametrize(
("app_factory", "guard"),
[
(dishka_app, guard_with_app),
],
)
async def test_guard_injects_app_dependency(
app_factory,
guard,
app_provider: AppProvider,
):
async with app_factory(guard, app_provider) as client:
response = client.get("/")
assert response.status_code == 200
app_provider.mock.assert_called_with(APP_DEP_VALUE)