Skip to content
Closed
Show file tree
Hide file tree
Changes from all 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
77 changes: 5 additions & 72 deletions tests/serialization/test_serialization_json.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,24 +17,20 @@
from trpc_sdk.abc import BaseSerializer
from trpc_sdk.serialization import JsonData
from trpc_sdk.serialization import JsonSerializer
from trpc_sdk.serialization import json_to_pb_kwargs
from trpc_sdk.serialization import pb_to_json_kwargs
from trpc_sdk.serialization._serialization import _PROTOBUF_VERSION
from trpc_sdk.serialization._serialization import _USE_NEW_PARAM


def register_pb_json_format_kwargs(pb_kwargs=None, json_kwargs=None):
"""Update the serializer kwargs dicts in place.
def register_pb_json_format_kwargs(pb_kwargs=None):
"""Update ``pb_to_json_kwargs`` in place.

An empty mapping clears that side so JsonSerializer falls back to its
protobuf-version defaults. ``None`` leaves that side unchanged.
An empty mapping clears it so JsonSerializer falls back to its
protobuf-version defaults. ``None`` leaves it unchanged.
"""
if pb_kwargs is not None:
pb_to_json_kwargs.clear()
pb_to_json_kwargs.update(pb_kwargs)
if json_kwargs is not None:
json_to_pb_kwargs.clear()
json_to_pb_kwargs.update(json_kwargs)


# JsonSerializer tests
Expand Down Expand Up @@ -397,51 +393,10 @@ def test_register_pb_map_json_kwargs_with_pb_kwargs():
register_pb_json_format_kwargs(pb_kwargs={})


def test_register_pb_map_json_kwargs_with_json_kwargs():
"""Test register_pb_json_format_kwargs with json_kwargs"""
# Register custom json_kwargs
custom_json_kwargs = {"ignore_unknown_fields": False}
register_pb_json_format_kwargs(json_kwargs=custom_json_kwargs)

serializer = JsonSerializer()
request = HelloRequest()
request.msg = "Test"

serialized = serializer.serialize(request)

# Deserialize with custom kwargs
new_request = HelloRequest()
serializer.deserialize(serialized, new_request)
assert new_request.msg == "Test"

# Reset to default
register_pb_json_format_kwargs(json_kwargs={})


def test_register_pb_map_json_kwargs_with_both():
"""Test register_pb_json_format_kwargs with both pb_kwargs and json_kwargs"""
custom_pb_kwargs = {"use_integers_for_enums": True}
custom_json_kwargs = {"ignore_unknown_fields": True}

register_pb_json_format_kwargs(pb_kwargs=custom_pb_kwargs, json_kwargs=custom_json_kwargs)

serializer = JsonSerializer()
request = HelloRequest()
request.msg = "Test both kwargs"

serialized = serializer.serialize(request)
new_request = HelloRequest()
serializer.deserialize(serialized, new_request)
assert new_request.msg == "Test both kwargs"

# Reset to default
register_pb_json_format_kwargs(pb_kwargs={}, json_kwargs={})


def test_register_pb_map_json_kwargs_with_none():
"""Test register_pb_json_format_kwargs with None parameters"""
# Should not raise any exception
register_pb_json_format_kwargs(pb_kwargs=None, json_kwargs=None)
register_pb_json_format_kwargs(pb_kwargs=None)

serializer = JsonSerializer()
request = HelloRequest()
Expand Down Expand Up @@ -551,28 +506,6 @@ def test_pb_serialize_with_custom_kwargs():
register_pb_json_format_kwargs(pb_kwargs={})


def test_pb_deserialize_with_custom_kwargs():
"""Test _pb_deserialize with custom kwargs registered"""
serializer = JsonSerializer()

# First serialize a message
request = HelloRequest()
request.msg = "Deserialize test"
serialized = serializer.serialize(request)

# Register custom json_kwargs
custom_kwargs = {"ignore_unknown_fields": True}
register_pb_json_format_kwargs(json_kwargs=custom_kwargs)

# Deserialize with custom kwargs
new_request = HelloRequest()
serializer._pb_deserialize(serialized, new_request)
assert new_request.msg == "Deserialize test"

# Reset
register_pb_json_format_kwargs(json_kwargs={})


def test_json_data_field_default_factory():
"""Test JsonData field default factory"""
# Create multiple JsonData instances
Expand Down
8 changes: 1 addition & 7 deletions trpc_sdk/serialization/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
The package is split by responsibility:

- :mod:`~trpc_sdk.serialization._types` — ``SerializationType``, ``JsonData``, ``Body``
- :mod:`~trpc_sdk.serialization._serialization` — JSON / protobuf / noop / JCE / WUP plugins
- :mod:`~trpc_sdk.serialization._serialization` — JSON / protobuf / noop plugins
- :mod:`~trpc_sdk.serialization._utils` — ``serialize`` / ``deserialize`` / ``get_serializer``
- :mod:`~trpc_sdk.serialization._constants` — ``SerializationCode`` wire values

Expand All @@ -21,12 +21,9 @@

from __future__ import annotations

from ._serialization import JceSerializer
from ._serialization import JsonSerializer
from ._serialization import NoopSerializer
from ._serialization import ProtoSerializer
from ._serialization import WupSerializer
from ._serialization import json_to_pb_kwargs
from ._serialization import pb_to_json_kwargs
from ._types import Body
from ._types import JsonData
Expand All @@ -44,9 +41,6 @@
"JsonData",
"Body",
"pb_to_json_kwargs",
"json_to_pb_kwargs",
"ProtoSerializer",
"NoopSerializer",
"JceSerializer",
"WupSerializer",
]
101 changes: 10 additions & 91 deletions trpc_sdk/serialization/_serialization.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,9 @@
"""Built-in ContentType serializer plugins.

