Buckets:
AnonymousSpottedToad/human_verified_bucket / codebase /python /allen0099_FastAPI-CacheX /tests /test_cache.py
| import pytest | |
| from fastapi import FastAPI | |
| from fastapi import Response | |
| from fastapi.testclient import TestClient | |
| from starlette.requests import Request | |
| from starlette.responses import HTMLResponse | |
| from starlette.responses import JSONResponse | |
| from starlette.responses import PlainTextResponse | |
| from starlette.responses import StreamingResponse | |
| from fastapi_cachex.backends.memory import MemoryBackend | |
| from fastapi_cachex.cache import cache | |
| from fastapi_cachex.exceptions import CacheXError | |
| from fastapi_cachex.proxy import BackendProxy | |
| from fastapi_cachex.types import CacheEntry | |
| app = FastAPI() | |
| client = TestClient(app) | |
| def test_default_cache(): | |
| async def default_cache_endpoint(): | |
| return Response( | |
| content=b'{"message": "This is a default cache endpoint"}', | |
| media_type="application/json", | |
| ) | |
| response = client.get("/default") | |
| assert response.status_code == 200 | |
| assert response.headers["Cache-Control"] == "" | |
| assert "ETag" in response.headers | |
| def test_cache_with_ttl(): | |
| async def cache_with_ttl_endpoint(): | |
| return Response( | |
| content=b'{"message": "This endpoint has a TTL of 30 seconds"}', | |
| media_type="application/json", | |
| ) | |
| response = client.get("/cache-with-ttl") | |
| assert response.status_code == 200 | |
| assert response.headers["Cache-Control"] == "max-age=3" | |
| assert "ETag" in response.headers | |
| response2 = client.get( | |
| "/cache-with-ttl", | |
| headers={"If-None-Match": response.headers["ETag"]}, | |
| ) | |
| assert response2.status_code == 304 | |
| assert response2.headers["Cache-Control"] == "max-age=3" | |
| assert response2.headers["ETag"] == response.headers["ETag"] | |
| def test_ttl_endpoint(): | |
| async def ttl_endpoint(): | |
| return Response( | |
| content=b'{"message": "This endpoint has a TTL of 60 seconds"}', | |
| media_type="application/json", | |
| ) | |
| response = client.get("/ttl") | |
| assert response.status_code == 200 | |
| assert response.headers["Cache-Control"] == "max-age=60" | |
| def test_no_cache_endpoint(): | |
| async def no_cache_endpoint(): | |
| return Response( | |
| content=b'{"message": "This endpoint should not be cached"}', | |
| media_type="application/json", | |
| ) | |
| response = client.get("/no-cache") | |
| assert response.status_code == 200 | |
| assert response.headers["Cache-Control"] == "no-cache" | |
| def test_no_store_endpoint(): | |
| async def no_store_endpoint(): | |
| return Response( | |
| content=b'{"message": "This endpoint must not be stored"}', | |
| media_type="application/json", | |
| ) | |
| response = client.get("/no-store") | |
| assert response.status_code == 200 | |
| assert response.headers["Cache-Control"] == "no-store" | |
| def test_public_private_endpoints(): | |
| async def public_endpoint(): | |
| return Response( | |
| content=b'{"message": "This is a public endpoint"}', | |
| media_type="application/json", | |
| ) | |
| async def private_endpoint(): | |
| return Response( | |
| content=b'{"message": "This is a private endpoint"}', | |
| media_type="application/json", | |
| ) | |
| public_response = client.get("/public") | |
| assert public_response.status_code == 200 | |
| assert "public" in public_response.headers["Cache-Control"].lower() | |
| private_response = client.get("/private") | |
| assert private_response.status_code == 200 | |
| assert "private" in private_response.headers["Cache-Control"].lower() | |
| def test_etag_handling(): | |
| async def etag_endpoint(): | |
| return Response( | |
| content=b'{"message": "This endpoint supports ETag"}', | |
| media_type="application/json", | |
| ) | |
| # First request - should get the full response | |
| response1 = client.get("/etag") | |
| assert response1.status_code == 200 | |
| assert "ETag" in response1.headers | |
| # Second request with If-None-Match header | |
| etag = response1.headers["ETag"] | |
| response2 = client.get("/etag", headers={"If-None-Match": etag}) | |
| assert response2.status_code == 304 # Not Modified | |
| def test_stale_responses(): | |
| async def stale_while_revalidate_endpoint(): | |
| return Response( | |
| content=b'{"message": "This endpoint allows stale content while revalidating"}', | |
| media_type="application/json", | |
| ) | |
| async def stale_if_error_endpoint(): | |
| return Response( | |
| content=b'{"message": "This endpoint allows stale content on error"}', | |
| media_type="application/json", | |
| ) | |
| response1 = client.get("/stale-while-revalidate") | |
| assert response1.status_code == 200 | |
| assert "stale-while-revalidate=30" in response1.headers["Cache-Control"] | |
| response2 = client.get("/stale-if-error") | |
| assert response2.status_code == 200 | |
| assert "stale-if-error=60" in response2.headers["Cache-Control"] | |
| def test_broken_stale(): | |
| with pytest.raises(CacheXError, match="stale_ttl must be set if stale is used"): | |
| async def stale_broken_endpoint(): | |
| return Response( | |
| content=b'{"message": "This endpoint allows stale content"}', | |
| media_type="application/json", | |
| ) | |
| def test_positional_args(): | |
| async def positional_args_endpoint(arg: str, *, name: str = "default"): | |
| return Response( | |
| content=b'{"message": "This endpoint uses positional args"}', | |
| media_type="application/json", | |
| ) | |
| response = client.get("/positional-args/test") | |
| assert response.status_code == 200 | |
| def test_sync_endpoint(): | |
| def sync_endpoint(): | |
| return Response( | |
| content=b'{"message": "This is a synchronous endpoint"}', | |
| media_type="application/json", | |
| ) | |
| response = client.get("/sync") | |
| assert response.status_code == 200 | |
| def test_no_cache_with_revalidate(): | |
| async def no_cache_revalidate_endpoint(): | |
| return Response( | |
| content=b'{"message": "This endpoint should not be cached but must revalidate"}', | |
| media_type="application/json", | |
| ) | |
| response = client.get("/no-cache-revalidate") | |
| assert response.status_code == 200 | |
| assert response.headers["Cache-Control"] == "no-cache, must-revalidate" | |
| def test_must_revalidate_endpoint(): | |
| async def must_revalidate_endpoint(): | |
| return Response( | |
| content=b'{"message": "This endpoint must revalidate"}', | |
| media_type="application/json", | |
| ) | |
| response = client.get("/must-revalidate") | |
| assert response.status_code == 200 | |
| assert response.headers["Cache-Control"] == "must-revalidate" | |
| def test_immutable_endpoint(): | |
| async def immutable_endpoint(): | |
| return Response( | |
| content=b'{"message": "This endpoint is immutable"}', | |
| media_type="application/json", | |
| ) | |
| response = client.get("/immutable") | |
| assert response.status_code == 200 | |
| assert response.headers["Cache-Control"] == "immutable" | |
| def test_json_response(): | |
| async def json_response_endpoint(): | |
| return JSONResponse( | |
| content={"message": "This is a JSON response"}, | |
| media_type="application/json", | |
| ) | |
| response = client.get("/json-response") | |
| assert response.status_code == 200 | |
| def test_param_var_keyword(): | |
| async def param_keyword_endpoint(param: str = "default"): | |
| return Response( | |
| content=b'{"message": "This endpoint uses param and keyword"}', | |
| media_type="application/json", | |
| ) | |
| response = client.get("/param-keyword?param=test&keyword=value") | |
| assert response.status_code == 200 | |
| def test_contain_request(): | |
| async def contain_request_endpoint(request: Request): | |
| return Response( | |
| content=b'{"message": "This endpoint contains request"}', | |
| media_type="application/json", | |
| ) | |
| response = client.get("/contain-request") | |
| assert response.status_code == 200 | |
| assert "ETag" in response.headers | |
| def test_post_should_not_cache(): | |
| async def post_endpoint(): | |
| return Response( | |
| content=b'{"message": "This is a POST endpoint"}', | |
| media_type="application/json", | |
| ) | |
| response = client.post("/post") | |
| assert response.status_code == 200 | |
| assert "cache-control" not in response.headers | |
| def test_use_default_response_class(): | |
| async def default_response_class_endpoint(): | |
| return {"message": "This endpoint uses the default response class"} | |
| response = client.get("/") | |
| assert response.status_code == 200 | |
| assert response.headers["content-type"] == "application/json" | |
| def test_use_configured_default_response_class(): | |
| custom_app = FastAPI(default_response_class=PlainTextResponse) | |
| async def configured_default_response_class_endpoint(): | |
| return "This endpoint uses the configured default response class" | |
| response = TestClient(custom_app).get("/") | |
| assert response.status_code == 200 | |
| assert response.headers["content-type"] == "text/plain; charset=utf-8" | |
| def test_response_class_html(): | |
| async def html_endpoint(): | |
| return "<h1>Hello World</h1>" | |
| response = client.get("/html") | |
| assert response.status_code == 200 | |
| assert response.headers["content-type"] == "text/html; charset=utf-8" | |
| assert response.text == "<h1>Hello World</h1>" | |
| def test_response_class_plain_text(): | |
| async def text_endpoint(): | |
| return "Hello World" | |
| response = client.get("/text") | |
| assert response.status_code == 200 | |
| assert response.headers["content-type"] == "text/plain; charset=utf-8" | |
| assert response.text == "Hello World" | |
| def test_response_class_json_with_raw_dict(): | |
| async def json_dict_endpoint(): | |
| return {"message": "Hello World"} | |
| response = client.get("/json-dict") | |
| assert response.status_code == 200 | |
| assert response.headers["content-type"] == "application/json" | |
| assert response.json() == {"message": "Hello World"} | |
| def test_response_class_with_etag(): | |
| """Test that different response classes still generate and handle ETags correctly""" | |
| async def html_etag_endpoint(): | |
| return "<h1>Hello World</h1>" | |
| # First request | |
| response1 = client.get("/html-etag") | |
| assert response1.status_code == 200 | |
| assert "ETag" in response1.headers | |
| # Second request with ETag | |
| etag = response1.headers["ETag"] | |
| response2 = client.get("/html-etag", headers={"If-None-Match": etag}) | |
| assert response2.status_code == 304 # Not Modified | |
| def test_no_cache_with_unchanged_data(): | |
| """Test no-cache behavior when data hasn't changed.""" | |
| counter = 0 | |
| async def no_cache_unchanged_endpoint(): | |
| return {"message": "This endpoint uses no-cache", "counter": counter} | |
| # First request should return 200 | |
| response1 = client.get("/no-cache-unchanged") | |
| assert response1.status_code == 200 | |
| assert response1.json() == {"message": "This endpoint uses no-cache", "counter": 0} | |
| etag1 = response1.headers["ETag"] | |
| assert "no-cache" in response1.headers["Cache-Control"].lower() | |
| # Second request with ETag should return 304 as data hasn't changed | |
| response2 = client.get("/no-cache-unchanged", headers={"If-None-Match": etag1}) | |
| assert response2.status_code == 304 | |
| assert "ETag" in response2.headers | |
| assert response2.headers["ETag"] == etag1 | |
| # Third request without ETag should return 200 but same data | |
| response3 = client.get("/no-cache-unchanged") | |
| assert response3.status_code == 200 | |
| assert response3.json() == {"message": "This endpoint uses no-cache", "counter": 0} | |
| assert response3.headers["ETag"] == etag1 | |
| def test_no_cache_with_changing_data(): | |
| """Test no-cache behavior when data changes between requests.""" | |
| counter = {"value": 0} | |
| async def no_cache_changing_endpoint(): | |
| counter["value"] += 1 | |
| return {"message": "This endpoint uses no-cache", "counter": counter["value"]} | |
| # First request | |
| response1 = client.get("/no-cache-changing") | |
| assert response1.status_code == 200 | |
| assert response1.json() == {"message": "This endpoint uses no-cache", "counter": 1} | |
| etag1 = response1.headers["ETag"] | |
| assert "no-cache" in response1.headers["Cache-Control"].lower() | |
| # Second request with previous ETag should still return 200 with new data | |
| response2 = client.get("/no-cache-changing", headers={"If-None-Match": etag1}) | |
| assert response2.status_code == 200 # Not 304 because data changed | |
| assert response2.json() == {"message": "This endpoint uses no-cache", "counter": 2} | |
| etag2 = response2.headers["ETag"] | |
| assert etag2 != etag1 # ETags should be different as content changed | |
| # Third request with latest ETag | |
| response3 = client.get("/no-cache-changing", headers={"If-None-Match": etag2}) | |
| assert response3.status_code == 200 | |
| assert response3.json() == {"message": "This endpoint uses no-cache", "counter": 3} | |
| assert response3.headers["ETag"] != etag2 # ETag should change again | |
| def test_cache_with_include_router(): | |
| """FastAPI 0.137.0 changes router.routes to contain intermediate objects when | |
| include_router() is used (routes are preserved, not cloned). | |
| cache() must still work correctly in this scenario because it accesses the | |
| matched route via scope["route"] — not by iterating router.routes. | |
| """ | |
| from fastapi import APIRouter | |
| from starlette.responses import HTMLResponse | |
| sub_router = APIRouter(prefix="/sub") | |
| async def sub_json(): | |
| return {"from": "sub_router"} | |
| async def sub_html(): | |
| return "<p>hello</p>" | |
| test_app = FastAPI() | |
| test_app.include_router(sub_router) | |
| test_client = TestClient(test_app) | |
| # JSON route — default response_class (JSONResponse via DefaultPlaceholder or direct) | |
| r1 = test_client.get("/sub/json") | |
| assert r1.status_code == 200 | |
| assert r1.json() == {"from": "sub_router"} | |
| assert "ETag" in r1.headers | |
| assert r1.headers["Cache-Control"] == "max-age=60" | |
| # Subsequent request should serve from cache (304 with matching ETag) | |
| r2 = test_client.get("/sub/json", headers={"If-None-Match": r1.headers["ETag"]}) | |
| assert r2.status_code == 304 | |
| # Explicit response_class=HTMLResponse must be respected | |
| r3 = test_client.get("/sub/html") | |
| assert r3.status_code == 200 | |
| assert "text/html" in r3.headers["content-type"] | |
| assert r3.text == "<p>hello</p>" | |
| assert "ETag" in r3.headers | |
| def test_streaming_response_not_cached(): | |
| """StreamingResponse has no .body; @cache must serve it as-is without an ETag.""" | |
| call_count = {"n": 0} | |
| stream_app = FastAPI() | |
| async def streaming_endpoint(): | |
| call_count["n"] += 1 | |
| async def gen(): | |
| yield b"chunk" | |
| return StreamingResponse(gen(), media_type="text/plain") | |
| stream_client = TestClient(stream_app) | |
| r1 = stream_client.get("/stream") | |
| assert r1.status_code == 200 | |
| assert "ETag" not in r1.headers | |
| assert call_count["n"] == 1 | |
| # Second request — handler must be called again (nothing cached) | |
| r2 = stream_client.get("/stream") | |
| assert r2.status_code == 200 | |
| assert "ETag" not in r2.headers | |
| assert call_count["n"] == 2 | |
| def test_streaming_response_with_no_cache_and_if_none_match(): | |
| """StreamingResponse through no_cache=True + If-None-Match must be served as-is.""" | |
| stream_app2 = FastAPI() | |
| async def streaming_nocache(): | |
| async def gen(): | |
| yield b"data" | |
| return StreamingResponse(gen(), media_type="text/plain") | |
| stream_client2 = TestClient(stream_app2) | |
| r = stream_client2.get( | |
| "/stream-nocache", | |
| headers={"If-None-Match": 'W/"some-old-etag"'}, | |
| ) | |
| assert r.status_code == 200 | |
| assert "ETag" not in r.headers | |
| def test_backend_fallback_when_none(): | |
| """When no backend is configured, @cache silently falls back to MemoryBackend.""" | |
| BackendProxy.set(None) | |
| fallback_app = FastAPI() | |
| async def fallback_endpoint(): | |
| return Response(content=b"ok", media_type="text/plain") | |
| fallback_client = TestClient(fallback_app) | |
| r = fallback_client.get("/fallback") | |
| assert r.status_code == 200 | |
| # After the request, a MemoryBackend should now be registered | |
| assert isinstance(BackendProxy.get(), MemoryBackend) | |
| def test_no_store_and_no_cache_combined(): | |
| """no_store=True takes priority; only 'no-store' appears in Cache-Control.""" | |
| combo_app = FastAPI() | |
| async def no_store_no_cache_endpoint(): | |
| return Response(content=b"data", media_type="text/plain") | |
| combo_client = TestClient(combo_app) | |
| r = combo_client.get("/no-store-no-cache") | |
| assert r.status_code == 200 | |
| cc = r.headers["Cache-Control"] | |
| assert "no-store" in cc | |
| assert "no-cache" not in cc | |
| def test_ttl_zero_entry_expires_immediately(): | |
| """ttl=0 causes the entry to expire immediately; subsequent requests re-execute handler.""" | |
| call_count = {"n": 0} | |
| ttl0_app = FastAPI() | |
| ttl0_backend = MemoryBackend() | |
| BackendProxy.set(ttl0_backend) | |
| async def ttl_zero_endpoint(): | |
| call_count["n"] += 1 | |
| return Response(content=b"hello", media_type="text/plain") | |
| ttl0_client = TestClient(ttl0_app) | |
| r1 = ttl0_client.get("/ttl-zero") | |
| assert r1.status_code == 200 | |
| assert "ETag" in r1.headers | |
| assert call_count["n"] == 1 | |
| # Remove the (immediately-expired) entry directly from the backend dict | |
| # so the next request hits a fresh cache miss and re-executes the handler. | |
| ttl0_backend.cache.clear() | |
| # Second request — no cached entry, handler called again | |
| r2 = ttl0_client.get("/ttl-zero") | |
| assert r2.status_code == 200 | |
| assert call_count["n"] == 2 | |
| def test_stale_client_etag_with_changed_cache(): | |
| """If the client sends an ETag that doesn't match the cached one, return 200 with new ETag.""" | |
| import time | |
| from fastapi_cachex.types import CacheItem | |
| etag_app = FastAPI() | |
| etag_backend = MemoryBackend() | |
| BackendProxy.set(etag_backend) | |
| async def etag_mismatch_endpoint(): | |
| return Response(content=b"original", media_type="text/plain") | |
| etag_client = TestClient(etag_app) | |
| # Warm the cache | |
| r1 = etag_client.get("/etag-mismatch") | |
| assert r1.status_code == 200 | |
| original_etag = r1.headers["ETag"] | |
| # Directly inject a different cache entry into the backend (simulates content change). | |
| # We bypass the async interface to avoid cross-event-loop issues in a sync test. | |
| # TestClient uses "testserver" as the default Host header. | |
| cache_key = "GET|||testserver|||/etag-mismatch|||" | |
| new_entry = CacheEntry( | |
| fingerprint='W/"newetag"', content=b"changed", media_type="text/plain" | |
| ) | |
| etag_backend.cache[cache_key] = CacheItem( | |
| value=new_entry, expiry=time.time() + 3600 | |
| ) | |
| # Client sends old ETag, but cache now has a different ETag — must get 200 with new content | |
| r2 = etag_client.get("/etag-mismatch", headers={"If-None-Match": original_etag}) | |
| assert r2.status_code == 200 | |
| assert r2.headers["ETag"] == 'W/"newetag"' | |
| def test_stale_ttl_without_stale_raises(): | |
| """stale_ttl without stale= must raise CacheXError at decoration time.""" | |
| with pytest.raises(CacheXError, match="stale must be set"): | |
| async def bad_endpoint(): | |
| pass | |
| def test_public_and_private_raises(): | |
| """public=True and private=True are mutually exclusive; must raise CacheXError.""" | |
| with pytest.raises(CacheXError, match="mutually exclusive"): | |
| async def bad_endpoint(): | |
| pass | |
Xet Storage Details
- Size:
- 21.6 kB
- Xet hash:
- 5e3a146e23f8620a3c9390ce1066cee6de34e22e7a5fa2fa2dc06cf669a80fbb
·
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.