Coverage for tests/test_security_oauth2_authorization_code_bearer.py: 100%

26 statements  

« prev     ^ index     » next       coverage.py v7.6.1, created at 2025-12-04 08:29 +0000

1from typing import Optional 1abcdefg

2 

3from fastapi import FastAPI, Security 1abcdefg

4from fastapi.security import OAuth2AuthorizationCodeBearer 1abcdefg

5from fastapi.testclient import TestClient 1abcdefg

6 

7app = FastAPI() 1abcdefg

8 

9oauth2_scheme = OAuth2AuthorizationCodeBearer( 1abcdefg

10 authorizationUrl="authorize", tokenUrl="token", auto_error=True 

11) 

12 

13 

14@app.get("/items/") 1abcdefg

15async def read_items(token: Optional[str] = Security(oauth2_scheme)): 1abcdefg

16 return {"token": token} 1hijklmn

17 

18 

19client = TestClient(app) 1abcdefg

20 

21 

22def test_no_token(): 1abcdefg

23 response = client.get("/items") 1opqrstu

24 assert response.status_code == 401, response.text 1opqrstu

25 assert response.json() == {"detail": "Not authenticated"} 1opqrstu

26 

27 

28def test_incorrect_token(): 1abcdefg

29 response = client.get("/items", headers={"Authorization": "Non-existent testtoken"}) 1vwxyzAB

30 assert response.status_code == 401, response.text 1vwxyzAB

31 assert response.json() == {"detail": "Not authenticated"} 1vwxyzAB

32 

33 

34def test_token(): 1abcdefg

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

36 assert response.status_code == 200, response.text 1hijklmn

37 assert response.json() == {"token": "testtoken"} 1hijklmn

38 

39 

40def test_openapi_schema(): 1abcdefg

41 response = client.get("/openapi.json") 1CDEFGHI

42 assert response.status_code == 200, response.text 1CDEFGHI

43 assert response.json() == { 1CDEFGHI

44 "openapi": "3.1.0", 

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

46 "paths": { 

47 "/items/": { 

48 "get": { 

49 "responses": { 

50 "200": { 

51 "description": "Successful Response", 

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

53 } 

54 }, 

55 "summary": "Read Items", 

56 "operationId": "read_items_items__get", 

57 "security": [{"OAuth2AuthorizationCodeBearer": []}], 

58 } 

59 } 

60 }, 

61 "components": { 

62 "securitySchemes": { 

63 "OAuth2AuthorizationCodeBearer": { 

64 "type": "oauth2", 

65 "flows": { 

66 "authorizationCode": { 

67 "authorizationUrl": "authorize", 

68 "tokenUrl": "token", 

69 "scopes": {}, 

70 } 

71 }, 

72 } 

73 } 

74 }, 

75 }