Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .github/workflows/main.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
3 changes: 3 additions & 0 deletions .gitmodules
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
[submodule "specification"]
path = specification
url = https://github.com/OctopusDeploy/openfeature-provider-specification.git
27 changes: 27 additions & 0 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 `<fixture file> - <case description>`.

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.
Expand Down
4 changes: 4 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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"]

Expand Down
1 change: 1 addition & 0 deletions specification
Submodule specification added at 0f4985
10 changes: 10 additions & 0 deletions tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
FakeFeatureFlagsServer,
run_fake_feature_flags_server,
)
from openfeature import api


def pytest_addoption(parser: pytest.Parser) -> None:
Expand All @@ -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()
143 changes: 143 additions & 0 deletions tests/specification_fixtures.py
Original file line number Diff line number Diff line change
@@ -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
`<fixture file> - <case description>`."""
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
8 changes: 2 additions & 6 deletions tests/test_octopus_feature_provider.py
Original file line number Diff line number Diff line change
Expand Up @@ -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." },
Expand Down Expand Up @@ -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."""
Expand Down
38 changes: 38 additions & 0 deletions tests/test_specification_fixtures.py
Original file line number Diff line number Diff line change
@@ -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)