Coverage for tests / test_security_oauth2_authorization_code_bearer.py: 100%

31 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", tokenUrl="token", auto_error=True 

12) 

13 

14 

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

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

17 return {"token": token} 1efghij

18 

19 

20client = TestClient(app) 1abcd

21 

22 

23def test_no_token(): 1abcd

24 response = client.get("/items") 1klm

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

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

27 

28 

29def test_incorrect_token(): 1abcd

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

31 assert response.status_code == 401, response.text 1nop

32 assert response.json() == {"detail": "Not authenticated"} 1nop

33 

34 

35def test_token(): 1abcd

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

37 assert response.status_code == 200, response.text 1egi

38 assert response.json() == {"token": "testtoken"} 1egi

39 

40 

41def test_token_with_whitespaces(): 1abcd

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

43 assert response.status_code == 200, response.text 1fhj

44 assert response.json() == {"token": "testtoken"} 1fhj

45 

46 

47def test_openapi_schema(): 1abcd

48 response = client.get("/openapi.json") 1qrs

49 assert response.status_code == 200, response.text 1qrs

50 assert response.json() == snapshot( 1qrs

51 { 

52 "openapi": "3.1.0", 

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

54 "paths": { 

55 "/items/": { 

56 "get": { 

57 "responses": { 

58 "200": { 

59 "description": "Successful Response", 

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

61 } 

62 }, 

63 "summary": "Read Items", 

64 "operationId": "read_items_items__get", 

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

66 } 

67 } 

68 }, 

69 "components": { 

70 "securitySchemes": { 

71 "OAuth2AuthorizationCodeBearer": { 

72 "type": "oauth2", 

73 "flows": { 

74 "authorizationCode": { 

75 "authorizationUrl": "authorize", 

76 "tokenUrl": "token", 

77 "scopes": {}, 

78 } 

79 }, 

80 } 

81 } 

82 }, 

83 } 

84 )