Skip to content

Commit 7e27e50

Browse files
nseidandantuzi
authored andcommitted
Respond to Pablo's feedback
1 parent 7877ebd commit 7e27e50

3 files changed

Lines changed: 105 additions & 42 deletions

File tree

rre-dataset-generator/src/search_engine/opensearch_engine.py

Lines changed: 25 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import json
12
import logging
23
from typing import List, Dict, Any, Union
34

@@ -99,15 +100,27 @@ def _search(self, payload: Dict[str, Any]) -> List[Document]:
99100
return result
100101

101102
@staticmethod
102-
def _normalize(value: Any) -> Any:
103-
"""
104-
Normalize a field value:
105-
- string → return [cleaned string]
106-
- list of strings → return [cleaned strings]
107-
- else → return as it is
108-
"""
109-
if isinstance(value, str):
110-
return [clean_text(value)]
111-
if isinstance(value, list) and all(isinstance(i, str) for i in value):
112-
return [clean_text(i) for i in value]
113-
return value
103+
def _normalize(value: Any) -> List[str]:
104+
"""Normalize a field value into a list of cleaned strings or throws an exception."""
105+
try:
106+
if value is None:
107+
return []
108+
109+
if isinstance(value, str):
110+
return [clean_text(value)]
111+
112+
if isinstance(value, list):
113+
return [clean_text(v) if isinstance(v, str) else str(v) for v in value]
114+
115+
if isinstance(value, dict):
116+
cleaned_dict = {
117+
k: clean_text(v) if isinstance(v, str) else v
118+
for k, v in value.items()
119+
}
120+
return [json.dumps(cleaned_dict)]
121+
122+
return [str(value)]
123+
124+
except Exception as e:
125+
raise ValueError(f"Failed to normalize value: {value}") from e
126+

rre-dataset-generator/tests/mocks/opensearch.py

Lines changed: 15 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,27 @@
1+
from typing import List, Dict, Union, Any
2+
13
import requests
24

35

46
class MockResponseOpenSearchEngine:
5-
def __init__(self, hits_data, status_code=200):
6-
self._hits_data = hits_data if isinstance(hits_data, list) else [hits_data]
7+
def __init__(self, hits_data: Union[Dict[str, Any], List[Dict[str, Any]]], status_code: int = 200):
8+
if isinstance(hits_data, dict):
9+
self._hits_data = [hits_data]
10+
elif isinstance(hits_data, list):
11+
self._hits_data = hits_data
12+
else:
13+
raise ValueError("hits_data must be a dict or a list of dicts")
14+
15+
if not isinstance(status_code, int):
16+
raise TypeError("status_code must be an int")
17+
718
self.status_code = status_code
819

9-
def raise_for_status(self):
20+
def raise_for_status(self) -> None:
1021
if self.status_code != 200:
1122
raise requests.exceptions.HTTPError(f"Status code: {self.status_code}")
1223

13-
def json(self):
24+
def json(self) -> Dict[str, Any]:
1425
return {
1526
"hits": {
1627
"total": {"value": len(self._hits_data), "relation": "eq"},
Lines changed: 65 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
1+
import json
12
import logging
23

4+
import pytest
35
import requests
46

57
from src.config import Config
@@ -11,47 +13,84 @@
1113
configure_logging(level=logging.DEBUG)
1214

1315

14-
def test_opensearch_search_engine(monkeypatch):
15-
config = Config.load("tests/unit/resources/good_config_opensearch.yaml")
16-
search_engine = OpenSearchEngine("http://testurl/testcore")
16+
@pytest.fixture
17+
def opensearch_config():
18+
"""Fixture that loads a valid OpenSearch config for unit tests."""
19+
return Config.load("tests/unit/resources/good_config_opensearch.yaml")
1720

18-
doc = {
19-
"id": "1",
20-
"title": "test title",
21-
"description": "test description"
22-
}
2321

24-
hit = {
22+
@pytest.fixture
23+
def opensearch_hit():
24+
return {
2525
"_index": "testcore",
2626
"_id": "1",
2727
"_score": 1.0,
28-
"_source": doc
28+
"_source": {
29+
"id": "1",
30+
"title": "test title",
31+
"description": "test description"
32+
}
2933
}
3034

35+
36+
def test_fetch_for_query_generation(monkeypatch, opensearch_config, opensearch_hit):
37+
opensearch = OpenSearchEngine("http://testurl/testcore")
38+
3139
expected_doc = Document(
32-
id=doc["id"],
33-
fields={k: search_engine._normalize(v) for k, v in doc.items() if k != "id"}
40+
id="1",
41+
fields={
42+
"title": opensearch._normalize("test title"),
43+
"description": opensearch._normalize("test description")
44+
}
45+
)
46+
47+
def mock_post(*args, **kwargs):
48+
return MockResponseOpenSearchEngine([opensearch_hit], status_code=200)
49+
50+
monkeypatch.setattr(requests, "post", mock_post)
51+
52+
result = opensearch.fetch_for_query_generation(
53+
documents_filter=opensearch_config.documents_filter,
54+
doc_number=opensearch_config.doc_number,
55+
doc_fields=opensearch_config.doc_fields
3456
)
3557

36-
def post(*args, **kwargs):
37-
return MockResponseOpenSearchEngine([hit], status_code=200)
58+
assert len(result) == 1, "Expected one document"
59+
assert result[0] == expected_doc, "Mismatch in query generated doc"
3860

39-
monkeypatch.setattr(requests, "post", post)
4061

41-
result = search_engine.fetch_for_query_generation(
42-
documents_filter=config.documents_filter,
43-
doc_number=config.doc_number,
44-
doc_fields=config.doc_fields
62+
def test_fetch_for_evaluation(monkeypatch, opensearch_config, opensearch_hit):
63+
opensearch = OpenSearchEngine("http://testurl/testcore")
64+
65+
expected_doc = Document(
66+
id="1",
67+
fields={
68+
"title": opensearch._normalize("test title"),
69+
"description": opensearch._normalize("test description")
70+
}
4571
)
4672

47-
assert len(result) == 1
48-
assert result[0] == expected_doc
73+
def mock_post(*args, **kwargs):
74+
return MockResponseOpenSearchEngine([opensearch_hit], status_code=200)
4975

50-
result = search_engine.fetch_for_evaluation(
76+
monkeypatch.setattr(requests, "post", mock_post)
77+
78+
result = opensearch.fetch_for_evaluation(
79+
query_template=opensearch_config.query_template,
5180
keyword="car",
52-
query_template=config.query_template,
53-
doc_fields=config.doc_fields
81+
doc_fields=opensearch_config.doc_fields
5482
)
5583

56-
assert len(result) == 1
57-
assert result[0] == expected_doc
84+
assert len(result) == 1, "Expected one document"
85+
assert result[0] == expected_doc, "Mismatch in doc evaluation"
86+
87+
88+
def test_normalize():
89+
engine = OpenSearchEngine("http://dummy")
90+
91+
assert engine._normalize(" hello ") == ["hello"], "Failed to normalize string"
92+
assert engine._normalize(["a", " b "]) == ["a", "b"], "Failed to normalize list of strings"
93+
assert engine._normalize(123) == ["123"], "Failed to normalize integer"
94+
assert engine._normalize(None) == [], "Failed to normalize None"
95+
assert engine._normalize({"key": " value "}) == [json.dumps({"key": "value"})], "Failed to normalize dict"
96+

0 commit comments

Comments
 (0)