async def _stream() -> WSStream: stream = WSStream(AsyncMock(), Config(), AsyncMock(), False, None, None, AsyncMock(), 1) stream.context.spawn_app.return_value = AsyncMock() # type: ignore stream.app_put = AsyncMock() stream.config._log = AsyncMock(spec=Logger) return stream
async def _stream() -> WSStream: stream = WSStream(Config(), False, None, None, CoroutineMock(), CoroutineMock(), 1) stream.spawn_app.return_value = CoroutineMock() stream.app_put = CoroutineMock() stream.config._log = AsyncMock(spec=Logger) return stream
async def test_send_invalid_http_message( stream: WSStream, status: Any, headers: Any, body: Any ) -> None: stream.connection = Mock() stream.state = ASGIWebsocketState.HANDSHAKE stream.scope = {"method": "GET"} with pytest.raises((TypeError, ValueError)): await stream.app_send( {"type": "websocket.http.response.start", "headers": headers, "status": status} ) await stream.app_send({"type": "websocket.http.response.body", "body": body})
async def test_pings(stream: WSStream, event_loop: asyncio.AbstractEventLoop) -> None: stream.config.websocket_ping_interval = 0.1 await stream.handle( Request( stream_id=1, http_version="2", headers=[(b"sec-websocket-version", b"13")], raw_path=b"/?a=b", method="GET", ) ) async with TaskGroup(event_loop) as task_group: stream.context = Context(task_group) await stream.app_send({"type": "websocket.accept"}) stream.app_put = AsyncMock() await asyncio.sleep(0.15) assert stream.send.call_args_list == [ call(Response(stream_id=1, headers=[], status_code=200)), call(Data(stream_id=1, data=b"\x89\x00")), call(Data(stream_id=1, data=b"\x89\x00")), ] await stream.handle(StreamClosed(stream_id=1))
async def test_handle_connection(stream: WSStream) -> None: await stream.handle( Request( stream_id=1, http_version="2.0", headers=[(b"sec-websocket-version", b"13")], raw_path=b"/?a=b", method="GET", ) ) await stream.app_send({"type": "websocket.accept"}) stream.app_put = CoroutineMock() await stream.handle(Data(stream_id=1, data=b"\x81\x85&`\x13\x0eN\x05\x7fbI")) stream.app_put.assert_called() assert stream.app_put.call_args_list == [ call({"type": "websocket.receive", "bytes": None, "text": "hello"}) ]
async def test_closed_app_send_noop(stream: WSStream) -> None: stream.closed = True await stream.app_send( cast(WebsocketAcceptEvent, {"type": "websocket.accept"})) stream.send.assert_not_called() # type: ignore
def test_stream_idle(stream: WSStream, state: ASGIWebsocketState, idle: bool) -> None: stream.state = state assert stream.idle is idle
async def test_send_invalid_message_given_state(stream: WSStream, state: ASGIWebsocketState, message_type: str) -> None: stream.state = state with pytest.raises(UnexpectedMessage): await stream.app_send({"type": message_type}) # type: ignore
async def test_closed_app_send_noop(stream: WSStream) -> None: stream.closed = True await stream.app_send({"type": "websocket.accept"}) stream.send.assert_not_called()