test_subclass.py
Overview
The [test_subclass.py](/projects/287/67683) file is a test suite designed to verify the behavior of the `orjson` JSON serialization library when handling subclassed built-in Python types. It focuses on ensuring that subclasses of fundamental types like `str`, `int`, `dict`, `list`, `float`, and `tuple` interact correctly with [orjson.dumps()](/projects/287/67747) under various conditions.
This file includes two primary test classes:
TestSubclass: Tests the default serialization behavior of subclassed types withorjson.TestSubclassPassthrough: Tests serialization behavior whenorjson's OPT_PASSTHROUGH_SUBCLASS option is enabled.
The tests cover correct serialization, error handling for invalid data or circular references, and differences in behavior compared to Python's standard `json` module.
Classes and Their Details
1. Subclass Definitions
These are simple subclasses of Python built-in types, used to test serialization behavior.
Class Name | Base Type | Description |
|---|---|---|
`SubStr` | `str` | Subclass of string |
`SubInt` | `int` | Subclass of integer |
`SubDict` | `dict` | Subclass of dictionary |
`SubList` | `list` | Subclass of list |
`SubFloat` | `float` | Subclass of float |
`SubTuple` | `tuple` | Subclass of tuple |
These classes have no additional methods or properties and exist solely to test subclass serialization behavior.
2. TestSubclass
This class contains multiple test methods that check how [orjson.dumps()](/projects/287/67747) handles subclassed objects without any special options.
Methods
test_subclass_str(self)Purpose: Verify that
SubStrinstances serialize as normal strings.Assertion:
orjson.dumps(SubStr("zxc")) == b'"zxc"'Usage: Ensures subclassed strings serialize correctly.
test_subclass_str_invalid(self)Purpose: Verify that invalid UTF-8 surrogate code points in
SubStrraiseorjson.JSONEncodeError.Assertion: Raises
orjson.JSONEncodeErrorwhen serializingSubStr("\ud800").Usage: Checks error handling for invalid Unicode sequences.
test_subclass_int(self)Purpose: Verify that
SubIntinstances serialize as normal integers.Assertion:
orjson.dumps(SubInt(1)) == b"1"Usage: Validates integer serialization.
test_subclass_int_64(self)Purpose: Verify serialization of 64-bit integer boundary values.
Details: Tests serialization of
9223372036854775807and its negative counterpart.Assertion: Serialized output matches string-encoded integer.
Usage: Validates support for 64-bit integer range.
test_subclass_int_53(self)Purpose: Test serialization failure for integers exceeding 53-bit limit under strict integer option.
Details: Values
9007199254740992and its negative raiseJSONEncodeErrorwhen OPT_STRICT_INTEGER is enabled.Usage: Checks
orjson's strict integer handling for large integers.
test_subclass_dict(self)Purpose: Verify that
SubDictserializes like a normal dictionary.Assertion:
orjson.dumps(SubDict({"a": "b"})) == b'{"a":"b"}'
test_subclass_list(self)Purpose: Verify that
SubListserializes properly.Assertions:
orjson.dumps(SubList(["a", "b"])) == b'["a","b"]'Serialization and deserialization of a large list (
[True] * 512) round-trips correctly.
Usage: Validates list subclass serialization and deserialization integrity.
test_subclass_float(self)Purpose: Verify that
SubFloatinstances raiseJSONEncodeErrorinorjsonbut serialize correctly with Python'sjsonmodule.Usage: Highlights
orjsonlimitation with float subclasses.
test_subclass_tuple(self)Purpose: Verify that
SubTupleraises error inorjsonbut serializes as list injson.Usage: Shows
orjsondoes not support tuple subclasses.
test_namedtuple(self)Purpose: Verify that namedtuple instances raise
JSONEncodeError.Usage: Confirms that
orjsondoes not support namedtuples directly.
test_subclass_circular_dict(self)Purpose: Verify detection of circular references in
SubDict.Details: Creates a dictionary referencing itself and asserts encoding error.
Usage: Tests circular reference detection in subclassed dicts.
test_subclass_circular_list(self)Purpose: Verify detection of circular references in
SubList.Usage: Similar to above, but for list subclass.
test_subclass_circular_nested(self)Purpose: Verify detection of complex nested circular references involving
SubDictandSubList.Usage: Ensures
orjsondetects circular references even in nested, mixed subclassed containers.
3. TestSubclassPassthrough
This class tests serialization behavior when [orjson.OPT_PASSTHROUGH_SUBCLASS](/projects/287/67684) option is enabled, which instructs `orjson` to not implicitly treat subclasses as their base types.
Methods
test_subclass_str(self)Purpose: Verify that
SubStrfails serialization under passthrough mode.Assertion: Raises
JSONEncodeErrorwith OPT_PASSTHROUGH_SUBCLASS.
test_subclass_int(self)Purpose: Verify that
SubIntfails serialization under passthrough mode.
test_subclass_dict(self)Purpose: Verify that
SubDictfails serialization under passthrough mode.
test_subclass_list(self)Purpose: Verify that
SubListfails serialization under passthrough mode.
**Summary:** When passthrough mode is enabled, `orjson` does not attempt to convert subclass instances to their base types and instead raises errors, enforcing stricter type serialization.
Important Implementation Details and Algorithms
The file uses simple subclassing of built-in types without overriding any behaviors or adding new properties.
The tests rely on pytest for assertion and exception handling.
The serialization is performed using orjson.dumps(), which is a fast JSON serializer implemented in Rust.
The tests ensure correct serialization, error raising on invalid data (e.g., invalid Unicode surrogates), strict integer handling, and circular reference detection.
Circular references in subclassed containers are tested to verify
orjson's ability to detect and prevent infinite recursion.The difference in behavior between
orjsonand the built-injsonmodule regarding subclass serialization is highlighted, especially for floats and tuples.
Interaction with Other Parts of the System
orjsonLibrary: The primary dependency tested here; this file validates howorjsonhandles subclassed data types.pytest: Used as the testing framework for organizing and asserting tests.
jsonModule: Used as a reference to compare serialization behavior, especially forSubFloatandSubTuple.collections.namedtuple: Used to test serialization of namedtuple subclasses.
This test file is likely part of a broader test suite for the `orjson` package or an application using `orjson` where subclass serialization behavior is critical.
Usage Examples
import orjson
from test_subclass import SubStr, SubInt
# Serialize a subclassed string
data = SubStr("example")
json_bytes = orjson.dumps(data)
print(json_bytes) # Output: b'"example"'
# Serialize a subclassed integer
num = SubInt(42)
json_bytes = orjson.dumps(num)
print(json_bytes) # Output: b'42'
# Attempt serialization with invalid surrogate (raises JSONEncodeError)
try:
invalid_str = SubStr("\ud800")
orjson.dumps(invalid_str)
except orjson.JSONEncodeError:
print("Invalid Unicode surrogate detected.")
Mermaid Class Diagram
classDiagram
class SubStr {
}
class SubInt {
}
class SubDict {
}
class SubList {
}
class SubFloat {
}
class SubTuple {
}
class TestSubclass {
+test_subclass_str()
+test_subclass_str_invalid()
+test_subclass_int()
+test_subclass_int_64()
+test_subclass_int_53()
+test_subclass_dict()
+test_subclass_list()
+test_subclass_float()
+test_subclass_tuple()
+test_namedtuple()
+test_subclass_circular_dict()
+test_subclass_circular_list()
+test_subclass_circular_nested()
}
class TestSubclassPassthrough {
+test_subclass_str()
+test_subclass_int()
+test_subclass_dict()
+test_subclass_list()
}
SubStr --|> str
SubInt --|> int
SubDict --|> dict
SubList --|> list
SubFloat --|> float
SubTuple --|> tuple
TestSubclass ..> SubStr : tests
TestSubclass ..> SubInt : tests
TestSubclass ..> SubDict : tests
TestSubclass ..> SubList : tests
TestSubclass ..> SubFloat : tests
TestSubclass ..> SubTuple : tests
TestSubclass ..> collections.namedtuple : tests
TestSubclassPassthrough ..> SubStr : tests
TestSubclassPassthrough ..> SubInt : tests
TestSubclassPassthrough ..> SubDict : tests
TestSubclassPassthrough ..> SubList : tests
Summary
[test_subclass.py](/projects/287/67683) is a specialized test suite verifying the serialization capabilities and limitations of `orjson` with respect to subclassed Python built-in types. It ensures that `orjson` can serialize these subclasses correctly or raise appropriate errors when encountering unsupported cases, especially under strict serialization options or passthrough mode. The tests also demonstrate `orjson`'s behavior differences compared to Python's standard `json` library and validate handling of edge cases like circular references and invalid Unicode data.