Coverage for tests/test_tutorial/test_cors/test_tutorial001.py: 100%

19 statements  

« prev     ^ index     » next       coverage.py v7.6.1, created at 2025-05-05 00:03 +0000

1from fastapi.testclient import TestClient 1ghijkl

2 

3from docs_src.cors.tutorial001 import app 1ghijkl

4 

5 

6def test_cors(): 1ghijkl

7 client = TestClient(app) 1abcdef

8 # Test pre-flight response 

9 headers = { 1abcdef

10 "Origin": "https://localhost.tiangolo.com", 

11 "Access-Control-Request-Method": "GET", 

12 "Access-Control-Request-Headers": "X-Example", 

13 } 

14 response = client.options("/", headers=headers) 1abcdef

15 assert response.status_code == 200, response.text 1abcdef

16 assert response.text == "OK" 1abcdef

17 assert ( 1abcdef

18 response.headers["access-control-allow-origin"] 

19 == "https://localhost.tiangolo.com" 

20 ) 

21 assert response.headers["access-control-allow-headers"] == "X-Example" 1abcdef

22 

23 # Test standard response 

24 headers = {"Origin": "https://localhost.tiangolo.com"} 1abcdef

25 response = client.get("/", headers=headers) 1abcdef

26 assert response.status_code == 200, response.text 1abcdef

27 assert response.json() == {"message": "Hello World"} 1abcdef

28 assert ( 1abcdef

29 response.headers["access-control-allow-origin"] 

30 == "https://localhost.tiangolo.com" 

31 ) 

32 

33 # Test non-CORS response 

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

35 assert response.status_code == 200, response.text 1abcdef

36 assert response.json() == {"message": "Hello World"} 1abcdef

37 assert "access-control-allow-origin" not in response.headers 1abcdef