From 9e4ce1ea0f0ad8b113443aa9fc01712e8b6a815b Mon Sep 17 00:00:00 2001 From: Gustav Bylund Date: Wed, 19 Feb 2025 22:22:49 +0100 Subject: [PATCH] test(dependency_cache): add test for repeated parsing --- tests/test_dependency_cache.py | 40 +++++++++++++++++++++++++++++++++- 1 file changed, 39 insertions(+), 1 deletion(-) diff --git a/tests/test_dependency_cache.py b/tests/test_dependency_cache.py index 08fb9b74f..cda3ec7b9 100644 --- a/tests/test_dependency_cache.py +++ b/tests/test_dependency_cache.py @@ -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/")