Coverage for tests / test_tutorial / test_websockets / test_tutorial003.py: 100%

34 statements  

« prev     ^ index     » next       coverage.py v7.13.3, created at 2026-04-06 01:24 +0000

1import importlib 1bcde

2import time 1bcde

3from types import ModuleType 1bcde

4 

5import pytest 1bcde

6from fastapi.testclient import TestClient 1bcde

7 

8 

9@pytest.fixture( 1bcde

10 name="mod", 

11 params=[ 

12 pytest.param("tutorial003_py310"), 

13 ], 

14) 

15def get_mod(request: pytest.FixtureRequest): 1bcde

16 mod = importlib.import_module(f"docs_src.websockets_.{request.param}") 1imjnkolp

17 

18 return mod 1imjnkolp

19 

20 

21@pytest.fixture(name="html") 1bcde

22def get_html(mod: ModuleType): 1bcde

23 return mod.html 1ijkl

24 

25 

26@pytest.fixture(name="client") 1bcde

27def get_client(mod: ModuleType): 1bcde

28 client = TestClient(mod.app) 1imjnkolp

29 

30 return client 1imjnkolp

31 

32 

33def test_get(client: TestClient, html: str): 1bcde

34 response = client.get("/") 1qrst

35 assert response.text == html 1qrst

36 

37 

38def test_websocket_handle_disconnection(client: TestClient): 1bcde

39 with ( 1a

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") 1fgha

44 data1 = connection.receive_text() 1fgha

45 assert data1 == "You wrote: Hello from 1234" 1fgha

46 time.sleep(0.01) # Give server time to process broadcast 1fgha

47 data2 = connection_two.receive_text() 1fgha

48 client1_says = "Client #1234 says: Hello from 1234" 1fgha

49 assert data2 == client1_says 1fgha

50 data1 = connection.receive_text() 1fgha

51 assert data1 == client1_says 1fgha

52 connection_two.close() 1fgha

53 time.sleep(0.01) # Give server time to process broadcast 1fgha

54 data1 = connection.receive_text() 1fgha

55 assert data1 == "Client #5678 left the chat" 1fgha