Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Pickle support #372

Merged
merged 7 commits into from
Dec 19, 2024
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions odxtools/nameditemlist.py
Original file line number Diff line number Diff line change
Expand Up @@ -189,6 +189,16 @@ def __deepcopy__(self, memo: Dict[int, Any]) -> Any:

return result

def __reduce__(self) -> Tuple[Any, ...]:
nada-ben-ali marked this conversation as resolved.
Show resolved Hide resolved
"""Support for Python's pickle protocol.
This method ensures that the object can be reconstructed with its current state,
using its class and the list of items it contains.
It returns a tuple containing the reconstruction function (the class)
and its arguments necessary to recreate the object.

"""
return self.__class__, (list(self),)


class NamedItemList(ItemAttributeList[T]):

Expand Down
9 changes: 7 additions & 2 deletions odxtools/tablerow.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# SPDX-License-Identifier: MIT
from dataclasses import dataclass
from typing import TYPE_CHECKING, Any, Dict, List, Optional
from dataclasses import dataclass, fields
from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple
from xml.etree import ElementTree

from .basicstructure import BasicStructure
Expand Down Expand Up @@ -157,3 +157,8 @@ def structure(self) -> Optional[BasicStructure]:
def dop(self) -> Optional[DataObjectProperty]:
"""The data object property object resolved by dop_ref."""
return self._dop

def __reduce__(self) -> Tuple[Any, ...]:
"""This ensures that the object can be correctly reconstructed during unpickling."""
state = self.__dict__.copy()
return self.__class__, tuple([getattr(self, x.name) for x in fields(self)]), state
nada-ben-ali marked this conversation as resolved.
Show resolved Hide resolved
7 changes: 7 additions & 0 deletions tests/test_decoding.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
# SPDX-License-Identifier: MIT
import pickle
import unittest

from odxtools.compumethods.compuinternaltophys import CompuInternalToPhys
Expand Down Expand Up @@ -2447,6 +2448,12 @@ def test_decode_response(self) -> None:
self.assertEqual(expected_message.coding_object, decoded_message.coding_object)
self.assertEqual(expected_message.param_dict, decoded_message.param_dict)

# check object serialization and deserialization using pickle
pickled_ecu_var = pickle.dumps(ecu_variant)
unpickled_ecu_var = pickle.loads(pickled_ecu_var)

self.assertEqual(ecu_variant, unpickled_ecu_var)

def test_code_dtc(self) -> None:
odxlinks = OdxLinkDatabase()
diag_coded_type = StandardLengthType(
Expand Down
6 changes: 6 additions & 0 deletions tests/test_diag_data_dictionary_spec.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
# SPDX-License-Identifier: MIT
import pickle
import unittest
from copy import copy

Expand Down Expand Up @@ -428,6 +429,11 @@ def test_initialization(self) -> None:
decoded = mux.decode_from_pdu(decode_state)
self.assertEqual(decoded, ("default_case", {}))

# check that the object can be properly serialized and deserialized using pickle
nada-ben-ali marked this conversation as resolved.
Show resolved Hide resolved
pickled_ddds = pickle.dumps(ddds)
unpickled_ddds = pickle.loads(pickled_ddds)
self.assertEqual(ddds, unpickled_ddds)


if __name__ == "__main__":
unittest.main()
25 changes: 19 additions & 6 deletions tests/test_odxtools.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
# SPDX-License-Identifier: MIT
import pickle
import unittest
from dataclasses import dataclass
from typing import List
Expand Down Expand Up @@ -90,16 +91,28 @@ def test_encode_response_with_matching_request_param_and_structure(self) -> None
self.assertEqual(bytes(coded_response), bytes.fromhex("faba03"))


@dataclass
class X:
short_name: str
value: int


class TestNamedItemList(unittest.TestCase):

def test_NamedItemList(self) -> None:
def setUp(self):
self.foo_obj = NamedItemList([X("hello", 0), X("world", 1)])

def test_NamedItemList(self):
# Test with the original object
foo = self.foo_obj.__class__(self.foo_obj)
nada-ben-ali marked this conversation as resolved.
Show resolved Hide resolved
self._test_NamedItemList_functionality(foo)

@dataclass
class X:
short_name: str
value: int
# Test with the pickled object
pickled_foo = pickle.dumps(self.foo_obj)
unpickled_foo = pickle.loads(pickled_foo)
self._test_NamedItemList_functionality(unpickled_foo)

foo = NamedItemList([X("hello", 0), X("world", 1)])
def _test_NamedItemList_functionality(self, foo):
self.assertEqual(foo.hello, X("hello", 0))
self.assertEqual(foo[0], X("hello", 0))
self.assertEqual(foo[1], X("world", 1))
Expand Down
Loading