Skip to content

test: test_no_platform_key_configured_raises_500 fails locally when .env file present #271

@neuromechanist

Description

@neuromechanist

Bug

tests/test_api/test_authorization.py::TestSelectApiKey::test_no_platform_key_configured_raises_500 fails locally for any developer who has a .env file (i.e. essentially every dev with a working setup).

CI is green because GitHub Actions runners have no .env on disk.

Reproduction

# With .env present at repo root containing OPENROUTER_API_KEY=...
uv run pytest tests/test_api/test_authorization.py::TestSelectApiKey::test_no_platform_key_configured_raises_500 -v

Result:

FAILED ... - Failed: DID NOT RAISE <class 'fastapi.exceptions.HTTPException'>

Root cause

The test relies on monkeypatch.delenv("OPENROUTER_API_KEY") to simulate "no platform key configured". However, src/api/config.py defines:

class Settings(BaseSettings):
    model_config = SettingsConfigDict(
        env_file=".env",
        env_file_encoding="utf-8",
        ...
    )
    openrouter_api_key: str | None = Field(default=None, ...)

get_settings() re-reads from .env on each call (or via cached settings populated from .env), so deleting the env var does not actually remove the key. The test's intent ("no platform key configured") is never realized.

Fix options

  1. Monkeypatch Settings.openrouter_api_key directly (e.g. via monkeypatch.setattr(settings, "openrouter_api_key", None) after invalidating any lru_cache on get_settings).
  2. Use monkeypatch.setattr on the Settings model's _env_file to point to a temp empty file.
  3. Override get_settings dependency for the duration of the test.

Same pattern likely affects other tests that try to clear API key env vars while a .env exists.

Related

Discovered while reviewing #269 (OpenNeuroPET community PR) on branch feature/issue-269-openneuropet-community.

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't workingtestingTesting and quality assurance

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions