Debian Codegraph @

tests/unit/test_handlers/test_websocket_handlers/test_stream.py

raw symbols ◀ ▶ SCIP
2 Debian patches touch this file
1 from __future__ import annotations
2
3 import asyncio
4 import dataclasses
5 from typing import TYPE_CHECKING, AsyncGenerator, Dict, Generator
6 from unittest.mock import MagicMock
7
•8 import platform
9 import pytest
10
11 from litestar import Controller, Litestar, WebSocket
12 from litestar.di import NamedDependency
13 from litestar.dto import DataclassDTO, dto_field
14 from litestar.exceptions import ImproperlyConfiguredException
15 from litestar.handlers.websocket_handlers import websocket_stream
16 from litestar.testing import create_test_client
17
18 if TYPE_CHECKING:
19 from litestar.connection import ASGIConnection
20 from litestar.handlers.base import BaseRouteHandler
21
22
23 def test_websocket_stream() -> None:
24 @websocket_stream("/")
25 async def handler(socket: WebSocket) -> AsyncGenerator[str, None]:
26 yield "foo"
27 yield "bar"
28
29 with create_test_client([handler]) as client, client.websocket_connect("/") as ws:
30 assert ws.receive_text(timeout=0.1) == "foo"
31 assert ws.receive_text(timeout=0.1) == "bar"
32
•33
•34 @pytest.mark.skipif(platform.machine() == "riscv64" , reason="Expected to fail on riscv64, test is running too flaky.")
35 @pytest.mark.skipif(platform.machine() == "ppc64" , reason="Expected to fail on ppc64(el), test is running too flaky.")
36 def test_websocket_stream_in_controller() -> None:
37 class MyController(Controller):
38 @websocket_stream("/")
39 async def handler(self, socket: WebSocket) -> AsyncGenerator[str, None]:
40 yield "foo"
41
42 with create_test_client([MyController]) as client, client.websocket_connect("/") as ws:
43 assert ws.receive_text(timeout=0.1) == "foo"
44
45
46 def test_websocket_stream_without_socket() -> None:
47 @websocket_stream("/")
48 async def handler() -> AsyncGenerator[str, None]:
49 yield "foo"
50
51 with create_test_client([handler]) as client, client.websocket_connect("/") as ws:
52 assert ws.receive_text(timeout=0.1) == "foo"
53
54
55 def test_websocket_stream_dependency_injection() -> None:
56 async def provide_hello() -> str:
57 return "hello"
58
59 # ensure we can inject dependencies
60 @websocket_stream("/1", dependencies={"greeting": provide_hello})
61 async def handler_one(greeting: NamedDependency[str]) -> AsyncGenerator[str, None]:
62 yield greeting
63
64 # ensure dependency injection also works with 'socket' present
65 @websocket_stream("/2", dependencies={"greeting": provide_hello})
66 async def handler_two(socket: WebSocket, greeting: NamedDependency[str]) -> AsyncGenerator[str, None]:
67 yield greeting
68
69 with create_test_client([handler_one, handler_two]) as client:
70 with client.websocket_connect("/1") as ws:
71 assert ws.receive_text(timeout=0.1) == "hello"
72
73 with client.websocket_connect("/2") as ws:
74 assert ws.receive_text(timeout=0.1) == "hello"
75
76
77 def test_websocket_stream_dependencies_cleaned_up_after_stream_close() -> None:
78 mock = MagicMock()
79
80 async def dep() -> AsyncGenerator[str, None]:
81 yield "foo"
82 mock()
83
84 @websocket_stream(
85 "/",
86 dependencies={"message": dep},
87 listen_for_disconnect=False,
88 )
89 async def handler(socket: WebSocket, message: NamedDependency[str]) -> AsyncGenerator[str, None]:
90 yield "one"
91 await socket.receive_text()
92 yield message
93
94 with create_test_client([handler]) as client, client.websocket_connect("/") as ws:
95 assert ws.receive_text(timeout=0.1) == "one"
96 assert mock.call_count == 0
97 ws.send_text("")
98 assert ws.receive_text(timeout=0.1) == "foo"
99
100 assert mock.call_count == 1
101
102
103 def test_websocket_stream_handle_disconnect() -> None:
104 @websocket_stream("/")
105 async def handler() -> AsyncGenerator[str, None]:
106 while True:
107 yield "foo"
108 # sleep for longer than our read-timeout to ensure we're disconnecting prematurely
109 await asyncio.sleep(1)
110
111 with create_test_client([handler]) as client, client.websocket_connect("/") as ws:
112 assert ws.receive_text(timeout=0.1) == "foo"
113
114 with create_test_client([handler]) as client, client.websocket_connect("/") as ws:
115 # ensure we still disconnect even after receiving some data
116 ws.send_text("")
117 assert ws.receive_text(timeout=0.1) == "foo"
118
119
120 def test_websocket_stream_send_json() -> None:
121 @websocket_stream("/")
122 async def handler() -> AsyncGenerator[Dict[str, str], None]: # noqa: UP006
123 yield {"hello": "there"}
124 yield {"and": "goodbye"}
125
126 with create_test_client([handler]) as client, client.websocket_connect("/") as ws:
127 assert ws.receive_json(timeout=0.1) == {"hello": "there"}
128 assert ws.receive_json(timeout=0.1) == {"and": "goodbye"}
129
130
131 def test_websocket_stream_send_json_with_dto() -> None:
132 @dataclasses.dataclass
133 class Event:
134 id: int = dataclasses.field(metadata=dto_field("private"))
135 content: str
136
137 @websocket_stream("/", return_dto=DataclassDTO[Event])
138 async def handler() -> AsyncGenerator[Event, None]:
139 yield Event(id=1, content="hello")
140
141 with create_test_client([handler], signature_types=[Event]) as client, client.websocket_connect("/") as ws:
142 assert ws.receive_json(timeout=0.1) == {"content": "hello"}
143
144
145 def test_raises_if_stream_fn_does_not_return_async_generator() -> None:
146 with pytest.raises(ImproperlyConfiguredException):
147
148 @websocket_stream("/") # type: ignore[arg-type]
149 def foo() -> Generator[bytes, None, None]:
150 yield b""
151
152 Litestar([foo])
153
154 with pytest.raises(ImproperlyConfiguredException):
155
156 @websocket_stream("/") # type: ignore[arg-type]
157 def foo() -> bytes:
158 return b""
159
160 Litestar([foo])
161
162
163 def test_websocket_stream_applies_guards() -> None:
164 guard_called = False
165
166 async def custom_guard(connection: ASGIConnection, _: BaseRouteHandler) -> None:
167 nonlocal guard_called
168 guard_called = True
169
170 @websocket_stream("/", guards=[custom_guard])
171 async def handler() -> AsyncGenerator[Dict[str, str], None]: # noqa: UP006
172 yield {"Urfaust": "Gespinnst"}
173 yield {"Des": "Verderbens"}
174
175 with create_test_client([handler]) as client, client.websocket_connect("/") as ws:
176 assert ws.receive_json(timeout=0.1) == {"Urfaust": "Gespinnst"}
177 assert ws.receive_json(timeout=0.1) == {"Des": "Verderbens"}
178 assert guard_called is True