Coverage for tests/test_tutorial/test_security/test_tutorial006_an_py39.py: 100%

39 statements  

« prev     ^ index     » next       coverage.py v7.6.1, created at 2024-08-08 03:53 +0000

1from base64 import b64encode 1eabcd

2 

3import pytest 1eabcd

4from fastapi.testclient import TestClient 1eabcd

5 

6from ...utils import needs_py39 1eabcd

7 

8 

9@pytest.fixture(name="client") 1eabcd

10def get_client(): 1eabcd

11 from docs_src.security.tutorial006_an import app 1abcd

12 

13 client = TestClient(app) 1abcd

14 return client 1abcd

15 

16 

17@needs_py39 1eabcd

18def test_security_http_basic(client: TestClient): 1eabcd

19 response = client.get("/users/me", auth=("john", "secret")) 1abcd

20 assert response.status_code == 200, response.text 1abcd

21 assert response.json() == {"username": "john", "password": "secret"} 1abcd

22 

23 

24@needs_py39 1eabcd

25def test_security_http_basic_no_credentials(client: TestClient): 1eabcd

26 response = client.get("/users/me") 1abcd

27 assert response.json() == {"detail": "Not authenticated"} 1abcd

28 assert response.status_code == 401, response.text 1abcd

29 assert response.headers["WWW-Authenticate"] == "Basic" 1abcd

30 

31 

32@needs_py39 1eabcd

33def test_security_http_basic_invalid_credentials(client: TestClient): 1eabcd

34 response = client.get( 1abcd

35 "/users/me", headers={"Authorization": "Basic notabase64token"} 

36 ) 

37 assert response.status_code == 401, response.text 1abcd

38 assert response.headers["WWW-Authenticate"] == "Basic" 1abcd

39 assert response.json() == {"detail": "Invalid authentication credentials"} 1abcd

40 

41 

42@needs_py39 1eabcd

43def test_security_http_basic_non_basic_credentials(client: TestClient): 1eabcd

44 payload = b64encode(b"johnsecret").decode("ascii") 1abcd

45 auth_header = f"Basic {payload}" 1abcd

46 response = client.get("/users/me", headers={"Authorization": auth_header}) 1abcd

47 assert response.status_code == 401, response.text 1abcd

48 assert response.headers["WWW-Authenticate"] == "Basic" 1abcd

49 assert response.json() == {"detail": "Invalid authentication credentials"} 1abcd

50 

51 

52@needs_py39 1eabcd

53def test_openapi_schema(client: TestClient): 1eabcd

54 response = client.get("/openapi.json") 1abcd

55 assert response.status_code == 200, response.text 1abcd

56 assert response.json() == { 1abcd

57 "openapi": "3.1.0", 

58 "info": {"title": "FastAPI", "version": "0.1.0"}, 

59 "paths": { 

60 "/users/me": { 

61 "get": { 

62 "responses": { 

63 "200": { 

64 "description": "Successful Response", 

65 "content": {"application/json": {"schema": {}}}, 

66 } 

67 }, 

68 "summary": "Read Current User", 

69 "operationId": "read_current_user_users_me_get", 

70 "security": [{"HTTPBasic": []}], 

71 } 

72 } 

73 }, 

74 "components": { 

75 "securitySchemes": {"HTTPBasic": {"type": "http", "scheme": "basic"}} 

76 }, 

77 }