Coverage for tests / test_security_http_basic_optional.py: 100%

38 statements  

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

1from base64 import b64encode 1abcd

2from typing import Optional 1abcd

3 

4from fastapi import FastAPI, Security 1abcd

5from fastapi.security import HTTPBasic, HTTPBasicCredentials 1abcd

6from fastapi.testclient import TestClient 1abcd

7from inline_snapshot import snapshot 1abcd

8 

9app = FastAPI() 1abcd

10 

11security = HTTPBasic(auto_error=False) 1abcd

12 

13 

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

15def read_current_user(credentials: Optional[HTTPBasicCredentials] = Security(security)): 1abcd

16 if credentials is None: 1hijklm

17 return {"msg": "Create an account first"} 1ikm

18 return {"username": credentials.username, "password": credentials.password} 1hjl

19 

20 

21client = TestClient(app) 1abcd

22 

23 

24def test_security_http_basic(): 1abcd

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

26 assert response.status_code == 200, response.text 1hjl

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

28 

29 

30def test_security_http_basic_no_credentials(): 1abcd

31 response = client.get("/users/me") 1ikm

32 assert response.status_code == 200, response.text 1ikm

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

34 

35 

36def test_security_http_basic_invalid_credentials(): 1abcd

37 response = client.get( 1nop

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

39 ) 

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

41 assert response.headers["WWW-Authenticate"] == "Basic" 1nop

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

43 

44 

45def test_security_http_basic_non_basic_credentials(): 1abcd

46 payload = b64encode(b"johnsecret").decode("ascii") 1efg

47 auth_header = f"Basic {payload}" 1efg

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

49 assert response.status_code == 401, response.text 1efg

50 assert response.headers["WWW-Authenticate"] == "Basic" 1efg

51 assert response.json() == {"detail": "Not authenticated"} 1efg

52 

53 

54def test_openapi_schema(): 1abcd

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

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

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

58 { 

59 "openapi": "3.1.0", 

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

61 "paths": { 

62 "/users/me": { 

63 "get": { 

64 "responses": { 

65 "200": { 

66 "description": "Successful Response", 

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

68 } 

69 }, 

70 "summary": "Read Current User", 

71 "operationId": "read_current_user_users_me_get", 

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

73 } 

74 } 

75 }, 

76 "components": { 

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

78 }, 

79 } 

80 )