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

21 statements  

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

1from fastapi.testclient import TestClient 1abcde

2 

3from docs_src.security.tutorial001_an import app 1abcde

4 

5client = TestClient(app) 1abcde

6 

7 

8def test_no_token(): 1abcde

9 response = client.get("/items") 1abcde

10 assert response.status_code == 401, response.text 1abcde

11 assert response.json() == {"detail": "Not authenticated"} 1abcde

12 assert response.headers["WWW-Authenticate"] == "Bearer" 1abcde

13 

14 

15def test_token(): 1abcde

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

17 assert response.status_code == 200, response.text 1abcde

18 assert response.json() == {"token": "testtoken"} 1abcde

19 

20 

21def test_incorrect_token(): 1abcde

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

23 assert response.status_code == 401, response.text 1abcde

24 assert response.json() == {"detail": "Not authenticated"} 1abcde

25 assert response.headers["WWW-Authenticate"] == "Bearer" 1abcde

26 

27 

28def test_openapi_schema(): 1abcde

29 response = client.get("/openapi.json") 1abcde

30 assert response.status_code == 200, response.text 1abcde

31 assert response.json() == { 1abcde

32 "openapi": "3.1.0", 

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

34 "paths": { 

35 "/items/": { 

36 "get": { 

37 "responses": { 

38 "200": { 

39 "description": "Successful Response", 

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

41 } 

42 }, 

43 "summary": "Read Items", 

44 "operationId": "read_items_items__get", 

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

46 } 

47 } 

48 }, 

49 "components": { 

50 "securitySchemes": { 

51 "OAuth2PasswordBearer": { 

52 "type": "oauth2", 

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

54 } 

55 } 

56 }, 

57 }