fix(agent): raise ConfigError for malformed numeric env vars
This commit is contained in:
@@ -30,16 +30,24 @@ def _require(env: Mapping[str, str], name: str) -> str:
|
||||
return value
|
||||
|
||||
|
||||
def _int(env: Mapping[str, str], name: str, default: str) -> int:
|
||||
"""Parse an integer environment variable, raising ConfigError if invalid."""
|
||||
try:
|
||||
return int(env.get(name, default))
|
||||
except ValueError:
|
||||
raise ConfigError(f"invalid integer for environment variable: {name}")
|
||||
|
||||
|
||||
def load_config(env: Mapping[str, str] | None = None) -> AgentConfig:
|
||||
if env is None:
|
||||
env = os.environ
|
||||
return AgentConfig(
|
||||
db_host=_require(env, "DB_HOST"),
|
||||
db_port=int(env.get("DB_PORT", "5432")),
|
||||
db_port=_int(env, "DB_PORT", "5432"),
|
||||
db_user=_require(env, "POSTGRES_USER"),
|
||||
db_password=_require(env, "POSTGRES_PASSWORD"),
|
||||
agent_db_name=env.get("AGENT_DB_NAME", "agentdb"),
|
||||
firefly_url=_require(env, "FIREFLY_API_URL"),
|
||||
firefly_token=_require(env, "AGENT_FIREFLY_TOKEN"),
|
||||
heartbeat_interval_minutes=int(env.get("HEARTBEAT_INTERVAL_MINUTES", "60")),
|
||||
heartbeat_interval_minutes=_int(env, "HEARTBEAT_INTERVAL_MINUTES", "60"),
|
||||
)
|
||||
|
||||
@@ -51,3 +51,15 @@ def test_missing_required_var_names_the_var(missing):
|
||||
env = {k: v for k, v in MINIMAL_ENV.items() if k != missing}
|
||||
with pytest.raises(ConfigError, match=missing):
|
||||
load_config(env)
|
||||
|
||||
|
||||
def test_invalid_db_port_raises_config_error():
|
||||
env = {**MINIMAL_ENV, "DB_PORT": "notanumber"}
|
||||
with pytest.raises(ConfigError, match="DB_PORT"):
|
||||
load_config(env)
|
||||
|
||||
|
||||
def test_invalid_heartbeat_interval_raises_config_error():
|
||||
env = {**MINIMAL_ENV, "HEARTBEAT_INTERVAL_MINUTES": "abc"}
|
||||
with pytest.raises(ConfigError, match="HEARTBEAT_INTERVAL_MINUTES"):
|
||||
load_config(env)
|
||||
|
||||
Reference in New Issue
Block a user