@@ -103,40 +103,6 @@ def test_instance_to_json_hook_receives_instance():
103103 assert json .loads (to_json (Widget ("gear" , 5 ))) == {"label" : "gear" , "size" : 5 }
104104
105105
106- @dataclass
107- class HookedDataclass :
108- """Dataclass that overrides serialization via to_json/from_json.
109-
110- Its ``value`` field is not JSON-native on the wire (it is encoded as a
111- string), so plain ``dataclasses.asdict`` would not round-trip. The hooks
112- take precedence over the default dataclass encoding.
113- """
114-
115- value : int
116-
117- def to_json (self ) -> dict :
118- return {"value" : str (self .value )}
119-
120- @classmethod
121- def from_json (cls , data : dict ) -> "HookedDataclass" :
122- return cls (int (data ["value" ]))
123-
124- def __eq__ (self , other : object ) -> bool :
125- return isinstance (other , HookedDataclass ) and other .value == self .value
126-
127-
128- def test_dataclass_to_json_hook_takes_precedence_over_asdict ():
129- # A dataclass exposing to_json should serialize via the hook, not asdict.
130- encoded = json_codec .to_json (HookedDataclass (7 ))
131- assert json .loads (encoded ) == {"value" : "7" }
132-
133-
134- def test_dataclass_hook_round_trips_with_expected_type ():
135- encoded = json_codec .to_json (HookedDataclass (7 ))
136- result = json_codec .from_json (encoded , HookedDataclass )
137- assert result == HookedDataclass (7 )
138-
139-
140106# ----- to_json -----
141107
142108
0 commit comments