"""Unit tests for the LangChain embedding factory. LangChain experiment branch: the factory now returns a ``langchain_core.embeddings.Embeddings`` object instead of the custom ``EmbeddingClient`` interface. """ import pytest from langchain_core.embeddings import Embeddings def test_factory_returns_embeddings_object(monkeypatch: pytest.MonkeyPatch) -> None: """get_embedding_client() must return a LangChain Embeddings object.""" import app.embeddings.factory as _factory monkeypatch.setattr(_factory, "_instance", None) client = _factory.get_embedding_client() assert isinstance(client, Embeddings) def test_factory_singleton(monkeypatch: pytest.MonkeyPatch) -> None: """get_embedding_client() must return the same instance on repeated calls.""" import app.embeddings.factory as _factory monkeypatch.setattr(_factory, "_instance", None) c1 = _factory.get_embedding_client() c2 = _factory.get_embedding_client() assert c1 is c2, "Factory returned a different instance on second call" def test_factory_openai_when_key_set(monkeypatch: pytest.MonkeyPatch) -> None: """Factory should use OpenAIEmbeddings when openai_api_key is non-empty.""" from langchain_openai import OpenAIEmbeddings import app.embeddings.factory as _factory monkeypatch.setattr(_factory, "_instance", None) fake_settings = type("S", (), {"openai_api_key": "sk-test", "embedding_model": "text-embedding-3-small"})() monkeypatch.setattr(_factory, "settings", fake_settings) client = _factory.get_embedding_client() assert isinstance(client, OpenAIEmbeddings) def test_factory_huggingface_without_key(monkeypatch: pytest.MonkeyPatch) -> None: """Factory should fall back to HuggingFaceEmbeddings when no OpenAI key is set.""" from langchain_huggingface import HuggingFaceEmbeddings import app.embeddings.factory as _factory monkeypatch.setattr(_factory, "_instance", None) fake_settings = type("S", (), {"openai_api_key": "", "local_embedding_model": "all-MiniLM-L6-v2"})() monkeypatch.setattr(_factory, "settings", fake_settings) client = _factory.get_embedding_client() assert isinstance(client, HuggingFaceEmbeddings) def test_embeddings_embed_query_returns_vector(monkeypatch: pytest.MonkeyPatch) -> None: """embed_query() should return a non-empty list of floats.""" import app.embeddings.factory as _factory monkeypatch.setattr(_factory, "_instance", None) client = _factory.get_embedding_client() vec = client.embed_query("The property is a Victorian terrace.") assert isinstance(vec, list) assert len(vec) > 0 assert all(isinstance(v, float) for v in vec) def test_embeddings_embed_documents_batch(monkeypatch: pytest.MonkeyPatch) -> None: """embed_documents() should return one vector per input text.""" import app.embeddings.factory as _factory monkeypatch.setattr(_factory, "_instance", None) client = _factory.get_embedding_client() texts = ["first sentence", "second sentence", "third sentence"] vecs = client.embed_documents(texts) assert len(vecs) == 3 assert all(len(v) > 0 for v in vecs)