conftest.py 5.12 KB
"""Shared test fixtures for intent-fusion tests."""

from __future__ import annotations

from unittest.mock import MagicMock, patch

import numpy as np
import pytest

from intent_fusion.types import IntentEntry


class MockLLM:
    """Deterministic mock LLM for testing.

    Returns a fixed JSON response that maps specific keywords to intents.
    """

    def __init__(self, response: str | None = None):
        self._response = response

    async def chat(self, messages: list[dict[str, str]], **kwargs) -> str:
        if self._response is not None:
            return self._response

        user_msg = messages[-1]["content"] if messages else ""

        if "where is my order" in user_msg or "shipping" in user_msg:
            return '{"top": [{"skill": "query_order_status", "score": 0.92}, {"skill": "cancel_order", "score": 0.30}, {"skill": "free_chat", "score": 0.10}]}'
        if "cancel" in user_msg or "changed my mind" in user_msg:
            return '{"top": [{"skill": "cancel_order", "score": 0.90}, {"skill": "query_order_status", "score": 0.35}, {"skill": "free_chat", "score": 0.10}]}'
        if "return" in user_msg or "send back" in user_msg:
            return '{"top": [{"skill": "initiate_return", "score": 0.88}, {"skill": "query_refund_status", "score": 0.40}, {"skill": "free_chat", "score": 0.10}]}'
        if "hello" in user_msg or "hi there" in user_msg:
            return '{"top": [{"skill": "free_chat", "score": 0.95}, {"skill": "query_order_status", "score": 0.10}, {"skill": "cancel_order", "score": 0.05}]}'

        return '{"top": [{"skill": "free_chat", "score": 0.60}, {"skill": "query_order_status", "score": 0.20}, {"skill": "cancel_order", "score": 0.10}]}'


class FailingLLM:
    """LLM that always raises an exception."""

    async def chat(self, messages: list[dict[str, str]], **kwargs) -> str:
        raise ConnectionError("LLM service unavailable")


SAMPLE_ENTRIES = [
    IntentEntry(
        name="query_order_status",
        domain="Order Management",
        embed_text="track order, where is my package, shipping status, delivery ETA",
        tree_text="user wants to know where their order is or current shipping status",
    ),
    IntentEntry(
        name="cancel_order",
        domain="Order Management",
        embed_text="cancel order, I don't want it anymore, stop my order",
        tree_text="user wants to cancel an order they placed",
    ),
    IntentEntry(
        name="initiate_return",
        domain="Returns & Refunds",
        embed_text="return item, send back, return request",
        tree_text="user wants to start a return process for a received item",
    ),
    IntentEntry(
        name="query_refund_status",
        domain="Returns & Refunds",
        embed_text="refund status, where is my refund, money back",
        tree_text="user is asking about the status of a refund",
    ),
    IntentEntry(
        name="query_product_info",
        domain="Product",
        embed_text="product details, item description, specifications",
        tree_text="user wants information about a product",
    ),
]


def _make_fake_model():
    """Create a fake SentenceTransformer that returns deterministic vectors.

    Maps intent names to fixed vectors so cosine similarity is predictable:
    query_order_status -> high similarity to "order" queries,
    cancel_order -> high similarity to "cancel" queries, etc.
    """
    rng = np.random.RandomState(42)
    name_to_vec: dict[str, np.ndarray] = {}

    def encode(texts: list[str], normalize_embeddings: bool = False) -> np.ndarray:
        results = []
        for text in texts:
            text_lower = text.lower()
            key = text_lower[:80]
            if key not in name_to_vec:
                vec = rng.randn(384).astype(np.float32)
                if "order" in text_lower or "shipping" in text_lower or "where" in text_lower:
                    vec[0] = 5.0
                if "cancel" in text_lower or "changed my mind" in text_lower:
                    vec[1] = 5.0
                if "return" in text_lower or "send back" in text_lower:
                    vec[2] = 5.0
                if "refund" in text_lower or "money back" in text_lower:
                    vec[3] = 5.0
                if "product" in text_lower or "description" in text_lower:
                    vec[4] = 5.0
                if normalize_embeddings:
                    norm = np.linalg.norm(vec)
                    if norm > 0:
                        vec = vec / norm
                name_to_vec[key] = vec
            results.append(name_to_vec[key])
        return np.array(results)

    model = MagicMock()
    model.encode = encode
    return model


@pytest.fixture
def sample_entries() -> list[IntentEntry]:
    return list(SAMPLE_ENTRIES)


@pytest.fixture
def mock_llm() -> MockLLM:
    return MockLLM()


@pytest.fixture
def failing_llm() -> FailingLLM:
    return FailingLLM()


@pytest.fixture(autouse=True)
def _mock_sentence_transformer():
    """Globally mock SentenceTransformer to avoid downloading real models."""
    fake_model = _make_fake_model()
    with patch(
        "sentence_transformers.SentenceTransformer",
        return_value=fake_model,
    ):
        yield