|
| 1 | +from unittest.mock import Mock |
| 2 | + |
| 3 | +import pytest |
| 4 | + |
| 5 | +from haystack.preview.testing.factory import store_class |
| 6 | +from haystack.preview.document_stores.decorator import _default_store_to_dict, _default_store_from_dict |
| 7 | +from haystack.preview.document_stores.errors import StoreDeserializationError |
| 8 | + |
| 9 | + |
| 10 | +@pytest.mark.unit |
| 11 | +def test_default_store_to_dict(): |
| 12 | + MyStore = store_class("MyStore") |
| 13 | + comp = MyStore() |
| 14 | + res = _default_store_to_dict(comp) |
| 15 | + assert res == {"hash": id(comp), "type": "MyStore", "init_parameters": {}} |
| 16 | + |
| 17 | + |
| 18 | +@pytest.mark.unit |
| 19 | +def test_default_store_to_dict_with_custom_init_parameters(): |
| 20 | + extra_fields = {"init_parameters": {"custom_param": True}} |
| 21 | + MyStore = store_class("MyStore", extra_fields=extra_fields) |
| 22 | + comp = MyStore() |
| 23 | + res = _default_store_to_dict(comp) |
| 24 | + assert res == {"hash": id(comp), "type": "MyStore", "init_parameters": {"custom_param": True}} |
| 25 | + |
| 26 | + |
| 27 | +@pytest.mark.unit |
| 28 | +def test_default_store_from_dict(): |
| 29 | + MyStore = store_class("MyStore") |
| 30 | + comp = _default_store_from_dict(MyStore, {"type": "MyStore"}) |
| 31 | + assert isinstance(comp, MyStore) |
| 32 | + |
| 33 | + |
| 34 | +@pytest.mark.unit |
| 35 | +def test_default_store_from_dict_with_custom_init_parameters(): |
| 36 | + def store_init(self, custom_param: int): |
| 37 | + self.custom_param = custom_param |
| 38 | + |
| 39 | + extra_fields = {"__init__": store_init} |
| 40 | + MyStore = store_class("MyStore", extra_fields=extra_fields) |
| 41 | + comp = _default_store_from_dict(MyStore, {"type": "MyStore", "init_parameters": {"custom_param": 100}}) |
| 42 | + assert isinstance(comp, MyStore) |
| 43 | + assert comp.custom_param == 100 |
| 44 | + |
| 45 | + |
| 46 | +@pytest.mark.unit |
| 47 | +def test_default_store_from_dict_without_type(): |
| 48 | + with pytest.raises(StoreDeserializationError, match="Missing 'type' in store serialization data"): |
| 49 | + _default_store_from_dict(Mock, {}) |
| 50 | + |
| 51 | + |
| 52 | +@pytest.mark.unit |
| 53 | +def test_default_store_from_dict_unregistered_store(request): |
| 54 | + # We use the test function name as store name to make sure it's not registered. |
| 55 | + # Since the registry is global we risk to have a store with the same name registered in another test. |
| 56 | + store_name = request.node.name |
| 57 | + |
| 58 | + with pytest.raises(StoreDeserializationError, match=f"Store '{store_name}' can't be deserialized as 'Mock'"): |
| 59 | + _default_store_from_dict(Mock, {"type": store_name}) |
0 commit comments