This is the merged copy of the historical ``serialization_json`` /
``serialization_proto`` / ``serialization_noop`` / ``serialization_jce``
/ ``serialization_wup`` modules. Importing it (which
:mod:`trpc_sdk.serialization` does) registers every built-in serializer,
JCE (1) and WUP (200) included.

``jcepy`` is imported on first JCE / WUP use so processes that never
send those encodings do not need the optional dependency.
``serialization_proto`` / ``serialization_noop`` modules. Importing it
(which :mod:`trpc_sdk.serialization` does) registers every built-in
serializer.
"""

from __future__ import annotations
Expand All @@ -39,21 +35,21 @@
_PROTOBUF_VERSION = tuple(int(x) for x in google.protobuf.__version__.split(".")[:2])
_USE_NEW_PARAM = _PROTOBUF_VERSION >= (5, 26)

# Extra kwargs for MessageToJson / Parse used by JsonSerializer. Update in
# place (``pb_to_json_kwargs.update(...)``); rebinding the name after
# Extra kwargs for MessageToJson used by JsonSerializer. Update in place
# (``pb_to_json_kwargs.update(...)``); rebinding the name after
# ``from ... import`` does not reach this module.
pb_to_json_kwargs = {}
json_to_pb_kwargs = {}


@register_plugin(PluginType.SERIALIZATION, SerializationType.JSON, init_pos=PluginInitPos.WORKER)
class JsonSerializer(BaseSerializer):
"""JSON serializer registered as ``SerializationType.JSON``.

Accepts either a :class:`JsonData` dict wrapper or a protobuf
``Message``. Protobuf conversion uses :data:`pb_to_json_kwargs` /
:data:`json_to_pb_kwargs` when they are set; otherwise it picks the
protobuf 5.26+ vs older ``MessageToJson`` parameter names.
``Message``. Protobuf-to-JSON conversion uses :data:`pb_to_json_kwargs`
when it is set; otherwise it picks the protobuf 5.26+ vs older
``MessageToJson`` parameter names. JSON-to-protobuf conversion always
ignores unknown fields.
"""

def _pb_serialize(self, body: PbMessage) -> bytes:
Expand Down Expand Up @@ -90,16 +86,12 @@ def _pb_serialize(self, body: PbMessage) -> bytes:
def _pb_deserialize(self, data: bytes, body: PbMessage) -> None:
"""Populate a protobuf message from JSON bytes.

Uses :data:`json_to_pb_kwargs` when present; otherwise
``ignore_unknown_fields=True``.
Unknown JSON fields are ignored.

Args:
data: JSON bytes.
body: Protobuf message mutated in place.
"""
if json_to_pb_kwargs:
Parse(data, body, **json_to_pb_kwargs)
return
Parse(data, body, ignore_unknown_fields=True)

def _json_serialize(self, body: JsonData) -> bytes:
Expand Down Expand Up @@ -211,76 +203,3 @@ def deserialize(self, data: bytes, body: Any) -> None:
"""
if isinstance(body, Body):
body.data = data


@register_plugin(PluginType.SERIALIZATION, SerializationType.JCE, init_pos=PluginInitPos.WORKER)
class JceSerializer(BaseSerializer):
"""JCE serializer registered as ``SerializationType.JCE``.

``jcepy.core.tafcore`` is imported on first use. Output uses
``JceOutputStream.bodySerilization`` (the jcepy spelling). Input
skips the leading int32 tag and copies deserialized fields onto
``body``.
"""

def serialize(self, body: Any) -> bytes:
"""Serialize ``body`` with a JCE output stream.

Args:
body: JCE-capable application object.
"""
from jcepy.core import tafcore

oos = tafcore.JceOutputStream()
oos.bodySerilization(body)
return oos.getBuffer()

def deserialize(self, data: bytes, body: Any) -> None:
"""Populate ``body`` from JCE bytes.

Args:
data: JCE-encoded body bytes.
body: Object whose attributes are overwritten from the
deserialized result.
"""
from jcepy.core import tafcore

ios = tafcore.JceInputStream(data)
ios.read(tafcore.int32, 0, True)
res = ios.bodydeserialize(body)
for item in res.__dict__.items():
setattr(body, str(item[0]), item[1])


@register_plugin(PluginType.SERIALIZATION, SerializationType.Wup, init_pos=PluginInitPos.WORKER)
class WupSerializer(BaseSerializer):
"""Taf WUP serializer registered as ``SerializationType.Wup``.

``jcepy.core.tafcore`` is imported on first use. WUP is the Taf
dictionary packet (``TafUniPacket``), not the raw JCE stream used
by :class:`JceSerializer`.
"""

def serialize(self, body: Any) -> bytes:
"""Serialize ``body`` with ``TafUniPacket.WUPserialize``.

Args:
body: WUP-capable application object.
"""
from jcepy.core import tafcore

up = tafcore.TafUniPacket()
return up.WUPserialize(body)

def deserialize(self, data: bytes, body: Any) -> None:
"""Populate ``body`` from a WUP packet.

Args:
data: WUP-encoded body bytes.
body: Object to populate via ``WUPdeserialize``.
"""
from jcepy.core import tafcore

up = tafcore.TafUniPacket()
up.deserialize(data)
up.WUPdeserialize(body)
Loading