Coverage for tests / test_security_oauth2_authorization_code_bearer_description.py: 100%

27 statements  

« prev     ^ index     » next       coverage.py v7.13.3, created at 2026-02-12 18:15 +0000

1from typing import Optional 1abcd

2 

3from fastapi import FastAPI, Security 1abcd

4from fastapi.security import OAuth2AuthorizationCodeBearer 1abcd

5from fastapi.testclient import TestClient 1abcd

6from inline_snapshot import snapshot 1abcd

7 

8app = FastAPI() 1abcd

9 

10oauth2_scheme = OAuth2AuthorizationCodeBearer( 1abcd

11 authorizationUrl="authorize", 

12 tokenUrl="token", 

13 description="OAuth2 Code Bearer", 

14 auto_error=True, 

15) 

16 

17 

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

19async def read_items(token: Optional[str] = Security(oauth2_scheme)): 1abcd

20 return {"token": token} 1efg

21 

22 

23client = TestClient(app) 1abcd

24 

25 

26def test_no_token(): 1abcd

27 response = client.get("/items") 1hij

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

29 assert response.json() == {"detail": "Not authenticated"} 1hij

30 

31 

32def test_incorrect_token(): 1abcd

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

34 assert response.status_code == 401, response.text 1klm

35 assert response.json() == {"detail": "Not authenticated"} 1klm

36 

37 

38def test_token(): 1abcd

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

40 assert response.status_code == 200, response.text 1efg

41 assert response.json() == {"token": "testtoken"} 1efg

42 

43 

44def test_openapi_schema(): 1abcd

45 response = client.get("/openapi.json") 1nop

46 assert response.status_code == 200, response.text 1nop

47 assert response.json() == snapshot( 1nop

48 { 

49 "openapi": "3.1.0", 

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

51 "paths": { 

52 "/items/": { 

53 "get": { 

54 "responses": { 

55 "200": { 

56 "description": "Successful Response", 

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

58 } 

59 }, 

60 "summary": "Read Items", 

61 "operationId": "read_items_items__get", 

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

63 } 

64 } 

65 }, 

66 "components": { 

67 "securitySchemes": { 

68 "OAuth2AuthorizationCodeBearer": { 

69 "type": "oauth2", 

70 "flows": { 

71 "authorizationCode": { 

72 "authorizationUrl": "authorize", 

73 "tokenUrl": "token", 

74 "scopes": {}, 

75 } 

76 }, 

77 "description": "OAuth2 Code Bearer", 

78 } 

79 } 

80 }, 

81 } 

82 )