Skip to content
Open
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
40 changes: 40 additions & 0 deletions app/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@

from functools import lru_cache

from pydantic import field_validator
from pydantic_settings import BaseSettings, SettingsConfigDict

# Providers we accept from env vars. Must stay in sync with:
Expand Down Expand Up @@ -144,6 +145,45 @@ class Settings(BaseSettings):
router_num_retries_default: int = 2
router_num_retries_auto: int = 0

# ── Field validators ──────────────────────────────
# Catch misconfiguration at startup with a clear message rather than
# letting an out-of-range value reach uvicorn / LiteLLM Router and
# produce a confusing runtime error.

@field_validator("port")
@classmethod
def _port_in_range(cls, v: int) -> int:
if not 1 <= v <= 65535:
raise ValueError(f"port must be 1–65535, got {v}")
return v

@field_validator("router_cooldown_seconds")
@classmethod
def _cooldown_non_negative(cls, v: int) -> int:
if v < 0:
raise ValueError(
f"router_cooldown_seconds must be >= 0, got {v}"
)
return v

@field_validator("router_allowed_fails")
@classmethod
def _allowed_fails_non_negative(cls, v: int) -> int:
if v < 0:
raise ValueError(
f"router_allowed_fails must be >= 0, got {v}"
)
return v

@field_validator("router_num_retries_default", "router_num_retries_auto")
@classmethod
def _retries_non_negative(cls, v: int, info) -> int:
if v < 0:
raise ValueError(
f"{info.field_name} must be >= 0, got {v}"
)
return v

def env_provider_keys(self) -> dict[str, str]:
"""Return the configured ENV-sourced provider keys as {provider: key}."""
out: dict[str, str] = {}
Expand Down
114 changes: 114 additions & 0 deletions tests/unit/test_config_validation.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
"""Tests for Settings field validators.

The validators catch misconfiguration at startup — an out-of-range port
or a negative retry count should fail fast with a clear message rather
than propagating to uvicorn / LiteLLM Router and producing a confusing
runtime error deep in the stack.
"""

import pytest


def test_port_default_is_valid(isolated_env):
from app.config import Settings

s = Settings(_env_file=None)
assert s.port == 8000


def test_port_boundary_low(isolated_env):
from app.config import Settings

s = Settings(_env_file=None, port=1)
assert s.port == 1


def test_port_boundary_high(isolated_env):
from app.config import Settings

s = Settings(_env_file=None, port=65535)
assert s.port == 65535


def test_port_zero_rejected(isolated_env):
from app.config import Settings
from pydantic import ValidationError

with pytest.raises(ValidationError, match="port must be 1"):
Settings(_env_file=None, port=0)


def test_port_negative_rejected(isolated_env):
from app.config import Settings
from pydantic import ValidationError

with pytest.raises(ValidationError, match="port must be 1"):
Settings(_env_file=None, port=-1)


def test_port_above_max_rejected(isolated_env):
from app.config import Settings
from pydantic import ValidationError

with pytest.raises(ValidationError, match="port must be 1"):
Settings(_env_file=None, port=70000)


def test_cooldown_zero_allowed(isolated_env):
"""Tests set 0 to disable cooldown entirely — must remain valid."""
from app.config import Settings

s = Settings(_env_file=None, router_cooldown_seconds=0)
assert s.router_cooldown_seconds == 0


def test_cooldown_negative_rejected(isolated_env):
from app.config import Settings
from pydantic import ValidationError

with pytest.raises(ValidationError, match="router_cooldown_seconds must be >= 0"):
Settings(_env_file=None, router_cooldown_seconds=-10)


def test_allowed_fails_default_zero(isolated_env):
from app.config import Settings

s = Settings(_env_file=None)
assert s.router_allowed_fails == 0


def test_allowed_fails_negative_rejected(isolated_env):
from app.config import Settings
from pydantic import ValidationError

with pytest.raises(ValidationError, match="router_allowed_fails must be >= 0"):
Settings(_env_file=None, router_allowed_fails=-1)


def test_retries_default_allowed(isolated_env):
from app.config import Settings

s = Settings(_env_file=None)
assert s.router_num_retries_default == 2
assert s.router_num_retries_auto == 0


def test_retries_negative_rejected(isolated_env):
from app.config import Settings
from pydantic import ValidationError

with pytest.raises(ValidationError, match="router_num_retries_default must be >= 0"):
Settings(_env_file=None, router_num_retries_default=-1)

with pytest.raises(ValidationError, match="router_num_retries_auto must be >= 0"):
Settings(_env_file=None, router_num_retries_auto=-3)


def test_port_via_env_rejected(isolated_env, monkeypatch):
"""Env-sourced port still runs through the validator."""
from app.config import Settings
from pydantic import ValidationError

monkeypatch.setenv("PORT", "99999")
with pytest.raises(ValidationError, match="port must be 1"):
Settings(_env_file=None)