Coverage for tests / test_security_oauth2_authorization_code_bearer.py: 100%

30 statements  

« prev     ^ index     » next       coverage.py v7.13.3, created at 2026-04-06 01:24 +0000

1from fastapi import FastAPI, Security 1abcd

2from fastapi.security import OAuth2AuthorizationCodeBearer 1abcd

3from fastapi.testclient import TestClient 1abcd

4from inline_snapshot import snapshot 1abcd

5 

6app = FastAPI() 1abcd

7 

8oauth2_scheme = OAuth2AuthorizationCodeBearer( 1abcd

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

10) 

11 

12 

13@app.get("/items/") 1abcd

14async def read_items(token: str | None = Security(oauth2_scheme)): 1abcd

15 return {"token": token} 1efghijk

16 

17 

18client = TestClient(app) 1abcd

19 

20 

21def test_no_token(): 1abcd

22 response = client.get("/items") 1lmno

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

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

25 

26 

27def test_incorrect_token(): 1abcd

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

29 assert response.status_code == 401, response.text 1pqrs

30 assert response.json() == {"detail": "Not authenticated"} 1pqrs

31 

32 

33def test_token(): 1abcd

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

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

36 assert response.json() == {"token": "testtoken"} 1fgik

37 

38 

39def test_token_with_whitespaces(): 1abcd

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

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

42 assert response.json() == {"token": "testtoken"} 1ethj

43 

44 

45def test_openapi_schema(): 1abcd

46 response = client.get("/openapi.json") 1uvwx

47 assert response.status_code == 200, response.text 1uvwx

48 assert response.json() == snapshot( 1uvwx

49 { 

50 "openapi": "3.1.0", 

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

52 "paths": { 

53 "/items/": { 

54 "get": { 

55 "responses": { 

56 "200": { 

57 "description": "Successful Response", 

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

59 } 

60 }, 

61 "summary": "Read Items", 

62 "operationId": "read_items_items__get", 

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

64 } 

65 } 

66 }, 

67 "components": { 

68 "securitySchemes": { 

69 "OAuth2AuthorizationCodeBearer": { 

70 "type": "oauth2", 

71 "flows": { 

72 "authorizationCode": { 

73 "authorizationUrl": "authorize", 

74 "tokenUrl": "token", 

75 "scopes": {}, 

76 } 

77 }, 

78 } 

79 } 

80 }, 

81 } 

82 )