blob: 89dbbf1a69423f129b7ec7fa96e8dbeb3cf38576 [file]
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
from __future__ import annotations
import enum
from dataclasses import dataclass, make_dataclass
from typing import Dict, Generic, List, Optional, Set, Tuple, TypeVar
import pytest
import pyfory
from pyfory import Fory, ThreadSafeFory
from pyfory.error import TypeUnregisteredError
from pyfory.meta.typedef import TYPE_DEF_FIELD_BEARING_FLAG, TYPE_DEF_IDENTITY_SHIFT
from pyfory.meta.typedef_decoder import decode_typedef
from pyfory.meta.typedef_encoder import encode_typedef, prepend_header
from pyfory.serialization import Buffer
from pyfory.types import IdentityKind, TypeId
from pyfory.union import Union, UnionSerializer
class Player(enum.Enum):
JAVA = 0
FLASH = 1
class Size(enum.Enum):
SMALL = 0
LARGE = 1
@dataclass
class Media:
uri: str
title: Optional[str]
width: pyfory.Int32
height: pyfory.Int32
format: str
duration: pyfory.Int64
size: pyfory.Int64
bitrate: pyfory.Int32
has_bitrate: bool
persons: List[str]
player: Player
copyright: Optional[str]
@dataclass
class Image:
uri: str
title: Optional[str]
width: pyfory.Int32
height: pyfory.Int32
size: Size
@dataclass
class MediaContent:
media: Media
images: List[Image]
@dataclass(frozen=True)
class Point2D:
x: pyfory.Float64
y: pyfory.Float64
@dataclass(frozen=True)
class Vector2D:
x: pyfory.Float64
y: pyfory.Float64
@dataclass
class Ray:
origin: Point2D
direction: Vector2D
@dataclass
class Point3D:
x: pyfory.Float64
y: pyfory.Float64
z: pyfory.Float64
@dataclass
class Ray3D:
origin: Point3D
direction: Point3D
@dataclass
class Order:
order_id: pyfory.Int64
amount: pyfory.Float64
@dataclass
class UserRecord:
user_id: pyfory.Int64
name: str
T = TypeVar("T")
@dataclass
class PageResult(Generic[T]):
total: pyfory.Int32
items: List[T]
@dataclass
class CyclicNode:
name: str
next: Optional["CyclicNode"] = pyfory.field(default=None, ref=True, nullable=True)
@dataclass
class RemovedPayload:
tag: str
count: pyfory.Int32
@dataclass
class RemoteWithRemoved:
kept: pyfory.Int32
removed_single: RemovedPayload
removed_list: List[RemovedPayload]
removed_map: Dict[str, RemovedPayload]
@dataclass
class LocalWithoutRemoved:
kept: pyfory.Int32
@dataclass
class BaseAnimal:
name: str
@dataclass
class SubDog(BaseAnimal):
bark_volume: pyfory.Int32
@dataclass
class OtherAnimal:
name: str
@dataclass
class AnimalHolder:
pet: BaseAnimal
@dataclass
class ReduceDataclass:
x: pyfory.Int32
def __reduce__(self):
return (ReduceDataclass, (self.x,))
class PlainUnregistered:
def __init__(self, value: int):
self.value = value
@pyfory.dataclass(evolving=False)
class NonEvolvingStruct:
a: pyfory.Int32
b: str
class SampleUnion(Union):
@classmethod
def _from_case_id(cls, case_id: int, value: object):
return cls(case_id, value)
class SampleUnionSerializer(UnionSerializer):
def __init__(self, type_resolver, cls):
super().__init__(type_resolver, cls, {0: Point2D, 1: Order})
def _make_media_content() -> MediaContent:
return MediaContent(
media=Media(
uri="http://javaone.com/keynote.ogg",
title="Javaone Keynote",
width=640,
height=480,
format="video/theora",
duration=18000000,
size=58982400,
bitrate=262144,
has_bitrate=True,
persons=["Bill Gates, Jr.", "Steven Jobs"],
player=Player.JAVA,
copyright="Copyright (c) 2009, Scooby Dooby Doo",
),
images=[
Image(
uri="http://javaone.com/keynote_huge.jpg",
title="Javaone Keynote",
width=32000,
height=24000,
size=Size.LARGE,
),
Image(
uri="http://javaone.com/keynote_small.jpg",
title="Javaone Keynote",
width=320,
height=240,
size=Size.SMALL,
),
],
)
def _register_media(fory: Fory, by_name: bool = False):
if by_name:
fory.register_type(Player, name="bench.Player")
fory.register_type(Size, name="bench.Size")
fory.register_type(Media, name="bench.Media")
fory.register_type(Image, name="bench.Image")
fory.register_type(MediaContent, name="bench.MediaContent")
else:
fory.register_type(Player, type_id=1)
fory.register_type(Size, type_id=2)
fory.register_type(Media, type_id=3)
fory.register_type(Image, type_id=4)
fory.register_type(MediaContent, type_id=5)
@pytest.mark.parametrize("xlang", [True, False])
def test_root_header_protocol_generation(xlang):
fory = Fory(xlang=xlang, compatible=True)
data = fory.serialize(42)
expected_bitmap = 0x41 if xlang else 0x40
assert data[0] == expected_bitmap
assert fory.deserialize(data) == 42
# Reject 1.x generation (00), reserved generations (10, 11), and reserved bits.
for bad_gen in (0x00, 0x80, 0xC0):
bad = bytes([bad_gen | (1 if xlang else 0)]) + data[1:]
with pytest.raises(ValueError, match="protocol generation"):
fory.deserialize(bad)
for reserved_bit in (0x04, 0x08, 0x10, 0x20):
bad = bytes([expected_bitmap | reserved_bit]) + data[1:]
with pytest.raises(ValueError, match="Unsupported root header bitmap"):
fory.deserialize(bad)
def test_typedef_wire_header_identity_kinds_and_identity_only_named_struct():
# UNBOUND emits zero identity bytes and has identity_kind=00.
unreg = Fory(xlang=True, compatible=True)
td_unbound = encode_typedef(unreg.type_resolver, Point2D)
assert td_unbound.type_id == TypeId.COMPATIBLE_STRUCT
assert td_unbound.identity_kind == IdentityKind.UNBOUND
assert (td_unbound.encoded[8] & 0x80) == 0x80
assert ((td_unbound.encoded[8] >> TYPE_DEF_IDENTITY_SHIFT) & 0b11) == IdentityKind.UNBOUND
# BY_ID has identity_kind=01 and is strictly larger than UNBOUND.
reg_id = Fory(xlang=True, compatible=True)
reg_id.register_type(Point2D, type_id=101)
td_id = encode_typedef(reg_id.type_resolver, Point2D)
assert td_id.type_id == TypeId.COMPATIBLE_STRUCT
assert td_id.identity_kind == IdentityKind.BY_ID
assert len(td_unbound.encoded) < len(td_id.encoded)
# Reject reserved identity_kind=11 (3).
bad_body = bytes([TYPE_DEF_FIELD_BEARING_FLAG | (0b11 << TYPE_DEF_IDENTITY_SHIFT)])
with pytest.raises(ValueError, match="identity kind"):
decode_typedef(Buffer(prepend_header(bad_body, False)), unreg.type_resolver)
# Identity-only NAMED_STRUCT (evolving=False in compatible=True) has bit7=0, kind_code=1, 0 fields.
reg_fixed = Fory(xlang=True, compatible=True)
reg_fixed.register_type(NonEvolvingStruct, name="test.Fixed")
info = reg_fixed.type_resolver.get_type_info(NonEvolvingStruct)
assert info.type_id == TypeId.NAMED_STRUCT
assert info.type_def is not None
assert info.type_def.fields == []
assert info.type_def.encoded[8] == 1 # bit7=0, kind_code=1 (NAMED_STRUCT)
val = NonEvolvingStruct(a=7, b="ok")
assert reg_fixed.deserialize(reg_fixed.serialize(val)) == val
@pytest.mark.parametrize("xlang", [True, False])
@pytest.mark.parametrize("compatible", [True, False])
@pytest.mark.parametrize("ref", [True, False])
@pytest.mark.parametrize("writer_reg", [None, "id", "name"])
@pytest.mark.parametrize("reader_reg", [None, "id", "name"])
def test_4x2_registration_matrix_media_content(xlang, compatible, ref, writer_reg, reader_reg):
writer = Fory(xlang=xlang, compatible=compatible, ref=ref, strict=True)
reader = Fory(xlang=xlang, compatible=compatible, ref=ref, strict=True)
if writer_reg is not None:
_register_media(writer, by_name=(writer_reg == "name"))
if reader_reg is not None:
_register_media(reader, by_name=(reader_reg == "name"))
mc = _make_media_content()
data = writer.serialize(mc)
# Target-typed deserialize must succeed across EVERY registration combination.
assert reader.deserialize(data, MediaContent) == mc
# Warm second call exercises L0/L2 fast paths.
assert reader.deserialize(data, MediaContent) == mc
if writer_reg is None:
# Untyped deserialize of UNBOUND must always raise TypeUnregisteredError.
with pytest.raises(TypeUnregisteredError):
reader.deserialize(data)
elif writer_reg == reader_reg:
# Both registered with matching identity: untyped deserialize works.
assert reader.deserialize(data) == mc
def test_isomorphic_fast_path_promotion_and_wire_size():
mc = _make_media_content()
reg = Fory(xlang=True, compatible=True, strict=True)
_register_media(reg, by_name=False)
unreg = Fory(xlang=True, compatible=True, strict=True)
reg_bytes = reg.serialize(mc)
unreg_bytes = unreg.serialize(mc)
# 3 structs (MediaContent, Media, Image) each save 1 byte of user_type_id in UNBOUND mode.
assert len(unreg_bytes) == len(reg_bytes) - 3
# Write-registered -> Read-unregistered must promote directly to target's canonical serializer.
assert unreg.deserialize(reg_bytes, MediaContent) == mc
target_info = unreg.type_resolver.get_type_info(MediaContent)
reg_hash = reg.type_resolver.get_type_info(MediaContent).local_header_hash
adapted = target_info.get_adapted_type_info(reg_hash)
assert adapted is not None
assert adapted.serializer is target_info.serializer
@pytest.mark.parametrize("compatible", [True, False])
def test_point2d_vector2d_collision_and_evolution(compatible):
fory = Fory(xlang=True, compatible=compatible, strict=True)
ray = Ray(origin=Point2D(1.5, 2.5), direction=Vector2D(-0.5, 0.75))
data = fory.serialize(ray)
restored = fory.deserialize(data, Ray)
assert restored == ray
assert type(restored.origin) is Point2D
assert type(restored.direction) is Vector2D
# Even if writer writes two Point2D values (sharing a single stream meta slot),
# reading into Ray resolves origin->Point2D and direction->Vector2D cleanly.
p_bytes = fory.serialize(Point2D(3.0, 4.0))
assert type(fory.deserialize(p_bytes, Vector2D)) is Vector2D
assert fory.deserialize(p_bytes, Vector2D) == Vector2D(3.0, 4.0)
# Untyped deserialize of UNBOUND still fails even after both Point2D and Vector2D cached it.
with pytest.raises(TypeUnregisteredError):
fory.deserialize(p_bytes)
if compatible:
# Schema evolution: Ray3D (Point3D {x,y,z}) -> Ray (Point2D {x,y}, Vector2D {x,y}).
ray3d = Ray3D(origin=Point3D(1.0, 2.0, 3.0), direction=Point3D(4.0, 5.0, 6.0))
data3d = fory.serialize(ray3d)
restored2d = fory.deserialize(data3d, Ray)
assert type(restored2d.origin) is Point2D
assert type(restored2d.direction) is Vector2D
assert restored2d == Ray(origin=Point2D(1.0, 2.0), direction=Vector2D(4.0, 5.0))
# Repeat to exercise L2 cache on both Point2D and Vector2D.
restored2d_warm = fory.deserialize(data3d, Ray)
assert type(restored2d_warm.origin) is Point2D
assert type(restored2d_warm.direction) is Vector2D
assert restored2d_warm == restored2d
@pytest.mark.parametrize("compatible", [True, False])
def test_containers_and_generic_dataclasses(compatible):
fory = Fory(xlang=True, compatible=compatible, strict=True)
mc = _make_media_content()
# list[MediaContent]
mc_list = [mc, mc]
assert fory.deserialize(fory.serialize(mc_list), List[MediaContent]) == mc_list
# set[Point2D]
pts = {Point2D(1.0, 2.0), Point2D(3.0, 4.0)}
assert fory.deserialize(fory.serialize(pts), Set[Point2D]) == pts
# tuple[Point2D, ...]
pt_tuple = (Point2D(5.0, 6.0), Point2D(7.0, 8.0))
res_tuple = fory.deserialize(fory.serialize(pt_tuple), Tuple[Point2D, ...])
assert isinstance(res_tuple, tuple)
assert res_tuple == pt_tuple
# dict[str, Point2D]
pt_map = {"a": Point2D(1.0, 2.0), "b": Point2D(3.0, 4.0)}
assert fory.deserialize(fory.serialize(pt_map), Dict[str, Point2D]) == pt_map
# Optional[Point2D]
assert fory.deserialize(fory.serialize(None), Optional[Point2D]) is None
assert fory.deserialize(fory.serialize(Point2D(9.0, 10.0)), Optional[Point2D]) == Point2D(9.0, 10.0)
# Distinct generic dataclass instantiations (P0-3): PageResult[Order] vs PageResult[UserRecord].
if compatible:
order_page = PageResult(total=2, items=[Order(1, 12.5), Order(2, 99.0)])
user_page = PageResult(total=1, items=[UserRecord(7, "alice")])
order_bytes = fory.serialize(order_page)
user_bytes = fory.serialize(user_page)
r_orders = fory.deserialize(order_bytes, PageResult[Order])
r_users = fory.deserialize(user_bytes, PageResult[UserRecord])
assert r_orders == order_page
assert all(type(x) is Order for x in r_orders.items)
assert r_users == user_page
assert all(type(x) is UserRecord for x in r_users.items)
@pytest.mark.parametrize("compatible", [True, False])
def test_cyclic_and_shared_unregistered_refs(compatible):
fory = Fory(xlang=True, compatible=compatible, ref=True, strict=True)
node = CyclicNode(name="root")
node.next = node
data = fory.serialize(node)
restored = fory.deserialize(data, CyclicNode)
assert restored.name == "root"
assert restored.next is restored
# Shared unregistered struct inside list.
img = Image(uri="u", title="t", width=1, height=2, size=Size.SMALL)
mc = MediaContent(media=_make_media_content().media, images=[img, img])
restored_mc = fory.deserialize(fory.serialize(mc), MediaContent)
assert restored_mc == mc
assert restored_mc.images[0] is restored_mc.images[1]
def test_union_with_unregistered_struct_cases():
fory = Fory(xlang=True, compatible=True, strict=True)
fory.register_union(SampleUnion, type_id=200, serializer=SampleUnionSerializer)
u0 = SampleUnion(0, Point2D(1.0, 2.0))
u1 = SampleUnion(1, Order(42, 3.5))
assert fory.deserialize(fory.serialize(u0)).value() == Point2D(1.0, 2.0)
assert fory.deserialize(fory.serialize(u1)).value() == Order(42, 3.5)
def test_compatible_skip_removed_unregistered_fields_and_quota():
writer = Fory(xlang=True, compatible=True, ref=True, strict=True)
reader = Fory(xlang=True, compatible=True, ref=True, strict=True, max_schema_versions_per_type=1)
item = RemovedPayload(tag="gone", count=9)
remote = RemoteWithRemoved(
kept=77,
removed_single=item,
removed_list=[item, RemovedPayload(tag="other", count=10)],
removed_map={"k": item},
)
data = writer.serialize(remote)
assert reader.deserialize(data, LocalWithoutRemoved) == LocalWithoutRemoved(kept=77)
# Repeat read exercises L2 skip cache.
assert reader.deserialize(data, LocalWithoutRemoved) == LocalWithoutRemoved(kept=77)
# Quota saturation for UNBOUND evolution still decodes without unbounded cache growth.
point_ti = reader.type_resolver.resolve_target_type_info(Point2D)
unbound_hashes = []
for i in range(4):
remote_cls = make_dataclass(f"EvolvingPoint{i}", [("x", pyfory.Float64), ("y", pyfory.Float64), (f"extra_{i}", pyfory.Int32)])
inst = remote_cls(1.0, 2.0, i)
payload = writer.serialize(inst)
assert reader.deserialize(payload, Point2D) == Point2D(1.0, 2.0)
unbound_hashes.append(writer.type_resolver.get_type_info(remote_cls).local_header_hash)
assert point_ti.get_adapted_type_info(unbound_hashes[0]) is not None
for h in unbound_hashes[1:]:
assert point_ti.get_adapted_type_info(h) is None
# Multiple distinct registered BY_NAME schemas adapted to the same unregistered
# target must also stay capped by max_schema_versions_per_type on target L2.
named_reader = Fory(xlang=True, compatible=True, strict=True, max_schema_versions_per_type=1)
named_point_ti = named_reader.type_resolver.resolve_target_type_info(Point2D)
named_hashes = []
for i in range(4):
named_writer = Fory(xlang=True, compatible=True, strict=True)
remote_cls = make_dataclass(f"NamedRemotePoint{i}", [("x", pyfory.Float64), ("y", pyfory.Float64), (f"extra_{i}", pyfory.Int32)])
named_writer.register_type(remote_cls, name=f"ns.RemotePoint{i}")
payload = named_writer.serialize(remote_cls(3.0, 4.0, i))
assert named_reader.deserialize(payload, Point2D) == Point2D(3.0, 4.0)
named_hashes.append(named_writer.type_resolver.get_type_info(remote_cls).local_header_hash)
assert named_point_ti.get_adapted_type_info(named_hashes[0]) is not None
for h in named_hashes[1:]:
assert named_point_ti.get_adapted_type_info(h) is None
def test_security_strict_rejects_reduce_and_plain_classes_and_covariant_subclasses():
fory = Fory(xlang=False, compatible=True, strict=True)
with pytest.raises(TypeUnregisteredError):
fory.serialize(ReduceDataclass(1))
with pytest.raises(TypeUnregisteredError):
fory.serialize(PlainUnregistered(1))
with pytest.raises(TypeUnregisteredError):
fory.type_resolver.resolve_target_type_info(ReduceDataclass)
with pytest.raises(TypeUnregisteredError):
fory.type_resolver.resolve_target_type_info(PlainUnregistered)
# Covariant registered subclass works in declared base field; unrelated registered type fails.
poly = Fory(xlang=True, compatible=True, strict=True)
poly.register_type(BaseAnimal, type_id=300)
poly.register_type(SubDog, type_id=301)
poly.register_type(OtherAnimal, type_id=302)
poly.register_type(AnimalHolder, type_id=303)
holder = AnimalHolder(pet=SubDog(name="Rex", bark_volume=9))
restored = poly.deserialize(poly.serialize(holder))
assert type(restored.pet) is SubDog
assert restored == holder
other_bytes = poly.serialize(OtherAnimal(name="NotABase"))
with pytest.raises(TypeError):
poly.deserialize(other_bytes, BaseAnimal)
@pytest.mark.parametrize("xlang", [True, False])
def test_registration_freeze_single_and_thread_safe(xlang):
# Freeze on first serialize
f1 = Fory(xlang=xlang, compatible=True)
f1.register_type(Point2D, type_id=10)
f1.serialize(Point2D(1.0, 2.0))
with pytest.raises(RuntimeError):
f1.register_type(Vector2D, type_id=11)
with pytest.raises(RuntimeError):
f1.register_serializer(Point2D, f1.type_resolver.get_serializer(Point2D))
with pytest.raises(RuntimeError):
f1.register_union(SampleUnion, type_id=12, serializer=SampleUnionSerializer)
assert not f1.type_resolver.is_registered_by_id(Vector2D)
# Freeze even when first deserialize fails
f2 = Fory(xlang=xlang, compatible=True)
with pytest.raises(ValueError):
f2.deserialize(b"\x00")
with pytest.raises(RuntimeError):
f2.register_type(Point2D, type_id=10)
# ThreadSafeFory freeze
ts = ThreadSafeFory(xlang=xlang, compatible=True)
ts.register_type(Point2D, type_id=10)
data = ts.serialize(Point2D(1.0, 2.0))
assert ts.deserialize(data) == Point2D(1.0, 2.0)
with pytest.raises(RuntimeError):
ts.register_type(Vector2D, type_id=11)