Coverage for tests/utils/context/serializable_context.py: 87%

23 statements  

« prev     ^ index     » next       coverage.py v7.17.3, created at 2026-11-22 19:49 +0000

1from __future__ import annotations 

2 

3import json 

4 

5from abc import ABC, abstractmethod 

6from typing import Any, TypeVar 

7 

8T = TypeVar("T", bound="SerializableContext") 

9 

10 

11class SerializableContext(ABC): 

12 """Base class for test contexts that can be serialized to JSON. 

13 

14 Mirrors monero-cpp's ``serializable_struct``: :meth:`serialize` emits a 

15 compact JSON string holding only the fields that are defined (i.e. not 

16 ``None``), while :meth:`deserialize` rebuilds an instance from such a string 

17 through the subclass' :meth:`from_dict`. 

18 """ 

19 

20 __test__ = False 

21 

22 def serialize(self) -> str: 

23 """Serialize this context to a compact JSON string. 

24 

25 :returns str: the context serialized to a JSON string. 

26 """ 

27 return json.dumps(self.to_dict(), separators=(",", ":")) 

28 

29 @abstractmethod 

30 def to_dict(self) -> dict[str, Any]: 

31 """Build the JSON object for this context, adding only defined fields. 

32 

33 Analogous to monero-cpp's ``to_rapidjson_val``. 

34 

35 :returns dict[str, Any]: the context as a JSON-serializable dict. 

36 """ 

37 ... 

38 

39 @classmethod 

40 def deserialize(cls: type[T], context_json: str) -> T: 

41 """Deserialize a context from a JSON string. 

42 

43 :param str context_json: context in JSON format. 

44 :returns SerializableContext: deserialized instance. 

45 """ 

46 ctx: T = cls() 

47 cls.from_dict(json.loads(context_json), ctx) 

48 return ctx 

49 

50 @staticmethod 

51 @abstractmethod 

52 def from_dict(node: dict[str, Any], ctx: Any) -> None: 

53 """Populate ``ctx`` from a parsed JSON object. 

54 

55 Analogous to monero-cpp's ``from_property_tree``. 

56 

57 :param dict[str, Any] node: parsed JSON object. 

58 :param SerializableContext ctx: instance to populate. 

59 """ 

60 ... 

61 

62 @staticmethod 

63 def _put(root: dict[str, Any], key: str, value: Any) -> None: 

64 """Add ``key`` -> ``value`` to ``root`` only when ``value`` is defined. 

65 

66 :param dict[str, Any] root: JSON object being built. 

67 :param str key: member name. 

68 :param Any value: member value, skipped when ``None``. 

69 """ 

70 if value is not None: 

71 root[key] = value