python
5 days, 21 hours ago
import unittest
from unittest.mock import MagicMock
import numpy as np
from str_distance_util import StrDistanceUtil
class TestStrDistanceUtil(unittest.TestCase):
def setUp(self):
# Mock config and gcp_ai_service
self.config = {}
self.gcp_ai_service = MagicMock()
self.embedding_util_mock = MagicMock()
# Initialize StrDistanceUtil with a mock EmbeddingsUtil
self.util = StrDistanceUtil(self.config, self.gcp_ai_service)
self.util.embedding_util = self.embedding_util_mock
def test_distance(self):
list1 = [1, 2, 3]
list2 = [4, 5, 6]
expected = np.linalg.norm(np.array(list1) - np.array(list2))
result = self.util.distance(list1, list2)
self.assertAlmostEqual(result, expected, places=5)
def test_cosine_distance(self):
list1 = [1, 0, 0]
list2 = [0, 1, 0]
expected = 1 - np.dot(list1, list2) / (np.linalg.norm(list1) * np.linalg.norm(list2))
result = self.util.cosine_distance(list1, list2)
self.assertAlmostEqual(result, expected, places=5)
def test_get_str_distance(self):
call_id = "1234"
google_output = ["hello", "world"]
azure_output = ["hi", "planet"]
# Mock embeddings
google_embeddings = [[0.1, 0.2], [0.4, 0.5]]
azure_embeddings = [[0.1, 0.1], [0.3, 0.5]]
self.embedding_util_mock.get_embeddings.side_effect = [google_embeddings, azure_embeddings]
result = self.util.get_str_distance(call_id, google_output, azure_output)
# Expected result
expected = [
{"CALL_ID": "1234", "GOOGLE_NAMING": "hello", "AZURE_NAMING": "hi", "DISTANCE": 0.1},
{"CALL_ID": "1234", "GOOGLE_NAMING": "world", "AZURE_NAMING": "planet", "DISTANCE": 0.1},
]
self.assertEqual(len(result), len(expected))
for r, e in zip(result, expected):
self.assertEqual(r["CALL_ID"], e["CALL_ID"])
self.assertEqual(r["GOOGLE_NAMING"], e["GOOGLE_NAMING"])
self.assertEqual(r["AZURE_NAMING"], e["AZURE_NAMING"])
self.assertAlmostEqual(r["DISTANCE"], e["DISTANCE"], places=5)
def test_get_cosine_str_distance(self):
call_id = "5678"
google_output = ["alpha", "beta"]
azure_output = ["gamma", "delta"]
# Mock embeddings
google_embeddings = [[0.5, 0.5], [0.1, 0.9]]
azure_embeddings = [[0.4, 0.4], [0.0, 1.0]]
self.embedding_util_mock.get_embeddings.side_effect = [google_embeddings, azure_embeddings]
result = self.util.get_cosine_str_distance(call_id, google_output, azure_output)
# Expected result
expected = [
{"CALL_ID": "5678", "GOOGLE_NAMING": "alpha", "AZURE_NAMING": "gamma", "DISTANCE": 0.0204},
{"CALL_ID": "5678", "GOOGLE_NAMING": "beta", "AZURE_NAMING": "delta", "DISTANCE": 0.0},
]
self.assertEqual(len(result), len(expected))
for r, e in zip(result, expected):
self.assertEqual(r["CALL_ID"], e["CALL_ID"])
self.assertEqual(r["GOOGLE_NAMING"], e["GOOGLE_NAMING"])
self.assertEqual(r["AZURE_NAMING"], e["AZURE_NAMING"])
self.assertAlmostEqual(r["DISTANCE"], e["DISTANCE"], places=4)
if __name__ == "__main__":
unittest.main()
0 Comments
Please Login to Comment Here