test_config.py 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. """配置读取测试。"""
  2. import pytest
  3. from src.config import ConfigurationError, LLMSettings
  4. ENV_NAMES = (
  5. "LLM_MODEL_ID",
  6. "LLM_API_KEY",
  7. "LLM_BASE_URL",
  8. "LLM_TEMPERATURE",
  9. "LLM_TIMEOUT",
  10. )
  11. def _clear_llm_env(monkeypatch: pytest.MonkeyPatch) -> None:
  12. for name in ENV_NAMES:
  13. monkeypatch.delenv(name, raising=False)
  14. def test_settings_from_env_reads_valid_values(monkeypatch: pytest.MonkeyPatch) -> None:
  15. _clear_llm_env(monkeypatch)
  16. monkeypatch.setenv("LLM_MODEL_ID", "test-model")
  17. monkeypatch.setenv("LLM_API_KEY", "secret-for-test")
  18. monkeypatch.setenv("LLM_BASE_URL", "https://example.test/v1")
  19. monkeypatch.setenv("LLM_TEMPERATURE", "0.3")
  20. monkeypatch.setenv("LLM_TIMEOUT", "30")
  21. settings = LLMSettings.from_env()
  22. assert settings.model == "test-model"
  23. assert settings.temperature == 0.3
  24. assert settings.timeout == 30
  25. def test_settings_reject_missing_values(monkeypatch: pytest.MonkeyPatch) -> None:
  26. _clear_llm_env(monkeypatch)
  27. with pytest.raises(ConfigurationError, match="LLM_MODEL_ID"):
  28. LLMSettings.from_env()
  29. def test_settings_reject_placeholder_key() -> None:
  30. settings = LLMSettings(
  31. model="test-model",
  32. api_key="your_api_key_here",
  33. base_url="https://example.test/v1",
  34. )
  35. with pytest.raises(ConfigurationError, match="占位符"):
  36. settings.validate()
  37. @pytest.mark.parametrize(
  38. ("temperature", "timeout", "message"),
  39. [(-0.1, 30, "TEMPERATURE"), (0.2, 0, "TIMEOUT")],
  40. )
  41. def test_settings_reject_out_of_range_values(
  42. temperature: float, timeout: int, message: str
  43. ) -> None:
  44. settings = LLMSettings(
  45. model="test-model",
  46. api_key="secret-for-test",
  47. base_url="https://example.test/v1",
  48. temperature=temperature,
  49. timeout=timeout,
  50. )
  51. with pytest.raises(ConfigurationError, match=message):
  52. settings.validate()