Files
sonic_agent/tests/test_llm_properties.py
2026-03-18 21:23:14 -05:00

233 lines
9.2 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""Property-based tests for the LLM provider abstraction module.
Uses hypothesis to verify universal properties across many generated inputs.
Each property test is tagged with its design document reference.
"""
import os
from unittest.mock import MagicMock, patch
import pytest
from hypothesis import given, settings, strategies as st, assume
from langchain_core.language_models import BaseChatModel
from llm import PROVIDER_REGISTRY, DEFAULT_MODELS, create_model
# ── Strategies ───────────────────────────────────────────────────────────────
registered_providers = st.sampled_from(list(PROVIDER_REGISTRY.keys()))
# Non-empty printable strings for model names
model_name_strategy = st.text(
alphabet=st.characters(whitelist_categories=("L", "N", "P", "S", "Z")),
min_size=1,
max_size=50,
).filter(lambda s: s.strip() != "" and s.isprintable())
# Strings that are NOT registered provider names (exclude null bytes for env var compat)
unknown_provider_strategy = st.text(
alphabet=st.characters(blacklist_characters="\x00"),
min_size=0,
max_size=50,
).filter(lambda s: s not in PROVIDER_REGISTRY)
# Non-empty strings for URL and region values (exclude null bytes for env var compat)
non_empty_text = st.text(
alphabet=st.characters(blacklist_characters="\x00"),
min_size=1,
max_size=100,
).filter(lambda s: s.strip() != "")
# ── Property 1: Provider registry produces valid models ──────────────────────
class TestProperty1ProviderRegistryProducesValidModels:
"""Feature: llm-provider-abstraction, Property 1: Provider registry produces valid models
For any registered provider name, setting LLM_PROVIDER and calling
create_model() returns an instance of BaseChatModel.
**Validates: Requirements 1.1, 2.1, 6.1**
"""
@settings(max_examples=10)
@given(provider=registered_providers)
def test_registered_provider_returns_base_chat_model(self, provider):
"""For any registered provider, create_model returns BaseChatModel."""
mock_instance = MagicMock(spec=BaseChatModel)
with patch("llm.ChatOpenAI", return_value=mock_instance), \
patch("llm.ChatBedrock", return_value=mock_instance), \
patch.dict(os.environ, {"LLM_PROVIDER": provider}, clear=True):
result = create_model()
assert isinstance(result, BaseChatModel)
# ── Property 2: Model name resolution ────────────────────────────────────────
class TestProperty2ModelNameResolution:
"""Feature: llm-provider-abstraction, Property 2: Model name resolution
For any provider × model name string, the model uses that name.
Without MODEL_NAME, uses default from DEFAULT_MODELS.
**Validates: Requirements 2.3, 2.4**
"""
@settings(max_examples=10)
@given(provider=registered_providers, model_name=model_name_strategy)
def test_custom_model_name_is_used(self, provider, model_name):
"""For any provider and model name, the model is configured with that name."""
mock_instance = MagicMock(spec=BaseChatModel)
with patch("llm.ChatOpenAI", return_value=mock_instance) as mock_openai, \
patch("llm.ChatBedrock", return_value=mock_instance) as mock_bedrock, \
patch.dict(os.environ, {"LLM_PROVIDER": provider, "MODEL_NAME": model_name}, clear=True):
create_model()
if provider in ("openai", "llama-server"):
mock_openai.assert_called_once()
_, kwargs = mock_openai.call_args
assert kwargs["model"] == model_name
else:
mock_bedrock.assert_called_once()
_, kwargs = mock_bedrock.call_args
assert kwargs["model_id"] == model_name
@settings(max_examples=10)
@given(provider=registered_providers)
def test_default_model_name_when_not_set(self, provider):
"""Without MODEL_NAME, uses default from DEFAULT_MODELS."""
mock_instance = MagicMock(spec=BaseChatModel)
expected_default = DEFAULT_MODELS[provider]
with patch("llm.ChatOpenAI", return_value=mock_instance) as mock_openai, \
patch("llm.ChatBedrock", return_value=mock_instance) as mock_bedrock, \
patch.dict(os.environ, {"LLM_PROVIDER": provider}, clear=True):
create_model()
if provider in ("openai", "llama-server"):
mock_openai.assert_called_once()
_, kwargs = mock_openai.call_args
assert kwargs["model"] == expected_default
else:
mock_bedrock.assert_called_once()
_, kwargs = mock_bedrock.call_args
assert kwargs["model_id"] == expected_default
# ── Property 3: Unknown provider error message ───────────────────────────────
class TestProperty3UnknownProviderErrorMessage:
"""Feature: llm-provider-abstraction, Property 3: Unknown provider error message
For any string NOT in PROVIDER_REGISTRY, ValueError contains the invalid
name and all valid provider names.
**Validates: Requirements 2.5, 8.1**
"""
@settings(max_examples=10)
@given(invalid_provider=unknown_provider_strategy)
def test_unknown_provider_raises_valueerror_with_details(self, invalid_provider):
"""For any non-registry string, ValueError contains invalid name and all valid names."""
with patch.dict(os.environ, {"LLM_PROVIDER": invalid_provider}, clear=True):
with pytest.raises(ValueError) as exc_info:
create_model()
error_msg = str(exc_info.value)
# Error message should contain the invalid provider name
assert invalid_provider in error_msg
# Error message should contain all valid provider names
for valid_name in PROVIDER_REGISTRY.keys():
assert valid_name in error_msg
# ── Property 4: Llama server URL configuration ───────────────────────────────
class TestProperty4LlamaServerUrlConfiguration:
"""Feature: llm-provider-abstraction, Property 4: Llama server URL configuration
For any URL string in LLAMA_SERVER_URL, the ChatOpenAI instance gets
that base_url.
**Validates: Requirements 4.2**
"""
@settings(max_examples=10)
@given(url=non_empty_text)
def test_llama_server_uses_configured_url(self, url):
"""For any URL string in LLAMA_SERVER_URL, model base_url matches."""
mock_instance = MagicMock(spec=BaseChatModel)
with patch("llm.ChatOpenAI", return_value=mock_instance) as mock_openai, \
patch.dict(os.environ, {"LLM_PROVIDER": "llama-server", "LLAMA_SERVER_URL": url}, clear=True):
create_model()
mock_openai.assert_called_once()
_, kwargs = mock_openai.call_args
assert kwargs["base_url"] == url
# ── Property 5: Bedrock region configuration ─────────────────────────────────
class TestProperty5BedrockRegionConfiguration:
"""Feature: llm-provider-abstraction, Property 5: Bedrock region configuration
For any region string in AWS_REGION, ChatBedrock gets that region.
**Validates: Requirements 5.4**
"""
@settings(max_examples=10)
@given(region=non_empty_text)
def test_bedrock_uses_configured_region(self, region):
"""For any region string in AWS_REGION, model uses that region."""
mock_instance = MagicMock(spec=BaseChatModel)
with patch("llm.ChatBedrock", return_value=mock_instance) as mock_bedrock, \
patch.dict(os.environ, {"LLM_PROVIDER": "bedrock", "AWS_REGION": region}, clear=True):
create_model()
mock_bedrock.assert_called_once()
_, kwargs = mock_bedrock.call_args
assert kwargs["region_name"] == region
# ── Property 6: Factory exception propagation ────────────────────────────────
class TestProperty6FactoryExceptionPropagation:
"""Feature: llm-provider-abstraction, Property 6: Factory exception propagation
For any exception raised by a factory, create_model() propagates it unchanged.
**Validates: Requirements 8.2**
"""
@settings(max_examples=10)
@given(
provider=registered_providers,
error_msg=st.text(min_size=1, max_size=100).filter(lambda s: s.strip() != ""),
)
def test_factory_exception_propagates_unchanged(self, provider, error_msg):
"""For any exception from factory, it propagates unchanged."""
original_exception = RuntimeError(error_msg)
# Patch the factory in the registry to raise the exception
with patch.dict(PROVIDER_REGISTRY, {provider: MagicMock(side_effect=original_exception)}), \
patch.dict(os.environ, {"LLM_PROVIDER": provider}, clear=True):
with pytest.raises(RuntimeError) as exc_info:
create_model()
# Verify the exact same exception propagated
assert exc_info.value is original_exception
assert str(exc_info.value) == error_msg