|
|
@ -1,9 +1,27 @@ |
|
|
|
from fastapi import Depends, FastAPI, Security |
|
|
|
from fastapi._compat import PYDANTIC_V2 |
|
|
|
from fastapi.testclient import TestClient |
|
|
|
from pydantic import BaseModel |
|
|
|
|
|
|
|
app = FastAPI() |
|
|
|
|
|
|
|
counter_holder = {"counter": 0} |
|
|
|
counter_holder = {"counter": 0, "parsing_counter": 0} |
|
|
|
|
|
|
|
if PYDANTIC_V2: |
|
|
|
from pydantic import model_validator |
|
|
|
|
|
|
|
decorator = model_validator(mode="before") |
|
|
|
else: |
|
|
|
from pydantic import root_validator |
|
|
|
|
|
|
|
decorator = root_validator |
|
|
|
|
|
|
|
|
|
|
|
class Model(BaseModel): |
|
|
|
@decorator |
|
|
|
def __validate__(cls, _): |
|
|
|
counter_holder["parsing_counter"] += 1 |
|
|
|
return {} |
|
|
|
|
|
|
|
|
|
|
|
async def dep_counter(): |
|
|
@ -15,6 +33,10 @@ async def super_dep(count: int = Depends(dep_counter)): |
|
|
|
return count |
|
|
|
|
|
|
|
|
|
|
|
async def model_dep(model: Model) -> Model: |
|
|
|
return model |
|
|
|
|
|
|
|
|
|
|
|
@app.get("/counter/") |
|
|
|
async def get_counter(count: int = Depends(dep_counter)): |
|
|
|
return {"counter": count} |
|
|
@ -35,6 +57,15 @@ async def get_sub_counter_no_cache( |
|
|
|
return {"counter": count, "subcounter": subcount} |
|
|
|
|
|
|
|
|
|
|
|
@app.post("/sub-model-parsing/") |
|
|
|
async def get_double_model_parsing( |
|
|
|
a: Model = Depends(model_dep), |
|
|
|
b: Model = Depends(model_dep), |
|
|
|
): |
|
|
|
assert a is b |
|
|
|
return {"parsing_counter": counter_holder["parsing_counter"]} |
|
|
|
|
|
|
|
|
|
|
|
@app.get("/scope-counter") |
|
|
|
async def get_scope_counter( |
|
|
|
count: int = Security(dep_counter), |
|
|
@ -81,6 +112,13 @@ def test_sub_counter_no_cache(): |
|
|
|
assert response.json() == {"counter": 4, "subcounter": 3} |
|
|
|
|
|
|
|
|
|
|
|
def test_sub_model_parsing_no_repeatable_parsing(): |
|
|
|
counter_holder["parsing_counter"] = 0 |
|
|
|
response = client.post("/sub-model-parsing/", json={}) |
|
|
|
assert response.status_code == 200, response.text |
|
|
|
assert response.json() == {"parsing_counter": 1} |
|
|
|
|
|
|
|
|
|
|
|
def test_security_cache(): |
|
|
|
counter_holder["counter"] = 0 |
|
|
|
response = client.get("/scope-counter/") |
|
|
|