From 005d6e4b85cbddfc42360f5018ec9ca556ffe6ff Mon Sep 17 00:00:00 2001 From: Joao-Pedro-P-Holanda Date: Thu, 13 Feb 2025 18:53:01 -0300 Subject: [PATCH] test: adding tests to security scopes verification adding tests to validate an user scope created with a simple string or a list of strings --- tests/test_security_oauth2_scopes.py | 54 ++++++++++++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 tests/test_security_oauth2_scopes.py diff --git a/tests/test_security_oauth2_scopes.py b/tests/test_security_oauth2_scopes.py new file mode 100644 index 000000000..690ccca8a --- /dev/null +++ b/tests/test_security_oauth2_scopes.py @@ -0,0 +1,54 @@ +from typing import Annotated +from fastapi import FastAPI, Security +from fastapi.params import Depends +from fastapi.security import OAuth2PasswordBearer +from fastapi.security.oauth2 import SecurityScopes +from fastapi.testclient import TestClient + +app = FastAPI() + +oauth2_scheme = OAuth2PasswordBearer( + tokenUrl="token", + scopes={"me": "Read information about the current user.", "items": "Read items."}, +) + + +def get_security_scopes( + security_scopes: SecurityScopes, token: Annotated[str, Depends(oauth2_scheme)] +): + return security_scopes.scopes + + +@app.get("/me") +async def read_single_scope( + current_scope: Annotated[list[str], Security(get_security_scopes, scopes="me")], +): + return {"scopes": current_scope} + + +@app.get("/me-and-items") +async def read_single_scope( + current_scope: Annotated[ + list[str], Security(get_security_scopes, scopes=["me", "items"]) + ], +): + return {"scopes": current_scope} + + +client = TestClient(app) + + +def test_single_scope_string(): + response = client.get("/me", headers={"Authorization": "Bearer sometoken"}) + + assert response.status_code == 200 + assert response.json() == {"scopes": ["me"]} + + +def test_list_scopes(): + response = client.get( + "/me-and-items", headers={"Authorization": "Bearer sometoken"} + ) + + assert response.status_code == 200 + assert response.json() == {"scopes": ["me", "items"]}