Describe the bug
When working with Security() dependencies, the scopes disappear when app.dependency_overrides is executed. The callable dealing with the scopes gets an empty list instead of the scopes.
To Reproduce
from fastapi import FastAPI, Header, Security, Depends
from fastapi.security import SecurityScopes
from starlette.testclient import TestClient
app = FastAPI()
def get_user(required_scopes: SecurityScopes):
print(required_scopes.scopes)
return "John Doe"
def data():
return [1,2,3]
def other_data():
return [3,4,5]
@app.get("/test")
def test(user: str = Security(get_user, scopes=["foo", "bar"]), data = Depends(data)):
return data
client = TestClient(app)
response = client.get("/test")
app.dependency_overrides[data] = other_data
response = client.get("/test")
# prints: ["foo", "bar"] and [] instead of ["foo", "bar"] and ["foo", "bar"]
Expected behavior
In the above example I expect get_user() to print the same scopes twice. Instead, before the dependency_overrides it prints the correct scpoes, but an empty list afterwards.
Environment:
Hello,
I was reading your comment in the other thread. In my case, I am using dependency_overrides to mock the connection to database.
class TransactionTestCaseMixin:
db_session: Session
@pytest.fixture(autouse=True)
def receive_db_session(self, dbsession: Session):
self.db_session = dbsession
app.dependency_overrides[get_db] = lambda: self.db_session
That's causing us an issue using SecurityScopes when we are testing our service endpoint where we include a Dependant (Security) to manage the permissions of our endpoints.
Thanks for the report @phbender ! :bug: :detective:
This was fixed in https://github.com/tiangolo/fastapi/pull/1549 :rocket:
Released in FastAPI version 0.58.0. :tada:
Assuming the original issue was solved, it will be automatically closed now. But feel free to add more comments or create new issues.
I just ran into this. Thanks for the fix!!
Most helpful comment
I just ran into this. Thanks for the fix!!