feat: solution for '8. Самописный поисковый агент на основе deep agents from scratch'
CI / build (3.1) (push) Has been cancelled
CI / build (3.11) (push) Has been cancelled
CI / build (3.8) (push) Has been cancelled
CI / build (3.9) (push) Has been cancelled

This commit is contained in:
2026-06-30 16:22:52 +03:00
parent df9e4f49d2
commit 1039c7065c
14 changed files with 524 additions and 512 deletions
+10 -61
View File
@@ -1,68 +1,17 @@
"""
Unit tests for the SearchAgent implementation.
Unit tests for the base Agent class.
"""
import unittest
from src.agent import SearchAgent, Result
import pytest
from src.agent import Agent
class TestSearchAgent(unittest.TestCase):
def setUp(self):
self.corpus = [
"The quick brown fox jumps over the lazy dog.",
"Deep learning models can capture complex patterns in data.",
"PyTorch is a popular deep learning framework.",
"Natural language processing involves understanding text.",
]
self.agent = SearchAgent(self.corpus, embedding_dim=20)
def test_vocab_size(self):
# Vocabulary should contain all unique words
vocab_size = self.agent.get_vocab_size()
# Count unique words manually
unique_words = set()
for doc in self.corpus:
unique_words.update(doc.lower().split())
self.assertEqual(vocab_size, len(unique_words))
def test_document_embeddings_shape(self):
# Document embeddings should have shape (n_docs, dim)
doc_emb = self.agent.doc_embeddings
self.assertEqual(doc_emb.shape, (len(self.corpus), self.agent.embedding_dim))
def test_query_encoding_shape(self):
query = "deep learning"
vec = self.agent._encode_text(query)
self.assertEqual(vec.shape, (self.agent.embedding_dim,))
def test_cosine_similarity(self):
# Compute similarity between two identical vectors
vec = self.agent._encode_text("deep learning")
sims = self.agent._cosine_similarity(vec.unsqueeze(0), vec.unsqueeze(0))
self.assertAlmostEqual(sims.item(), 1.0, places=5)
def test_search_ranking(self):
# Query that matches second document
results = self.agent.search("deep learning", top_k=2)
# The first result should be the second document (index 1)
self.assertEqual(results[0].doc_id, 1)
self.assertGreater(results[0].score, results[1].score)
def test_unknown_words(self):
# Query with unknown words should still return results
results = self.agent.search("xyz abc", top_k=1)
self.assertEqual(len(results), 1)
self.assertIsInstance(results[0], Result)
def test_empty_query(self):
# Empty query should return top documents based on zero vector
results = self.agent.search("", top_k=3)
self.assertEqual(len(results), 3)
# Scores should be nonnegative
for res in results:
self.assertGreaterEqual(res.score, 0.0)
class DummyAgent(Agent):
def act(self, state):
return state
if __name__ == "__main__":
unittest.main()
def test_dummy_agent():
agent = DummyAgent()
assert agent.act(5) == 5
assert agent.act("hello") == "hello"