Skip to content

Commit e1c3d56

Browse files
FIX: Correct DataStore loading and update tests - bad rebase
1 parent c56149b commit e1c3d56

2 files changed

Lines changed: 56 additions & 108 deletions

File tree

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

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -197,9 +197,8 @@ def load_tmp_file_content(self) -> None:
197197
for query_id, context_dict in queries.items():
198198
context: QueryRatingContext = QueryRatingContext.from_dict(context_dict)
199199
self._queries_by_id[query_id] = context
200-
self._query_text_to_query_id[context.get_query()] = query_id
200+
self._query_text_to_query_id[context.get_query_text()] = query_id
201201

202202
documents = file_content.get("documents", {})
203203
for doc_id, doc_data in documents.items():
204204
self.add_document(doc_id, Document.model_validate(doc_data))
205-
Lines changed: 55 additions & 106 deletions
Original file line numberDiff line numberDiff line change
@@ -1,36 +1,23 @@
11
import json
22
from pathlib import Path
3+
from typing import Any
34

4-
import pytest
5-
from pathlib import Path
6-
from typing import Any, Dict
7-
8-
import importlib
9-
import json
10-
11-
import json
125
import pytest
136

147
from src.model.document import Document
15-
from src.search_engine.data_store import DataStore
16-
from src.search_engine import data_store
8+
from src.search_engine.data_store import DataStore, TMP_FILE
179

1810

1911
@pytest.fixture
20-
def empty_store():
12+
def empty_store() -> DataStore:
13+
"""Fixture for an empty DataStore that ignores any saved data."""
2114
return DataStore(ignore_saved_data=True)
2215

2316

24-
# -------------------- Helpers --------------------
2517

26-
def _read_json(path: Path):
27-
return json.loads(path.read_text(encoding="utf-8"))
28-
29-
def _write_json(path: Path, obj: Any):
30-
path.write_text(json.dumps(obj, indent=2, ensure_ascii=False), encoding="utf-8")
31-
32-
def _mk_ds_with_sample_data(save_documents: bool) -> DataStore:
33-
ds = DataStore(save_documents=save_documents, ignore_saved_data=True)
18+
def mock_datastore_with_sample_data() -> DataStore:
19+
"""Helper to create a DataStore instance with sample data."""
20+
ds = DataStore(ignore_saved_data=True)
3421
d1 = Document(id="d1", fields={"title": "AI", "text": "Deep learning"})
3522
d2 = Document(id="d2", fields={"title": "LLMs", "text": "Transformers"})
3623
ds.add_document(d1.id, d1)
@@ -45,114 +32,76 @@ def _mk_ds_with_sample_data(save_documents: bool) -> DataStore:
4532

4633
# -------------------- Unit tests (in-memory) --------------------
4734

48-
def test_add_and_get_document__expects__documents_stored_in_data_store():
49-
ds = DataStore(ignore_saved_data=True)
35+
def test_add_and_get_document__expects__documents_stored_in_data_store(empty_store: DataStore):
5036
docs = [
5137
Document(id="doc1", fields={"title": "Gadgets", "description": "Cutting edge technologies are on demand."}),
5238
Document(id="doc2", fields={"title": "Airpods", "description": "The quality of airpods from Apple is getting worse."}),
5339
Document(id="doc3", fields={"title": "MacBook Pro", "description": "The price of Apple laptops has been skyrocketed."}),
5440
]
5541
for d in docs:
56-
ds.add_document(d.id, d)
42+
empty_store.add_document(d.id, d)
5743

58-
assert ds.get_document("doc1") == docs[0]
59-
assert ds.get_document("doc2") == docs[1]
60-
assert ds.get_document("doc3") == docs[2]
44+
assert empty_store.get_document("doc1") == docs[0]
45+
assert empty_store.get_document("doc2") == docs[1]
46+
assert empty_store.get_document("doc3") == docs[2]
6147

6248

63-
def test_add_and_get_query__expects__query_stored_in_data_store_and_check_same_queries():
64-
ds = DataStore(ignore_saved_data=True)
65-
# Alta de queries
66-
qid1 = ds.add_query("technology", "doc1")
67-
assert ds.get_query(qid1).get_query_text() == "technology"
49+
def test_add_and_get_query__expects__query_stored_and_reused(empty_store: DataStore):
50+
# Add new queries
51+
qid1 = empty_store.add_query("technology", "doc1")
52+
assert empty_store.get_query(qid1).get_query_text() == "technology"
6853

69-
qid2 = ds.add_query("airpods", "doc2")
70-
assert ds.get_query(qid2).get_query_text() == "airpods"
54+
qid2 = empty_store.add_query("airpods", "doc2")
55+
assert empty_store.get_query(qid2).get_query_text() == "airpods"
7156

72-
# Misma query con nuevo doc_id -> reaprovecha el mismo query_id
73-
qid3 = ds.add_query("technology", "doc3")
57+
# Same query with a new doc_id -> should reuse the same query_id
58+
qid3 = empty_store.add_query("technology", "doc3")
7459
assert qid1 == qid3
75-
assert set(ds.get_query(qid3).get_doc_ids()) == {"doc1", "doc3"}
60+
assert set(empty_store.get_query(qid3).get_doc_ids()) == {"doc1", "doc3"}
7661

7762

78-
def test_datastore_add_query__expect__query_rating_and_has_rating(empty_store):
63+
def test_datastore_add_query__expects__rating_can_be_added_and_checked(empty_store: DataStore):
7964
qid = empty_store.add_query("test", doc_id="d1")
8065
# sentinel: without rating yet
8166
assert empty_store.has_rating_score(qid, "d1") is False
8267
empty_store.add_rating_score(qid, "d1", 1)
8368
assert empty_store.get_rating_score(qid, "d1") == 1
8469
assert empty_store.has_rating_score(qid, "d1") is True
8570

