| 1 |
import importlib |
| 2 |
import time |
| 3 |
from types import ModuleType |
| 4 |
|
| 5 |
import pytest |
| 6 |
from fastapi.testclient import TestClient |
| 7 |
|
| 8 |
|
| 9 |
@pytest.fixture( |
| 10 |
name="mod", |
| 11 |
params=[ |
| 12 |
pytest.param("tutorial003_py310"), |
| 13 |
], |
| 14 |
) |
| 15 |
def get_mod(request: pytest.FixtureRequest): |
| 16 |
mod = importlib.import_module(f"docs_src.websockets_.{request.param}") |
| 17 |
|
| 18 |
return mod |
| 19 |
|
| 20 |
|
| 21 |
@pytest.fixture(name="html") |
| 22 |
def get_html(mod: ModuleType): |
| 23 |
return mod.html |
| 24 |
|
| 25 |
|
| 26 |
@pytest.fixture(name="client") |
| 27 |
def get_client(mod: ModuleType): |
| 28 |
client = TestClient(mod.app) |
| 29 |
|
| 30 |
return client |
| 31 |
|
| 32 |
|
| 33 |
def test_get(client: TestClient, html: str): |
| 34 |
response = client.get("/") |
| 35 |
assert response.text == html |
| 36 |
|
| 37 |
|
| 38 |
def test_websocket_handle_disconnection(client: TestClient): |
| 39 |
with ( |
| 40 |
client.websocket_connect("/ws/1234") as connection, |
| 41 |
client.websocket_connect("/ws/5678") as connection_two, |
| 42 |
): |
| 43 |
connection.send_text("Hello from 1234") |
| 44 |
data1 = connection.receive_text() |
| 45 |
assert data1 == "You wrote: Hello from 1234" |
| 46 |
time.sleep(0.01) # Give server time to process broadcast |
| 47 |
data2 = connection_two.receive_text() |
| 48 |
client1_says = "Client #1234 says: Hello from 1234" |
| 49 |
assert data2 == client1_says |
| 50 |
data1 = connection.receive_text() |
| 51 |
assert data1 == client1_says |
| 52 |
connection_two.close() |
| 53 |
time.sleep(0.01) # Give server time to process broadcast |
| 54 |
data1 = connection.receive_text() |
| 55 |
assert data1 == "Client #5678 left the chat" |