Coverage for tests/test_security_http_basic_optional.py: 100%

37 statements  

« prev     ^ index     » next       coverage.py v7.6.1, created at 2025-01-13 13:38 +0000

1from base64 import b64encode 1abcde

2from typing import Optional 1abcde

3 

4from fastapi import FastAPI, Security 1abcde

5from fastapi.security import HTTPBasic, HTTPBasicCredentials 1abcde

6from fastapi.testclient import TestClient 1abcde

7 

8app = FastAPI() 1abcde

9 

10security = HTTPBasic(auto_error=False) 1abcde

11 

12 

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

14def read_current_user(credentials: Optional[HTTPBasicCredentials] = Security(security)): 1abcde

15 if credentials is None: 1klmnopqrst

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

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

18 

19 

20client = TestClient(app) 1abcde

21 

22 

23def test_security_http_basic(): 1abcde

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

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

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

27 

28 

29def test_security_http_basic_no_credentials(): 1abcde

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

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

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

33 

34 

35def test_security_http_basic_invalid_credentials(): 1abcde

36 response = client.get( 1uvwxy

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

38 ) 

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

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

41 assert response.json() == {"detail": "Invalid authentication credentials"} 1uvwxy

42 

43 

44def test_security_http_basic_non_basic_credentials(): 1abcde

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

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

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

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

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

50 assert response.json() == {"detail": "Invalid authentication credentials"} 1fghij

51 

52 

53def test_openapi_schema(): 1abcde

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

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

56 assert response.json() == { 1zABCD

57 "openapi": "3.1.0", 

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

59 "paths": { 

60 "/users/me": { 

61 "get": { 

62 "responses": { 

63 "200": { 

64 "description": "Successful Response", 

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

66 } 

67 }, 

68 "summary": "Read Current User", 

69 "operationId": "read_current_user_users_me_get", 

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

71 } 

72 } 

73 }, 

74 "components": { 

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

76 }, 

77 }