Coverage for tests/test_security_http_basic_realm.py: 100%

35 statements  

« prev     ^ index     » next       coverage.py v7.6.1, created at 2024-08-08 03:53 +0000

1from base64 import b64encode 1abcde

2 

3from fastapi import FastAPI, Security 1abcde

4from fastapi.security import HTTPBasic, HTTPBasicCredentials 1abcde

5from fastapi.testclient import TestClient 1abcde

6 

7app = FastAPI() 1abcde

8 

9security = HTTPBasic(realm="simple") 1abcde

10 

11 

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

13def read_current_user(credentials: HTTPBasicCredentials = Security(security)): 1abcde

14 return {"username": credentials.username, "password": credentials.password} 1abcde

15 

16 

17client = TestClient(app) 1abcde

18 

19 

20def test_security_http_basic(): 1abcde

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

22 assert response.status_code == 200, response.text 1abcde

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

24 

25 

26def test_security_http_basic_no_credentials(): 1abcde

27 response = client.get("/users/me") 1abcde

28 assert response.json() == {"detail": "Not authenticated"} 1abcde

29 assert response.status_code == 401, response.text 1abcde

30 assert response.headers["WWW-Authenticate"] == 'Basic realm="simple"' 1abcde

31 

32 

33def test_security_http_basic_invalid_credentials(): 1abcde

34 response = client.get( 1abcde

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

36 ) 

37 assert response.status_code == 401, response.text 1abcde

38 assert response.headers["WWW-Authenticate"] == 'Basic realm="simple"' 1abcde

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

40 

41 

42def test_security_http_basic_non_basic_credentials(): 1abcde

43 payload = b64encode(b"johnsecret").decode("ascii") 1abcde

44 auth_header = f"Basic {payload}" 1abcde

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

46 assert response.status_code == 401, response.text 1abcde

47 assert response.headers["WWW-Authenticate"] == 'Basic realm="simple"' 1abcde

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

49 

50 

51def test_openapi_schema(): 1abcde

52 response = client.get("/openapi.json") 1abcde

53 assert response.status_code == 200, response.text 1abcde

54 assert response.json() == { 1abcde

55 "openapi": "3.1.0", 

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

57 "paths": { 

58 "/users/me": { 

59 "get": { 

60 "responses": { 

61 "200": { 

62 "description": "Successful Response", 

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

64 } 

65 }, 

66 "summary": "Read Current User", 

67 "operationId": "read_current_user_users_me_get", 

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

69 } 

70 } 

71 }, 

72 "components": { 

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

74 }, 

75 }