|
| 1 | +"""OpenAPI contract-conformance test for py-recipe-service using Schemathesis. |
| 2 | +
|
| 3 | +Verifies that the service's live responses conform to the internal contract in |
| 4 | +`api/openapi-internal.yaml`. |
| 5 | +""" |
| 6 | + |
| 7 | +import pathlib |
| 8 | +from unittest.mock import AsyncMock, MagicMock |
| 9 | + |
| 10 | +import pytest |
| 11 | +import schemathesis |
| 12 | + |
| 13 | +from main import app, get_llm, verify_internal_hmac, RecipeListWrapper, LocalRecipeInput |
| 14 | + |
| 15 | +_CONTRACT = ( |
| 16 | + pathlib.Path(__file__).resolve().parents[3] / "api" / "openapi-internal.yaml" |
| 17 | +) |
| 18 | +app.openapi_schema = schemathesis.openapi.from_path(_CONTRACT).raw_schema |
| 19 | + |
| 20 | +# /ai/help belongs to py-help-service |
| 21 | +schema = schemathesis.openapi.from_asgi("/openapi.json", app).exclude(path="/ai/help") |
| 22 | + |
| 23 | +# Happy path only. Auth rejection (missing/invalid HMAC headers) is covered in test_recipe_service.py. |
| 24 | +schema.config.generation.update(modes=[schemathesis.GenerationMode.POSITIVE]) |
| 25 | +schema.config.phases.update(phases=["examples", "fuzzing"]) |
| 26 | + |
| 27 | + |
| 28 | +@pytest.fixture(autouse=True) |
| 29 | +def _stub_provider_dependencies(): |
| 30 | + app.dependency_overrides[verify_internal_hmac] = lambda: None |
| 31 | + |
| 32 | + conforming = RecipeListWrapper( |
| 33 | + recipes=[ |
| 34 | + LocalRecipeInput( |
| 35 | + title="Test Recipe", |
| 36 | + ingredients=[{"quantity": 1.0, "unit": "cup", "name": "Flour"}], |
| 37 | + instructions=["Mix.", "Bake."], |
| 38 | + portions=2.0, |
| 39 | + nutrients={"calories": 200, "protein": 5, "fat": 3, "carbs": 35}, |
| 40 | + ) |
| 41 | + ] |
| 42 | + ) |
| 43 | + structured_runnable = AsyncMock() |
| 44 | + structured_runnable.ainvoke.return_value = conforming |
| 45 | + llm = MagicMock() |
| 46 | + llm.with_structured_output.return_value = structured_runnable |
| 47 | + app.dependency_overrides[get_llm] = lambda: llm |
| 48 | + |
| 49 | + yield |
| 50 | + app.dependency_overrides.clear() |
| 51 | + |
| 52 | + |
| 53 | +@schema.parametrize() |
| 54 | +def test_openapi_conformance(case): |
| 55 | + case.call_and_validate() |
0 commit comments