diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index a862d8e..02cd74a 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -33,6 +33,9 @@ jobs: steps: - uses: actions/checkout@v7 + with: + # The specification fixtures the tests run + submodules: true - uses: astral-sh/setup-uv@68559e99cc807c1eb7e9238fd43a15bba460eec2 # v10.3.3 with: diff --git a/.gitmodules b/.gitmodules new file mode 100644 index 0000000..4f9a6e1 --- /dev/null +++ b/.gitmodules @@ -0,0 +1,3 @@ +[submodule "specification"] + path = specification + url = https://github.com/OctopusDeploy/openfeature-provider-specification.git diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index a39198f..71600ef 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -2,12 +2,39 @@ ## Setup +Clone the repository with its submodules: + +```bash +git clone --recurse-submodules https://github.com/OctopusDeploy/openfeature-provider-python.git +``` + +If you've already cloned it without them, fetch them now: + +```bash +git submodule update --init +``` + The project uses [uv](https://docs.astral.sh/uv/). Install it, then install the project and its development tools: ```bash uv sync ``` +## Specification fixtures + +`specification/` is a submodule of [openfeature-provider-specification](https://github.com/OctopusDeploy/openfeature-provider-specification), which holds the fixtures every Octopus provider runs. `tests/test_specification_fixtures.py` runs every case in `specification/Fixtures/*.json` through the real provider and the OpenFeature SDK, against a fake feature flags server, as part of `uv run pytest`. Each test is named ` - `. + +The test run fails if the submodule isn't checked out, so the fixtures can't be skipped by accident. + +To pick up new fixtures, move the submodule to the specification repository's latest commit and commit the result: + +```bash +git submodule update --remote specification +git add specification +``` + +When a fixture fails, fix the evaluator or the provider, not the test runner. If a fixture itself is wrong, fix it in the specification repository so every provider gets the change. + ## Running the checks CI runs these on every PR, and fails the build if any of them fail. Run them locally before you push. diff --git a/pyproject.toml b/pyproject.toml index a402892..36ee47a 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -40,6 +40,10 @@ build-backend = "uv_build" [tool.uv] exclude-newer = "2 days" +[tool.uv.build-backend] +# The specification fixtures submodule is only read by the tests +source-exclude = ["/specification"] + [tool.pytest.ini_options] testpaths = ["tests"] diff --git a/specification b/specification new file mode 160000 index 0000000..0f49852 --- /dev/null +++ b/specification @@ -0,0 +1 @@ +Subproject commit 0f49852280a40e082ba941aa19e9b2e46d04107d diff --git a/tests/conftest.py b/tests/conftest.py index e05bfb5..01f4cf9 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -5,6 +5,7 @@ FakeFeatureFlagsServer, run_fake_feature_flags_server, ) +from openfeature import api def pytest_addoption(parser: pytest.Parser) -> None: @@ -18,3 +19,12 @@ def pytest_addoption(parser: pytest.Parser) -> None: @pytest.fixture def feature_flags_server() -> Iterator[FakeFeatureFlagsServer]: yield from run_fake_feature_flags_server() + + +@pytest.fixture +def reset_the_sdk() -> Iterator[None]: + """Shut down every registered provider after the test, so none carries over + to the next one. Modules that register providers apply it to every test with + `pytestmark = pytest.mark.usefixtures("reset_the_sdk")`.""" + yield + api.shutdown() diff --git a/tests/specification_fixtures.py b/tests/specification_fixtures.py new file mode 100644 index 0000000..54dc0f6 --- /dev/null +++ b/tests/specification_fixtures.py @@ -0,0 +1,143 @@ +"""Loads the shared specification fixtures and checks results against them. + +Each file in `specification/Fixtures/` is one simulated evaluations response +plus the cases evaluated against it. The fixtures are shared with every other +Octopus provider, so passing them shows this provider evaluates flags the same +way. How a case is evaluated is left to the caller, so loading, naming and +assertions stay separate from it. +""" + +import json +from collections.abc import Callable, Mapping +from dataclasses import dataclass +from pathlib import Path +from typing import Any, cast + +import pytest +from openfeature.evaluation_context import EvaluationContext +from openfeature.exception import ErrorCode +from openfeature.flag_evaluation import FlagEvaluationDetails, Reason + +FIXTURES_DIRECTORY = Path(__file__).parent.parent / "specification" / "Fixtures" + +# The OpenFeature targeting key, not a custom attribute. +TARGETING_KEY = "targetingKey" + + +@dataclass(frozen=True) +class FixtureCase: + file_name: str + description: str + # The fixture's simulated evaluations response, as JSON. + response: str + slug: str + default_value: bool + # A null attribute is present with a None value, not absent. + context: Mapping[str, str | None] | None + expected_value: bool + # None when the fixture doesn't state a reason. + expected_reason: str | None + # None when the evaluation returns no error. + expected_error_code: ErrorCode | None + + @property + def id(self) -> str: + return f"{self.file_name} - {self.description}" + + def evaluation_context(self) -> EvaluationContext | None: + if self.context is None: + return None + attributes = { + key: value for key, value in self.context.items() if key != TARGETING_KEY + } + return EvaluationContext( + targeting_key=self.context.get(TARGETING_KEY), + # None isn't an EvaluationContextAttribute, but a fixture's null + # attribute has to reach the provider as present with no value. + attributes=cast(Any, attributes), + ) + + +def load_fixture_cases(directory: Path = FIXTURES_DIRECTORY) -> list[FixtureCase]: + """Every case in every fixture file in directory. + + Raises: + RuntimeError: If there are no fixture files, so a missing submodule + fails the run rather than passing with nothing tested. + ValueError: If a fixture file or case is malformed. The message names + the file and case, as the error is raised while pytest collects the + tests, where a bare KeyError wouldn't say which fixture it came from. + """ + paths = sorted(directory.glob("*.json")) + if not paths: + raise RuntimeError( + f"No specification fixtures found in {directory}. Initialise the " + "submodule with: git submodule update --init" + ) + return [case for path in paths for case in _load_fixture_file(path)] + + +def _load_fixture_file(path: Path) -> list[FixtureCase]: + try: + fixture = json.loads(path.read_text(encoding="utf-8")) + response = json.dumps(fixture["response"]) + raw_cases = fixture["cases"] + except (KeyError, TypeError, ValueError) as error: + raise ValueError( + f"{path.name} isn't a valid specification fixture: {error!r}" + ) from error + + cases = [] + for number, raw_case in enumerate(raw_cases, start=1): + try: + cases.append(_case(path.name, response, raw_case)) + except (KeyError, TypeError, ValueError) as error: + raise ValueError( + f"Case {number} in {path.name} isn't a valid specification " + f"fixture case: {error!r}" + ) from error + return cases + + +def _case(file_name: str, response: str, case: dict[str, Any]) -> FixtureCase: + configuration = case["configuration"] + expected = case["expected"] + error_code = expected.get("errorCode") + return FixtureCase( + file_name=file_name, + description=case["description"], + response=response, + slug=configuration["slug"], + default_value=configuration["defaultValue"], + context=configuration.get("context"), + expected_value=expected["value"], + expected_reason=expected.get("reason"), + expected_error_code=None if error_code is None else ErrorCode(error_code), + ) + + +def parametrize_fixture_cases() -> pytest.MarkDecorator: + """Parametrises a test's `case` argument with every fixture case, named + ` - `.""" + cases = load_fixture_cases() + return pytest.mark.parametrize("case", cases, ids=[case.id for case in cases]) + + +def run_fixture_case( + case: FixtureCase, + evaluate: Callable[[FixtureCase], FlagEvaluationDetails[bool]], +) -> None: + """Evaluate case and assert the result matches what the fixture expects. + + The reason is checked where the fixture states one. Where it doesn't but + the case expects an error, the reason must be ERROR, as the SDK passes a + returned error through without setting it. + """ + details = evaluate(case) + + assert details.value is case.expected_value + assert details.error_code == case.expected_error_code + if case.expected_reason is not None: + assert details.reason == case.expected_reason + elif case.expected_error_code is not None: + assert details.reason == Reason.ERROR diff --git a/tests/test_octopus_feature_provider.py b/tests/test_octopus_feature_provider.py index add3893..4760cfc 100644 --- a/tests/test_octopus_feature_provider.py +++ b/tests/test_octopus_feature_provider.py @@ -33,6 +33,8 @@ ) from octopus_openfeature_provider._octopus_feature_provider import MAX_CACHE_DURATION +pytestmark = pytest.mark.usefixtures("reset_the_sdk") + MANIFEST = """ [ { "slug": "enabled-feature", "value": true, "reason": "The flag is enabled for this environment." }, @@ -65,12 +67,6 @@ def provider() -> OctopusFeatureProvider: return OctopusFeatureProvider(new_configuration()) -@pytest.fixture(autouse=True) -def reset_the_sdk() -> Iterator[None]: - yield - api.shutdown() - - def client_for(server: FakeFeatureFlagsServer, **options: Any) -> OpenFeatureClient: """Register a provider for server, wait until it's initialized, and return an SDK client.""" diff --git a/tests/test_specification_fixtures.py b/tests/test_specification_fixtures.py new file mode 100644 index 0000000..4df1a55 --- /dev/null +++ b/tests/test_specification_fixtures.py @@ -0,0 +1,38 @@ +"""Runs the shared specification fixtures through the real provider and the SDK. + +Each case is served from the fake feature flags server, so it covers the HTTP +decode, the SDK's context merge and error handling, and the provider's boolean +wiring as well as the evaluator. +""" + +import pytest +from fake_feature_flags_server import FakeFeatureFlagsServer, configuration_for +from openfeature import api +from openfeature.flag_evaluation import FlagEvaluationDetails +from specification_fixtures import ( + FixtureCase, + parametrize_fixture_cases, + run_fixture_case, +) + +from octopus_openfeature_provider import OctopusFeatureProvider + +pytestmark = pytest.mark.usefixtures("reset_the_sdk") + + +@parametrize_fixture_cases() +def test_specification_fixture( + feature_flags_server: FakeFeatureFlagsServer, case: FixtureCase +) -> None: + def evaluate(fixture_case: FixtureCase) -> FlagEvaluationDetails[bool]: + feature_flags_server.evaluations.body = fixture_case.response + api.set_provider_and_wait( + OctopusFeatureProvider(configuration_for(feature_flags_server)) + ) + return api.get_client().get_boolean_details( + fixture_case.slug, + fixture_case.default_value, + fixture_case.evaluation_context(), + ) + + run_fixture_case(case, evaluate)