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

30 statements  

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

1import pytest 1eabcd

2from fastapi.testclient import TestClient 1eabcd

3 

4from ...utils import needs_py39 1eabcd

5 

6 

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

8def get_client(): 1eabcd

9 from docs_src.security.tutorial001_an_py39 import app 1abcd

10 

11 client = TestClient(app) 1abcd

12 return client 1abcd

13 

14 

15@needs_py39 1eabcd

16def test_no_token(client: TestClient): 1eabcd

17 response = client.get("/items") 1abcd

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

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

20 assert response.headers["WWW-Authenticate"] == "Bearer" 1abcd

21 

22 

23@needs_py39 1eabcd

24def test_token(client: TestClient): 1eabcd

25 response = client.get("/items", headers={"Authorization": "Bearer testtoken"}) 1abcd

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

27 assert response.json() == {"token": "testtoken"} 1abcd

28 

29 

30@needs_py39 1eabcd

31def test_incorrect_token(client: TestClient): 1eabcd

32 response = client.get("/items", headers={"Authorization": "Notexistent testtoken"}) 1abcd

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

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

35 assert response.headers["WWW-Authenticate"] == "Bearer" 1abcd

36 

37 

38@needs_py39 1eabcd

39def test_openapi_schema(client: TestClient): 1eabcd

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

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

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

43 "openapi": "3.1.0", 

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

45 "paths": { 

46 "/items/": { 

47 "get": { 

48 "responses": { 

49 "200": { 

50 "description": "Successful Response", 

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

52 } 

53 }, 

54 "summary": "Read Items", 

55 "operationId": "read_items_items__get", 

56 "security": [{"OAuth2PasswordBearer": []}], 

57 } 

58 } 

59 }, 

60 "components": { 

61 "securitySchemes": { 

62 "OAuth2PasswordBearer": { 

63 "type": "oauth2", 

64 "flows": {"password": {"scopes": {}, "tokenUrl": "token"}}, 

65 } 

66 } 

67 }, 

68 }