"""Unit tests for PostgresConfig.""" from __future__ import annotations import pytest from python_repositories.config import PostgresConfig def _set_required_postgres_env(monkeypatch: pytest.MonkeyPatch) -> None: monkeypatch.setenv("POSTGRES_URI", "postgresql://localhost/mydb") monkeypatch.setenv("POSTGRES_TABLE", "users") def test_from_env_loads_all_fields(monkeypatch: pytest.MonkeyPatch) -> None: _set_required_postgres_env(monkeypatch) config = PostgresConfig.from_env(use_dotenv=False) assert config.uri == "postgresql://localhost/mydb" assert config.table == "users" assert config.primary_key == "id" def test_from_env_reads_primary_key_from_env( monkeypatch: pytest.MonkeyPatch, ) -> None: _set_required_postgres_env(monkeypatch) monkeypatch.setenv("POSTGRES_PRIMARY_KEY", "user_id") config = PostgresConfig.from_env(use_dotenv=False) assert config.primary_key == "user_id" def test_from_env_defaults_primary_key_to_id_when_unset( monkeypatch: pytest.MonkeyPatch, ) -> None: _set_required_postgres_env(monkeypatch) monkeypatch.delenv("POSTGRES_PRIMARY_KEY", raising=False) config = PostgresConfig.from_env(use_dotenv=False) assert config.primary_key == "id" def test_from_env_raises_when_uri_missing(monkeypatch: pytest.MonkeyPatch) -> None: monkeypatch.delenv("POSTGRES_URI", raising=False) monkeypatch.setenv("POSTGRES_TABLE", "users") with pytest.raises(Exception): PostgresConfig.from_env(use_dotenv=False) def test_from_env_raises_when_table_missing(monkeypatch: pytest.MonkeyPatch) -> None: monkeypatch.setenv("POSTGRES_URI", "postgresql://localhost/mydb") monkeypatch.delenv("POSTGRES_TABLE", raising=False) with pytest.raises(Exception): PostgresConfig.from_env(use_dotenv=False) def test_from_env_respects_custom_env_var_names( monkeypatch: pytest.MonkeyPatch, ) -> None: monkeypatch.setenv("CUSTOM_POSTGRES_URI", "postgresql://custom/mydb") monkeypatch.setenv("CUSTOM_POSTGRES_TABLE", "items") monkeypatch.setenv("CUSTOM_POSTGRES_PRIMARY_KEY", "item_id") config = PostgresConfig.from_env( "CUSTOM_POSTGRES_URI", "CUSTOM_POSTGRES_TABLE", "CUSTOM_POSTGRES_PRIMARY_KEY", use_dotenv=False, ) assert config.uri == "postgresql://custom/mydb" assert config.table == "items" assert config.primary_key == "item_id"