English 中文(简体)
“快车道倡议”网络电话+“大声”——如何测试连接是否关闭?
原标题:FastAPI websockets + PyTest - how to test if a connection was closed?

我用FastAPI在用户和服务器之间通信的网页上书写互联网游戏背后机械。 为测试框架,我选择了Py Test。 我的目标是编写一份检查关系关闭的测试。

在试图与非现有房间连接之后,这不应深入执行(管理人员不允许与不存在的东西连接)。

我完全不知道如何检验这一点。 我试图利用正式文件找到任何解决办法,但我没有发现。

我的测试守则如下:

import pytest
from fastapi.testclient import TestClient
from fastapi.websockets import WebSocketDisconnect

from src.game_manager import GameManager
from src.main import app

async def override_manager() -> GameManager:
    try:
        yield override_manager.manager
    except AttributeError:
        manager = GameManager()
        manager.add_new_game(max_players=2, room_name="foo", password=None)
        manager.add_new_game(max_players=2, room_name="bar", password="123")
        override_manager.manager = manager
        yield override_manager.manager


app.dependency_overrides[get_manager] = override_manager

client = TestClient(app)


class TestWebsocketConnection:
    def test_connect_to_non_existing_room(self):
        with pytest.raises(WebSocketDisconnect) as e_info:
            with client.websocket_connect("/ws/non_existing_room") as ws:
                ws.send_json({"message": "Hello world"})

回返

FAILED tests/test_websockets.py::TestWebsocketConnection::test_connect_to_non_existing_room - Failed: DID NOT RAISE <class  starlette.websockets.WebSocketDisconnect >

最终点看:

@router.websocket("/ws/{room_name}")
@router.websocket("/ws/{room_name}/{password}")
async def websocket_endpoint(
    websocket: WebSocket,
    manager: Annotated[GameManager, Depends(get_manager)],
):
    room_name = websocket.path_params["room_name"]
    password = websocket.path_params.get("password", None)

    try:
        await manager.connect(websocket, room_name, password)
        client_id = websocket.scope["client_id"]
        while True:
            data = await websocket.receive_json()
            await manager.handle_message(room_name, client_id, data)
    except WebSocketDisconnect:
        await manager.remove(websocket)

<NOTE:manager.link(websocket, Room_name, Password),WebSocketDisjoint,条件是不能允许链接。

如果联系已经关闭,请你帮助我检验。

问题回答

奥凯找到了解决办法。

如果在打电话<代码>websocket.accept()后没有将任何名词发送到网上,并且在特定条件下终止联系(websocket.close(<>),我们可以尝试使用ws.receive_json()。 页: 1 WebSocketDislink。

对像我这样有类似问题的人来说,这是一个工作考验:

import pytest
from fastapi.testclient import TestClient
from fastapi.websockets import WebSocketDisconnect

...
client = TestClient(app)


class TestWebsocketConnection:
    def test_connect_to_non_existing_room(self):
        with pytest.raises(WebSocketDisconnect):
            with client.websocket_connect("/ws/non_existing_room") as ws:
                ws.receive_json()




相关问题
Can Django models use MySQL functions?

Is there a way to force Django models to pass a field to a MySQL function every time the model data is read or loaded? To clarify what I mean in SQL, I want the Django model to produce something like ...

An enterprise scheduler for python (like quartz)

I am looking for an enterprise tasks scheduler for python, like quartz is for Java. Requirements: Persistent: if the process restarts or the machine restarts, then all the jobs must stay there and ...

How to remove unique, then duplicate dictionaries in a list?

Given the following list that contains some duplicate and some unique dictionaries, what is the best method to remove unique dictionaries first, then reduce the duplicate dictionaries to single ...

What is suggested seed value to use with random.seed()?

Simple enough question: I m using python random module to generate random integers. I want to know what is the suggested value to use with the random.seed() function? Currently I am letting this ...

How can I make the PyDev editor selectively ignore errors?

I m using PyDev under Eclipse to write some Jython code. I ve got numerous instances where I need to do something like this: import com.work.project.component.client.Interface.ISubInterface as ...

How do I profile `paster serve` s startup time?

Python s paster serve app.ini is taking longer than I would like to be ready for the first request. I know how to profile requests with middleware, but how do I profile the initialization time? I ...

Pragmatically adding give-aways/freebies to an online store

Our business currently has an online store and recently we ve been offering free specials to our customers. Right now, we simply display the special and give the buyer a notice stating we will add the ...

Converting Dictionary to List? [duplicate]

I m trying to convert a Python dictionary into a Python list, in order to perform some calculations. #My dictionary dict = {} dict[ Capital ]="London" dict[ Food ]="Fish&Chips" dict[ 2012 ]="...

热门标签