Coverage for Users/vladimirpavlov/PycharmProjects/parameterizable/tests/test_json_processor_extra.py: 94%

1 import json

2 import importlib

3 import pytest

4

5 from mixinforge.json_processor import (

6 _to_serializable_dict,

7 _from_serializable_dict,

8 _Markers,

9)

10

11

12 class StrSlots:

13 __slots__ = "w"

14

15 def __init__(self, w):

16 self.w = w

17

18

19 class TwoSlots:

20 __slots__ = ("u", "v")

21

22 def __init__(self, u=0, v=0):

23 self.u = u

24 self.v = v

25

26

27 def test_to_from_with_string_slots():

28 obj = StrSlots("hello")

29 ser = _to_serializable_dict(obj)

30 back = _from_serializable_dict(ser)

31 assert isinstance(back, StrSlots)

32 assert back.w == "hello"

33

34

35 def test_recreate_object_tuple_state_swapped_components():

36 # Craft state where first element is dict_values and second is slot values list

37 state_tuple = ({}, [10, 20])

38 payload = {

39 _Markers.MODULE: __name__,

40 _Markers.CLASS: "TwoSlots",

41 _Markers.STATE: _to_serializable_dict(state_tuple),

42 }

43 back = _from_serializable_dict(payload)

44 assert isinstance(back, TwoSlots)

45 assert back.u == 10 and back.v == 20

46

47

48 def test_recreate_object_tuple_state_fallback_pair_becomes_slots():

49 # Neither element is dict or list/tuple, so fallback treats entire state as slot values

50 state_tuple = (1, 2)

51 payload = {

52 _Markers.MODULE: __name__,

53 _Markers.CLASS: "TwoSlots",

54 _Markers.STATE: _to_serializable_dict(state_tuple),

55 }

56 back = _from_serializable_dict(payload)

57 assert isinstance(back, TwoSlots)

58 assert back.u == 1 and back.v == 2

59

60

61 def test_from_serializable_plain_dict_is_unsupported():

62 with pytest.raises(TypeError):

63 _from_serializable_dict({"a": 1, "b": 2})

64