Coverage for tests / test_security_http_basic_optional.py: 100%

37 statements  

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

1from base64 import b64encode 1abcd

2 

3from fastapi import FastAPI, Security 1abcd

4from fastapi.security import HTTPBasic, HTTPBasicCredentials 1abcd

5from fastapi.testclient import TestClient 1abcd

6from inline_snapshot import snapshot 1abcd

7 

8app = FastAPI() 1abcd

9 

10security = HTTPBasic(auto_error=False) 1abcd

11 

12 

13@app.get("/users/me") 1abcd

14def read_current_user(credentials: HTTPBasicCredentials | None = Security(security)): 1abcd

15 if credentials is None: 1ijklmno

16 return {"msg": "Create an account first"} 1ipln

17 return {"username": credentials.username, "password": credentials.password} 1jkmo

18 

19 

20client = TestClient(app) 1abcd

21 

22 

23def test_security_http_basic(): 1abcd

24 response = client.get("/users/me", auth=("john", "secret")) 1jkmo

25 assert response.status_code == 200, response.text 1jkmo

26 assert response.json() == {"username": "john", "password": "secret"} 1jkmo

27 

28 

29def test_security_http_basic_no_credentials(): 1abcd

30 response = client.get("/users/me") 1ipln

31 assert response.status_code == 200, response.text 1ipln

32 assert response.json() == {"msg": "Create an account first"} 1ipln

33 

34 

35def test_security_http_basic_invalid_credentials(): 1abcd

36 response = client.get( 1qrst

37 "/users/me", headers={"Authorization": "Basic notabase64token"} 

38 ) 

39 assert response.status_code == 401, response.text 1qrst

40 assert response.headers["WWW-Authenticate"] == "Basic" 1qrst

41 assert response.json() == {"detail": "Not authenticated"} 1qrst

42 

43 

44def test_security_http_basic_non_basic_credentials(): 1abcd

45 payload = b64encode(b"johnsecret").decode("ascii") 1efgh

46 auth_header = f"Basic {payload}" 1efgh

47 response = client.get("/users/me", headers={"Authorization": auth_header}) 1efgh

48 assert response.status_code == 401, response.text 1efgh

49 assert response.headers["WWW-Authenticate"] == "Basic" 1efgh

50 assert response.json() == {"detail": "Not authenticated"} 1efgh

51 

52 

53def test_openapi_schema(): 1abcd

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

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

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

57 { 

58 "openapi": "3.1.0", 

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

60 "paths": { 

61 "/users/me": { 

62 "get": { 

63 "responses": { 

64 "200": { 

65 "description": "Successful Response", 

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

67 } 

68 }, 

69 "summary": "Read Current User", 

70 "operationId": "read_current_user_users_me_get", 

71 "security": [{"HTTPBasic": []}], 

72 } 

73 } 

74 }, 

75 "components": { 

76 "securitySchemes": {"HTTPBasic": {"type": "http", "scheme": "basic"}} 

77 }, 

78 } 

79 )