Browse Source

Refactor test to avoid mocking

pull/5624/head
Sebastián Ramírez 8 months ago
parent
commit
b9fffb72b4
  1. 53
      tests/test_dependency_scopes.py

53
tests/test_dependency_scopes.py

@ -1,58 +1,45 @@
from unittest.mock import Mock, call, patch
# Ref: https://github.com/tiangolo/fastapi/issues/5623
from typing import Any, Dict, List
import pytest
from fastapi import FastAPI, Security
from fastapi.security import SecurityScopes
from fastapi.testclient import TestClient
from typing_extensions import Annotated
async def security1(scopes: SecurityScopes):
return _security1(scopes.scopes)
def _security1(scopes): # pragma: no cover
pass
return scopes.scopes
async def security2(scopes: SecurityScopes):
return _security2(scopes.scopes)
def _security2(scopes): # pragma: no cover
pass
return scopes.scopes
async def dep3(
dep=Security(security1, scopes=["scope1"]),
dep2=Security(security2, scopes=["scope2"]),
dep1: Annotated[List[str], Security(security1, scopes=["scope1"])],
dep2: Annotated[List[str], Security(security2, scopes=["scope2"])],
):
return {}
@pytest.fixture
def mocks():
with patch.dict(globals(), {"_security1": Mock()}):
with patch.dict(globals(), {"_security2": Mock()}):
yield
return {"dep1": dep1, "dep2": dep2}
app = FastAPI()
@app.get("/recursive_scopes")
def recursive_scopes(dep=Security(dep3, scopes=["scope3"])):
return {}
def recursive_scopes(
dep3: Annotated[Dict[str, Any], Security(dep3, scopes=["scope3"])],
):
return dep3
client = TestClient(app)
# issue https://github.com/tiangolo/fastapi/issues/5623
def test_recursive_scopes(mocks):
"""
Test that scope recursion properly applies. Scopes added to a dependency should propagate
and be prepended correctly to all sub-dependencies.
"""
client.get("recursive_scopes")
_security1.assert_has_calls([call(["scope3", "scope1"])])
_security2.assert_has_calls([call(["scope3", "scope2"])])
def test_recursive_scopes():
response = client.get("recursive_scopes")
assert response.status_code == 200
assert response.json() == {
"dep1": ["scope3", "scope1"],
"dep2": ["scope3", "scope2"],
}

Loading…
Cancel
Save