86-
@pytest.mark.parametrize("save_documents, expects_documents_key", [(True, True), (False, False)])
87-
def test_save_tmp_file_content__expect__json_file_is_created_with_or_without_documents(tmp_path: Path, save_documents: bool, expects_documents_key: bool):
88-
ds = _mk_ds_with_sample_data(save_documents)
89-
# path = tmp_path / "datastore.json"
90-
ds.save_tmp_file_content()
9171

92-
newDataStore = DataStore(ignore_saved_data=False)
93-
for context_1, context_2 in zip(ds.get_queries(), newDataStore.get_queries()):
94-
assert context_1.get_query() == context_2.get_query()
95-
assert context_1.get_query_id() == context_2.get_query_id()
96-
assert set(context_1.get_doc_ids()) == set(context_2.get_doc_ids())
72+
def test_save_and_load_tmp_file__expects__state_is_persisted_and_restored(tmp_path):
73+
"""Tests that data store content is correctly saved and loaded from the default file."""
74+
# 1. Create a datastore, add data, and save it
75+
ds1 = mock_datastore_with_sample_data()
76+
ds1.save_tmp_file_content()
9777

98-
# Auto load in __init__ because ignore_saved_data=False
78+
# 2. Create a new datastore, which should auto-load the file
9979
ds2 = DataStore(ignore_saved_data=False)
100-
assert ds2.get_query(qid).get_query_text() == "test"
101-
assert ds2.get_rating_score(qid, "d1") == 1
102-
assert ds2.get_document("d1") == doc
103-
104-
# def test_load_tmp_file_content__expect__datastore_state_is_restored(tmp_path):
105-
# content = [{
106-
# "query_id": "q1",
107-
# "query_text": "ai",
108-
# "doc_ratings": {"d1": 1, "d2": 0},
109-
# "documents": [
110-
# {"id": "d1", "fields": {"title": "AI", "text": "Deep learning"}},
111-
# {"id": "d2", "fields": {"title": "LLMs", "text": "Transformers"}},
112-
# ],
113-
# }]
114-
# path = tmp_path / "datastore.json"
115-
# _write_json(path, content)
116-
#
117-
# ds = DataStore()
118-
# ds.load_tmp_file_content(path, clear=True)
119-
#
120-
# assert ds.get_query("q1").get_query() == "ai"
121-
# assert ds.get_rating_score("q1", "d1") == 1
122-
# assert ds.get_rating_score("q1", "d2") == 0
123-
# assert ds.get_document("d1").fields["title"] == "AI"
124-
# assert ds.get_document("d2").fields["text"] == "Transformers"
125-
126-
127-
# def test_load_tmp_file_content_with_shared_document__expects__no_duplication(tmp_path):
128-
# content = [
129-
# {"query_id": "q1", "query_text": "q one", "doc_ratings": {"d1": 1},
130-
# "documents": [{"id": "d1", "fields": {"title": "AI", "text": "X"}}]},
131-
# {"query_id": "q2", "query_text": "q two", "doc_ratings": {"d1": 0},
132-
# "documents": [{"id": "d1", "fields": {"title": "AI", "text": "X"}}]},
133-
# ]
134-
# path = tmp_path / "datastore.json"
135-
# _write_json(path, content)
136-
#
137-
# ds = DataStore()
138-
# ds.load_tmp_file_content(path, clear=True)
139-
#
140-
# assert ds.get_document("d1") is not None
141-
# assert ds.get_rating_score("q1", "d1") == 1
142-
# assert ds.get_rating_score("q2", "d1") == 0
143-
144-
#
145-
# def test_save_tmp_file_content_to_custom_path__expects__file_is_created(tmp_path):
146-
# ds = DataStore()
147-
# qid = ds.add_query("q", None)
148-
# ds.add_rating_score(qid, "dX", 1)
149-
#
150-
# path = tmp_path / "subdir" / "custom.json"
151-
# assert not path.exists()
152-
# ds.save_tmp_file_content(path)
153-
#
154-
# assert path.exists()
155-
# data = _read_json(path)
156-
# assert isinstance(data, list) and len(data) == 1
157-
#
15880

81+
# 3. Verify that the loaded data is correct
82+
assert len(ds1.get_queries()) == len(ds2.get_queries())
83+
assert len(ds1.get_documents()) == len(ds2.get_documents())
84+
85+
# Check a specific query and its ratings
86+
qid = ds1._query_text_to_query_id["artificial intelligence"]
87+
loaded_q = ds2.get_query(qid)
88+
assert loaded_q.get_query_text() == "artificial intelligence"
89+
assert loaded_q.get_rating_score("d1") == 1
90+
assert loaded_q.get_rating_score("d2") == 0
91+
92+
# Check that documents were loaded correctly
93+
doc = ds2.get_document("d1")
94+
assert doc is not None
95+
assert doc.fields["title"] == "AI"
96+
97+
98+
# Ensure the temporary file is cleaned up after tests
99+
@pytest.fixture(autouse=True)
100+
def cleanup_tmp_file():
101+
"""Clean up the default tmp file before and after each test."""
102+
tmp_file = Path(TMP_FILE)
103+
if tmp_file.exists():
104+
tmp_file.unlink()
105+
yield
106+
if tmp_file.exists():
107+
tmp_file.unlink()

0 commit comments

Comments
 (0)