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
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-22 19:49 +0000
1from __future__ import annotations
3import json
5from abc import ABC, abstractmethod
6from typing import Any, TypeVar
8T = TypeVar("T", bound="SerializableContext")
11class SerializableContext(ABC):
12 """Base class for test contexts that can be serialized to JSON.
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 """
20 __test__ = False
22 def serialize(self) -> str:
23 """Serialize this context to a compact JSON string.
25 :returns str: the context serialized to a JSON string.
26 """
27 return json.dumps(self.to_dict(), separators=(",", ":"))
29 @abstractmethod
30 def to_dict(self) -> dict[str, Any]:
31 """Build the JSON object for this context, adding only defined fields.
33 Analogous to monero-cpp's ``to_rapidjson_val``.
35 :returns dict[str, Any]: the context as a JSON-serializable dict.
36 """
37 ...
39 @classmethod
40 def deserialize(cls: type[T], context_json: str) -> T:
41 """Deserialize a context from a JSON string.
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
50 @staticmethod
51 @abstractmethod
52 def from_dict(node: dict[str, Any], ctx: Any) -> None:
53 """Populate ``ctx`` from a parsed JSON object.
55 Analogous to monero-cpp's ``from_property_tree``.
57 :param dict[str, Any] node: parsed JSON object.
58 :param SerializableContext ctx: instance to populate.
59 """
60 ...
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.
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