Coverage for tests/asgi/test_app.py: 98%
62 statements
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-17 21:20 +0000
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-17 21:20 +0000
1"""ASGI-specific logic that does not depend on a concrete broker.
3These tests exercise routing, the AsyncAPI docs/JSON endpoints, the ASGI
4handler decorators and dependency injection directly — no broker is required,
5so they run once instead of being inherited by every broker test case. Broker
6behaviour (message delivery, healthchecks, try-it-out dispatch) lives in
7``AsgiTestcase`` and is still parametrized per broker.
8"""
10from collections.abc import Callable
11from typing import Any
12from unittest.mock import MagicMock
14import pytest
15from fast_depends import Depends
16from starlette.testclient import TestClient
17from starlette.websockets import WebSocketDisconnect
19from faststream._internal.context import Context
20from faststream.annotations import FastStream, Logger
21from faststream.asgi import (
22 AsgiFastStream,
23 AsgiResponse,
24 AsyncAPIRoute,
25 Request,
26 get,
27 post,
28)
29from faststream.asgi.params import Header, Query
30from faststream.asgi.response import JSONResponse
31from faststream.asgi.types import ASGIApp, Scope
32from faststream.rabbit import RabbitBroker
33from faststream.specification import AsyncAPI
36def test_not_found() -> None:
37 client = TestClient(AsgiFastStream())
38 response = client.get("/")
39 assert response.status_code == 404
42def test_ws_not_found() -> None:
43 client = TestClient(AsgiFastStream())
44 with (
45 pytest.raises(WebSocketDisconnect),
46 client.websocket_connect("/ws"),
47 ): # raises error
48 pass
51def test_asyncapi_asgi() -> None:
52 app = AsgiFastStream(specification=AsyncAPI(), asyncapi_path="/docs")
54 client = TestClient(app)
55 response = client.get("/docs")
56 assert response.status_code == 200, response
57 assert response.text
60def test_asyncapi_json_default_path() -> None:
61 app = AsgiFastStream(specification=AsyncAPI(), asyncapi_path="/docs")
63 client = TestClient(app)
64 response = client.get("/docs.json")
65 assert response.status_code == 200, response
66 assert response.headers["content-type"] == "application/json"
67 assert response.json() == app.schema.to_specification().to_jsonable()
70def test_asyncapi_json_path_strips_trailing_slash() -> None:
71 app = AsgiFastStream(specification=AsyncAPI(), asyncapi_path="/docs/")
73 client = TestClient(app)
74 assert client.get("/docs.json").status_code == 200
77def test_asyncapi_json_custom_path() -> None:
78 app = AsgiFastStream(
79 specification=AsyncAPI(),
80 asyncapi_path=AsyncAPIRoute("/docs", asyncapi_json_path="/openapi.json"),
81 )
83 client = TestClient(app)
84 response = client.get("/openapi.json")
85 assert response.status_code == 200, response
86 assert response.json() == app.schema.to_specification().to_jsonable()
88 # the default derived path is not registered when overridden
89 assert client.get("/docs.json").status_code == 404
92def test_asyncapi_json_disabled() -> None:
93 app = AsgiFastStream(
94 specification=AsyncAPI(),
95 asyncapi_path=AsyncAPIRoute("/docs", asyncapi_json_path=None),
96 )
98 client = TestClient(app)
99 # docs HTML is still served
100 assert client.get("/docs").status_code == 200
101 # but the JSON endpoint is not registered
102 assert client.get("/docs.json").status_code == 404
105@pytest.mark.asyncio()
106async def test_async_context_manager(mock: MagicMock) -> None:
107 app = AsgiFastStream(
108 MagicMock(spec=RabbitBroker),
109 on_startup=[mock.on],
110 on_shutdown=[mock.off],
111 )
113 async with app as context_app:
114 assert context_app is app
116 mock.on.assert_called_once()
117 mock.off.assert_called_once()
120@pytest.mark.parametrize(
121 ("decorator", "client_method"),
122 (
123 pytest.param(get, "get", id="get"),
124 pytest.param(post, "post", id="post"),
125 ),
126)
127def test_decorators(decorator: Callable[..., ASGIApp], client_method: str) -> None:
128 @decorator
129 async def some_handler(scope: Scope) -> AsgiResponse:
130 return AsgiResponse(body=b"test", status_code=200)
132 app = AsgiFastStream(asgi_routes=[("/test", some_handler)])
134 client = TestClient(app)
135 response = getattr(client, client_method)("/test")
136 assert response.status_code == 200
137 assert response.text == "test"
140@pytest.mark.parametrize(
141 ("decorator", "client_method"),
142 (
143 pytest.param(get, "get", id="get"),
144 pytest.param(post, "post", id="post"),
145 ),
146)
147def test_context_injected(decorator: Callable[..., ASGIApp], client_method: str) -> None:
148 @decorator
149 async def some_handler(
150 request: Request, logger: Logger, app: FastStream
151 ) -> AsgiResponse:
152 return AsgiResponse(
153 body=f"{request.__class__.__name__} {logger.__class__.__name__} {app.__class__.__name__}".encode(),
154 status_code=200,
155 )
157 app = AsgiFastStream(asgi_routes=[("/test", some_handler)])
159 client = TestClient(app)
160 response = getattr(client, client_method)("/test")
161 assert response.status_code == 200
162 assert response.text == "AsgiRequest Logger AsgiFastStream"
165@pytest.mark.parametrize(
166 ("decorator", "client_method"),
167 (
168 pytest.param(get, "get", id="get"),
169 pytest.param(post, "post", id="post"),
170 ),
171)
172def test_fast_depends_injected(
173 decorator: Callable[..., ASGIApp], client_method: str
174) -> None:
175 def get_string() -> str:
176 return "test"
178 @decorator
179 async def some_handler(string: str = Depends(get_string)) -> AsgiResponse:
180 return AsgiResponse(body=string.encode(), status_code=200)
182 app = AsgiFastStream(asgi_routes=[("/test", some_handler)])
184 client = TestClient(app)
185 response = getattr(client, client_method)("/test")
186 assert response.status_code == 200
187 assert response.text == "test"
190@pytest.mark.parametrize(
191 "dependency",
192 (
193 pytest.param(Query(), id="query"),
194 pytest.param(Header(), id="header"),
195 ),
196)
197def test_validation_error_handled(dependency: Context) -> None:
198 @get
199 async def some_handler(dep: Any = dependency) -> AsgiResponse:
200 return AsgiResponse(status_code=200)
202 app = AsgiFastStream(asgi_routes=[("/test", some_handler)])
204 client = TestClient(app)
205 response = client.get("/test")
206 assert response.status_code == 422
207 assert response.text == "Validation error"
210@pytest.mark.parametrize(
211 ("query", "expected"),
212 (
213 pytest.param(
214 "name=Anna+Vanna&name=A%2BB",
215 {"name": ["Anna Vanna", "A+B"]},
216 id="ascii",
217 ),
218 pytest.param(
219 "name=%C3%A9&name=%E6%9D%B1%E4%BA%AC",
220 {"name": ["\u00e9", "\u6771\u4eac"]},
221 id="utf8-values",
222 ),
223 pytest.param("%C3%A9=value", {"\u00e9": ["value"]}, id="utf8-key"),
224 ),
225)
226def test_correct_encode_query_params(query: str, expected: dict[str, list[str]]) -> None:
227 """Fixes https://github.com/ag2ai/faststream/issues/3344."""
229 @get
230 async def handler(request: Request) -> AsgiResponse:
231 return JSONResponse(request.query_params)
233 client = TestClient(AsgiFastStream(asgi_routes=[("/test", handler)]))
234 response = client.get(f"/test?{query}")
235 assert response.status_code == 200
236 assert response.json() == expected