import pytest from fastapi import FastAPI from pytest_mock import MockerFixture from starlette.middleware import Middleware from starlette.testclient import TestClient from owslib import context from owslib.ext.starlette.middleware.context import ( CorrelationIdMiddleware, RequestContextMiddleware, ) @pytest.fixture(scope="session") def app() -> FastAPI: app = FastAPI( middleware=[ Middleware(CorrelationIdMiddleware), Middleware(RequestContextMiddleware), ] ) @app.get("/test") def endpoint() -> str: return "ok" return app @pytest.fixture(scope="session") def client(app: FastAPI) -> TestClient: return TestClient(app) def test_set_correlation_default(mocker: MockerFixture, client: TestClient) -> None: correlation_id = "test" correlation_id_mock = mocker.patch( "owslib.ext.starlette.middleware.context.context.correlation_id", ) correlation_id_mock.get.return_value = correlation_id response = client.get("/test") assert response.headers["Correlation-Id"] == correlation_id def test_set_correlation_in_header(client: TestClient) -> None: correlation_id = "test" response = client.get("/test", headers={"Correlation-Id": correlation_id}) assert response.headers["Correlation-Id"] == correlation_id def test_set_request_context(mocker: MockerFixture, client: TestClient) -> None: profile_type = "AudienceProfile" profile_id = "1000" request_context_mock = mocker.patch( "owslib.ext.starlette.middleware.context.context.request_context", ) client.get( "/test", headers={ "Orchard-Profile-Type": profile_type, "Orchard-Profile-Id": profile_id, }, ) request_context_mock.set.assert_called_once_with( context.RequestContext( context_type="profile", profile_type=profile_type, profile_id=int(profile_id), ) )