Debian Codegraph @

src/de.rs

raw symbols SCIP
1 use pyo3::exceptions::PyKeyError;
2 use pyo3::{intern, types::*, Bound};
3 use serde::de::{self, IntoDeserializer};
4 use serde::Deserialize;
5
6 use crate::error::{ErrorImpl, PythonizeError, Result};
7
8 #[cfg(feature = "arbitrary_precision")]
9 const TOKEN: &str = "$serde_json::private::Number";
10
11 /// Attempt to convert a Python object to an instance of `T`.
12 ///
13 /// Generally this only supports Python types that match `serde`'s object model well:
14 /// - integers (including arbitrary precision integers if the `arbitrary_precision` feature is enabled)
15 /// - floats
16 /// - strings
17 /// - bytes
18 /// - `collections.abc.Sequence` instances (as serde sequences)
19 /// - `collections.abc.Mapping` instances (as serde maps)
20 /// - dataclasses (as serde maps)
21 pub fn depythonize<'a, 'py, T>(obj: &'a Bound<'py, PyAny>) -> Result<T>
22 where
23 T: Deserialize<'a>,
24 {
25 T::deserialize(&mut Depythonizer::from_object(obj))
26 }
27
28 /// A structure that deserializes Python objects into Rust values
29 pub struct Depythonizer<'a, 'py> {
30 input: &'a Bound<'py, PyAny>,
31 }
32
33 impl<'a, 'py> Depythonizer<'a, 'py> {
34 /// Create a deserializer from a Python object
35 pub fn from_object(input: &'a Bound<'py, PyAny>) -> Self {
36 Depythonizer { input }
37 }
38
39 fn sequence_access(&self, expected_len: Option<usize>) -> Result<PySequenceAccess<'a, 'py>> {
40 let seq = self.input.cast::<PySequence>()?;
41 let len = self.input.len()?;
42
43 match expected_len {
44 Some(expected) if expected != len => {
45 Err(PythonizeError::incorrect_sequence_length(expected, len))
46 }
47 _ => Ok(PySequenceAccess::new(seq, len)),
48 }
49 }
50
51 fn set_access(&self) -> Result<PySetAsSequence<'py>> {
52 match self.input.cast::<PySet>() {
53 Ok(set) => Ok(PySetAsSequence::from_set(set)),
54 Err(e) => {
55 if let Ok(f) = self.input.cast::<PyFrozenSet>() {
56 Ok(PySetAsSequence::from_frozenset(f))
57 } else {
58 Err(e.into())
59 }
60 }
61 }
62 }
63
64 fn dict_access(&self) -> Result<PyMappingAccess<'py>> {
65 PyMappingAccess::new(self.input.cast()?)
66 }
67
68 fn dataclass_access(&self) -> Result<Option<PyDataclassAccess<'py>>> {
69 if let Some(dc) = DataclassCandidate::try_new(self.input) {
70 Some(PyDataclassAccess::new(dc)).transpose()
71 } else {
72 Ok(None)
73 }
74 }
75
76 fn deserialize_any_int<'de, V>(&self, int: &Bound<'_, PyInt>, visitor: V) -> Result<V::Value>
77 where
78 V: de::Visitor<'de>,
79 {
80 if let Ok(x) = int.extract::<u128>() {
81 if let Ok(x) = u8::try_from(x) {
82 visitor.visit_u8(x)
83 } else if let Ok(x) = u16::try_from(x) {
84 visitor.visit_u16(x)
85 } else if let Ok(x) = u32::try_from(x) {
86 visitor.visit_u32(x)
87 } else if let Ok(x) = u64::try_from(x) {
88 visitor.visit_u64(x)
89 } else {
90 visitor.visit_u128(x)
91 }
92 } else if let Ok(x) = int.extract::<i128>() {
93 if let Ok(x) = i8::try_from(x) {
94 visitor.visit_i8(x)
95 } else if let Ok(x) = i16::try_from(x) {
96 visitor.visit_i16(x)
97 } else if let Ok(x) = i32::try_from(x) {
98 visitor.visit_i32(x)
99 } else if let Ok(x) = i64::try_from(x) {
100 visitor.visit_i64(x)
101 } else {
102 visitor.visit_i128(x)
103 }
104 } else {
105 #[cfg(feature = "arbitrary_precision")]
106 {
107 visitor.visit_map(NumberDeserializer {
108 number: Some(int.to_string()),
109 })
110 }
111 #[cfg(not(feature = "arbitrary_precision"))]
112 {
113 // Re-attempt to return the original error.
114 let _: i128 = int.extract()?;
115 unreachable!()
116 }
117 }
118 }
119 }
120
121 macro_rules! deserialize_type {
122 ($method:ident => $visit:ident) => {
123 fn $method<V>(self, visitor: V) -> Result<V::Value>
124 where
125 V: de::Visitor<'de>,
126 {
127 visitor.$visit(self.input.extract()?)
128 }
129 };
130 }
131
132 impl<'de> de::Deserializer<'de> for &'_ mut Depythonizer<'_, '_> {
133 type Error = PythonizeError;
134
135 fn deserialize_any<V>(self, visitor: V) -> Result<V::Value>
136 where
137 V: de::Visitor<'de>,
138 {
139 let obj = self.input;
140
141 // First check for cases which are cheap to check due to pointer
142 // comparison or bitflag checks
143 if obj.is_none() {
144 self.deserialize_unit(visitor)
145 } else if obj.is_instance_of::<PyBool>() {
146 self.deserialize_bool(visitor)
147 } else if let Ok(x) = obj.cast::<PyInt>() {
148 self.deserialize_any_int(x, visitor)
149 } else if obj.is_instance_of::<PyList>() || obj.is_instance_of::<PyTuple>() {
150 self.deserialize_tuple(obj.len()?, visitor)
151 } else if obj.is_instance_of::<PyDict>() {
152 self.deserialize_map(visitor)
153 } else if obj.is_instance_of::<PyString>() {
154 self.deserialize_str(visitor)
155 }
156 // Continue with cases which are slower to check because they go
157 // through `isinstance` machinery
158 else if obj.is_instance_of::<PyBytes>() || obj.is_instance_of::<PyByteArray>() {
159 self.deserialize_bytes(visitor)
160 } else if obj.is_instance_of::<PyFloat>() {
161 self.deserialize_f64(visitor)
162 } else if obj.is_instance_of::<PyFrozenSet>() || obj.is_instance_of::<PySet>() {
163 self.deserialize_seq(visitor)
164 } else if obj.cast::<PySequence>().is_ok() {
165 self.deserialize_tuple(obj.len()?, visitor)
166 } else if obj.cast::<PyMapping>().is_ok() {
167 self.deserialize_map(visitor)
168 } else if let Some(dc) = DataclassCandidate::try_new(obj) {
169 visitor.visit_map(PyDataclassAccess::new(dc)?)
170 } else {
171 Err(obj.get_type().qualname().map_or_else(
172 |_| PythonizeError::unsupported_type("unknown"),
173 PythonizeError::unsupported_type,
174 ))
175 }
176 }
177
178 fn deserialize_bool<V>(self, visitor: V) -> Result<V::Value>
179 where
180 V: de::Visitor<'de>,
181 {
182 visitor.visit_bool(self.input.is_truthy()?)
183 }
184
185 fn deserialize_char<V>(self, visitor: V) -> Result<V::Value>
186 where
187 V: de::Visitor<'de>,
188 {
189 let s = self.input.cast::<PyString>()?.to_cow()?;
190 if s.len() != 1 {
191 return Err(PythonizeError::invalid_length_char());
192 }
193 visitor.visit_char(s.chars().next().unwrap())
194 }
195
196 deserialize_type!(deserialize_i8 => visit_i8);
197 deserialize_type!(deserialize_i16 => visit_i16);
198 deserialize_type!(deserialize_i32 => visit_i32);
199 deserialize_type!(deserialize_i64 => visit_i64);
200 deserialize_type!(deserialize_i128 => visit_i128);
201 deserialize_type!(deserialize_u8 => visit_u8);
202 deserialize_type!(deserialize_u16 => visit_u16);
203 deserialize_type!(deserialize_u32 => visit_u32);
204 deserialize_type!(deserialize_u64 => visit_u64);
205 deserialize_type!(deserialize_u128 => visit_u128);
206 deserialize_type!(deserialize_f32 => visit_f32);
207 deserialize_type!(deserialize_f64 => visit_f64);
208
209 fn deserialize_str<V>(self, visitor: V) -> Result<V::Value>
210 where
211 V: de::Visitor<'de>,
212 {
213 let s = self.input.cast::<PyString>()?;
214 visitor.visit_str(&s.to_cow()?)
215 }
216
217 fn deserialize_string<V>(self, visitor: V) -> Result<V::Value>
218 where
219 V: de::Visitor<'de>,
220 {
221 self.deserialize_str(visitor)
222 }
223
224 fn deserialize_bytes<V>(self, visitor: V) -> Result<V::Value>
225 where
226 V: de::Visitor<'de>,
227 {
228 let b = self.input.cast::<PyBytes>()?;
229 visitor.visit_bytes(b.as_bytes())
230 }
231
232 fn deserialize_byte_buf<V>(self, visitor: V) -> Result<V::Value>
233 where
234 V: de::Visitor<'de>,
235 {
236 self.deserialize_bytes(visitor)
237 }
238
239 fn deserialize_option<V>(self, visitor: V) -> Result<V::Value>
240 where
241 V: de::Visitor<'de>,
242 {
243 if self.input.is_none() {
244 visitor.visit_none()
245 } else {
246 visitor.visit_some(self)
247 }
248 }
249
250 fn deserialize_unit<V>(self, visitor: V) -> Result<V::Value>
251 where
252 V: de::Visitor<'de>,
253 {
254 if self.input.is_none() {
255 visitor.visit_unit()
256 } else {
257 Err(PythonizeError::msg("expected None"))
258 }
259 }
260
261 fn deserialize_unit_struct<V>(self, _name: &'static str, visitor: V) -> Result<V::Value>
262 where
263 V: de::Visitor<'de>,
264 {
265 self.deserialize_unit(visitor)
266 }
267
268 fn deserialize_newtype_struct<V>(self, _name: &'static str, visitor: V) -> Result<V::Value>
269 where
270 V: de::Visitor<'de>,
271 {
272 visitor.visit_newtype_struct(self)
273 }
274
275 fn deserialize_seq<V>(self, visitor: V) -> Result<V::Value>
276 where
277 V: de::Visitor<'de>,
278 {
279 match self.sequence_access(None) {
280 Ok(seq) => visitor.visit_seq(seq),
281 Err(e) => {
282 // we allow sets to be deserialized as sequences, so try that
283 if matches!(*e.inner, ErrorImpl::UnexpectedType(_)) {
284 if let Ok(set) = self.set_access() {
285 return visitor.visit_seq(set);
286 }
287 }
288 Err(e)
289 }
290 }
291 }
292
293 fn deserialize_tuple<V>(self, len: usize, visitor: V) -> Result<V::Value>
294 where
295 V: de::Visitor<'de>,
296 {
297 visitor.visit_seq(self.sequence_access(Some(len))?)
298 }
299
300 fn deserialize_tuple_struct<V>(
301 self,
302 _name: &'static str,
303 len: usize,
304 visitor: V,
305 ) -> Result<V::Value>
306 where
307 V: de::Visitor<'de>,
308 {
309 visitor.visit_seq(self.sequence_access(Some(len))?)
310 }
311
312 fn deserialize_map<V>(self, visitor: V) -> Result<V::Value>
313 where
314 V: de::Visitor<'de>,
315 {
316 if let Some(dc_access) = self.dataclass_access()? {
317 visitor.visit_map(dc_access)
318 } else {
319 visitor.visit_map(self.dict_access()?)
320 }
321 }
322
323 fn deserialize_struct<V>(
324 self,
325 _name: &'static str,
326 _fields: &'static [&'static str],
327 visitor: V,
328 ) -> Result<V::Value>
329 where
330 V: de::Visitor<'de>,
331 {
332 self.deserialize_map(visitor)
333 }
334
335 fn deserialize_enum<V>(
336 self,
337 _name: &'static str,
338 _variants: &'static [&'static str],
339 visitor: V,
340 ) -> Result<V::Value>
341 where
342 V: de::Visitor<'de>,
343 {
344 let item = &self.input;
345 if let Ok(s) = item.cast::<PyString>() {
346 visitor.visit_enum(s.to_cow()?.into_deserializer())
347 } else if let Ok(m) = item.cast::<PyMapping>() {
348 // Get the enum variant from the mapping key
349 if m.len()? != 1 {
350 return Err(PythonizeError::invalid_length_enum());
351 }
352 let variant: Bound<PyString> = m
353 .keys()?
354 .get_item(0)?
355 .cast_into::<PyString>()
356 .map_err(|_| PythonizeError::dict_key_not_string())?;
357 let value = m.get_item(&variant)?;
358 visitor.visit_enum(PyEnumAccess::new(&value, variant))
359 } else {
360 Err(PythonizeError::invalid_enum_type())
361 }
362 }
363
364 fn deserialize_identifier<V>(self, visitor: V) -> Result<V::Value>
365 where
366 V: de::Visitor<'de>,
367 {
368 let s = self
369 .input
370 .cast::<PyString>()
371 .map_err(|_| PythonizeError::dict_key_not_string())?;
372 visitor.visit_str(&s.to_cow()?)
373 }
374
375 fn deserialize_ignored_any<V>(self, visitor: V) -> Result<V::Value>
376 where
377 V: de::Visitor<'de>,
378 {
379 visitor.visit_unit()
380 }
381 }
382
383 struct PySequenceAccess<'a, 'py> {
384 seq: &'a Bound<'py, PySequence>,
385 index: usize,
386 len: usize,
387 }
388
389 impl<'a, 'py> PySequenceAccess<'a, 'py> {
390 fn new(seq: &'a Bound<'py, PySequence>, len: usize) -> Self {
391 Self { seq, index: 0, len }
392 }
393 }
394
395 impl<'de> de::SeqAccess<'de> for PySequenceAccess<'_, '_> {
396 type Error = PythonizeError;
397
398 fn next_element_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>>
399 where
400 T: de::DeserializeSeed<'de>,
401 {
402 if self.index < self.len {
403 let item = self.seq.get_item(self.index)?;
404 self.index += 1;
405 seed.deserialize(&mut Depythonizer::from_object(&item))
406 .map(Some)
407 } else {
408 Ok(None)
409 }
410 }
411 }
412
413 struct PySetAsSequence<'py> {
414 iter: Bound<'py, PyIterator>,
415 }
416
417 impl<'py> PySetAsSequence<'py> {
418 fn from_set(set: &Bound<'py, PySet>) -> Self {
419 Self {
420 iter: PyIterator::from_object(set).expect("set is always iterable"),
421 }
422 }
423
424 fn from_frozenset(set: &Bound<'py, PyFrozenSet>) -> Self {
425 Self {
426 iter: PyIterator::from_object(set).expect("frozenset is always iterable"),
427 }
428 }
429 }
430
431 impl<'de> de::SeqAccess<'de> for PySetAsSequence<'_> {
432 type Error = PythonizeError;
433
434 fn next_element_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>>
435 where
436 T: de::DeserializeSeed<'de>,
437 {
438 match self.iter.next() {
439 Some(item) => seed
440 .deserialize(&mut Depythonizer::from_object(&item?))
441 .map(Some),
442 None => Ok(None),
443 }
444 }
445 }
446
447 struct PyMappingAccess<'py> {
448 keys: Bound<'py, PyList>,
449 values: Bound<'py, PyList>,
450 key_idx: usize,
451 val_idx: usize,
452 len: usize,
453 }
454
455 impl<'py> PyMappingAccess<'py> {
456 fn new(map: &Bound<'py, PyMapping>) -> Result<Self> {
457 let keys = map.keys()?;
458 let values = map.values()?;
459 let len = map.len()?;
460 Ok(Self {
461 keys,
462 values,
463 key_idx: 0,
464 val_idx: 0,
465 len,
466 })
467 }
468 }
469
470 impl<'de> de::MapAccess<'de> for PyMappingAccess<'_> {
471 type Error = PythonizeError;
472
473 fn next_key_seed<K>(&mut self, seed: K) -> Result<Option<K::Value>>
474 where
475 K: de::DeserializeSeed<'de>,
476 {
477 if self.key_idx < self.len {
478 let item = self.keys.get_item(self.key_idx)?;
479 self.key_idx += 1;
480 seed.deserialize(&mut Depythonizer::from_object(&item))
481 .map(Some)
482 } else {
483 Ok(None)
484 }
485 }
486
487 fn next_value_seed<V>(&mut self, seed: V) -> Result<V::Value>
488 where
489 V: de::DeserializeSeed<'de>,
490 {
491 let item = self.values.get_item(self.val_idx)?;
492 self.val_idx += 1;
493 seed.deserialize(&mut Depythonizer::from_object(&item))
494 }
495 }
496
497 /// Intermediate structure used to denote that `obj` is a dataclass with `fields`.
498 struct DataclassCandidate<'a, 'py> {
499 obj: &'a Bound<'py, PyAny>,
500 fields: Bound<'py, PyAny>,
501 }
502
503 impl<'a, 'py> DataclassCandidate<'a, 'py> {
504 fn try_new(obj: &'a Bound<'py, PyAny>) -> Option<Self> {
505 let fields = obj
506 .getattr_opt(intern!(obj.py(), "__dataclass_fields__"))
507 .ok()
508 .flatten()?;
509 Some(Self { obj, fields })
510 }
511 }
512
513 struct PyDataclassAccess<'py> {
514 fields: Bound<'py, PyList>,
515 dict: Bound<'py, PyDict>,
516 field_idx: usize,
517 val_idx: usize,
518 len: usize,
519 }
520
521 impl<'py> PyDataclassAccess<'py> {
522 fn new(dc: DataclassCandidate<'_, 'py>) -> Result<Self> {
523 let fields = dc.fields.cast::<PyDict>()?.keys();
524 let dict = dc
525 .obj
526 .getattr(intern!(dc.obj.py(), "__dict__"))?
527 .cast_into()?;
528 let len = fields.len();
529 Ok(Self {
530 fields,
531 dict,
532 field_idx: 0,
533 val_idx: 0,
534 len,
535 })
536 }
537 }
538
539 impl<'de> de::MapAccess<'de> for PyDataclassAccess<'_> {
540 type Error = PythonizeError;
541
542 fn next_key_seed<K>(&mut self, seed: K) -> Result<Option<K::Value>>
543 where
544 K: de::DeserializeSeed<'de>,
545 {
546 if self.field_idx < self.len {
547 let item = self.fields.get_item(self.field_idx)?;
548 self.field_idx += 1;
549 seed.deserialize(&mut Depythonizer::from_object(&item))
550 .map(Some)
551 } else {
552 Ok(None)
553 }
554 }
555
556 fn next_value_seed<V>(&mut self, seed: V) -> Result<V::Value>
557 where
558 V: de::DeserializeSeed<'de>,
559 {
560 let key = self.fields.get_item(self.val_idx)?;
561 let value = self
562 .dict
563 .get_item(&key)?
564 .ok_or_else(|| PyKeyError::new_err(key.unbind()))?;
565 self.val_idx += 1;
566 seed.deserialize(&mut Depythonizer::from_object(&value))
567 }
568 }
569
570 struct PyEnumAccess<'a, 'py> {
571 de: Depythonizer<'a, 'py>,
572 variant: Bound<'py, PyString>,
573 }
574
575 impl<'a, 'py> PyEnumAccess<'a, 'py> {
576 fn new(obj: &'a Bound<'py, PyAny>, variant: Bound<'py, PyString>) -> Self {
577 Self {
578 de: Depythonizer::from_object(obj),
579 variant,
580 }
581 }
582 }
583
584 impl<'de> de::EnumAccess<'de> for PyEnumAccess<'_, '_> {
585 type Error = PythonizeError;
586 type Variant = Self;
587
588 fn variant_seed<V>(self, seed: V) -> Result<(V::Value, Self::Variant)>
589 where
590 V: de::DeserializeSeed<'de>,
591 {
592 let cow = self.variant.to_cow()?;
593 let de: de::value::StrDeserializer<'_, PythonizeError> = cow.as_ref().into_deserializer();
594 let val = seed.deserialize(de)?;
595 Ok((val, self))
596 }
597 }
598
599 impl<'de> de::VariantAccess<'de> for PyEnumAccess<'_, '_> {
600 type Error = PythonizeError;
601
602 fn unit_variant(self) -> Result<()> {
603 Ok(())
604 }
605
606 fn newtype_variant_seed<T>(self, seed: T) -> Result<T::Value>
607 where
608 T: de::DeserializeSeed<'de>,
609 {
610 seed.deserialize(&mut { self.de })
611 }
612
613 fn tuple_variant<V>(self, len: usize, visitor: V) -> Result<V::Value>
614 where
615 V: de::Visitor<'de>,
616 {
617 visitor.visit_seq(self.de.sequence_access(Some(len))?)
618 }
619
620 fn struct_variant<V>(self, _fields: &'static [&'static str], visitor: V) -> Result<V::Value>
621 where
622 V: de::Visitor<'de>,
623 {
624 visitor.visit_map(self.de.dict_access()?)
625 }
626 }
627
628 // See serde_json
629 #[cfg(feature = "arbitrary_precision")]
630 struct NumberDeserializer {
631 number: Option<String>,
632 }
633
634 #[cfg(feature = "arbitrary_precision")]
635 impl<'de> de::MapAccess<'de> for NumberDeserializer {
636 type Error = PythonizeError;
637
638 fn next_key_seed<K>(&mut self, seed: K) -> Result<Option<K::Value>>
639 where
640 K: de::DeserializeSeed<'de>,
641 {
642 if self.number.is_none() {
643 return Ok(None);
644 }
645 seed.deserialize(TOKEN.into_deserializer()).map(Some)
646 }
647
648 fn next_value_seed<V>(&mut self, seed: V) -> Result<V::Value>
649 where
650 V: de::DeserializeSeed<'de>,
651 {
652 seed.deserialize(self.number.take().unwrap().into_deserializer())
653 }
654 }
655
656 #[cfg(test)]
657 mod test {
658 use std::{collections::HashMap, ffi::CStr};
659
660 use super::*;
661 use crate::error::ErrorImpl;
662 use maplit::hashmap;
663 use pyo3::{IntoPyObject, Python};
664 use serde_json::{json, Value as JsonValue};
665
666 fn test_de<T>(code: &CStr, expected: &T, expected_json: &JsonValue)
667 where
668 T: de::DeserializeOwned + PartialEq + std::fmt::Debug,
669 {
670 Python::attach(|py| {
671 let obj = py.eval(code, None, None).unwrap();
672 test_de_with_obj(&obj, expected, expected_json);
673 });
674 }
675
676 fn test_de_with_obj<T>(obj: &Bound<'_, PyAny>, expected: &T, expected_json: &JsonValue)
677 where
678 T: de::DeserializeOwned + PartialEq + std::fmt::Debug,
679 {
680 let actual: T = depythonize(obj).unwrap();
681 assert_eq!(&actual, expected);
682
683 let actual_json: JsonValue = depythonize(obj).unwrap();
684 assert_eq!(&actual_json, expected_json);
685 }
686
687 #[test]
688 fn test_empty_struct() {
689 #[derive(Debug, Deserialize, PartialEq)]
690 struct Empty;
691
692 let expected = Empty;
693 let expected_json = json!(null);
694 let code = c"None";
695 test_de(code, &expected, &expected_json);
696 }
697
698 #[test]
699 fn test_struct() {
700 #[derive(Debug, Deserialize, PartialEq)]
701 struct Struct {
702 foo: String,
703 bar: usize,
704 baz: f32,
705 qux: bool,
706 }
707
708 let expected = Struct {
709 foo: "Foo".to_string(),
710 bar: 8usize,
711 baz: 45.23,
712 qux: true,
713 };
714 let expected_json = json!({
715 "foo": "Foo",
716 "bar": 8,
717 "baz": 45.23,
718 "qux": true
719 });
720 let code = c"{'foo': 'Foo', 'bar': 8, 'baz': 45.23, 'qux': True}";
721 test_de(code, &expected, &expected_json);
722 }
723
724 #[test]
725 fn test_struct_missing_key() {
726 #[derive(Debug, Deserialize, PartialEq)]
727 struct Struct {
728 foo: String,
729 bar: usize,
730 }
731
732 let code = c"{'foo': 'Foo'}";
733
734 Python::attach(|py| {
735 let locals = PyDict::new(py);
736 let obj = py.eval(code, None, Some(&locals)).unwrap();
737 assert!(matches!(
738 *depythonize::<Struct>(&obj).unwrap_err().inner,
739 ErrorImpl::Message(msg) if msg == "missing field `bar`"
740 ));
741 })
742 }
743
744 #[test]
745 fn test_tuple_struct() {
746 #[derive(Debug, Deserialize, PartialEq)]
747 struct TupleStruct(String, f64);
748
749 let expected = TupleStruct("cat".to_string(), -10.05);
750 let expected_json = json!(["cat", -10.05]);
751 let code = c"('cat', -10.05)";
752 test_de(code, &expected, &expected_json);
753 }
754
755 #[test]
756 fn test_tuple_too_long() {
757 #[derive(Debug, Deserialize, PartialEq)]
758 struct TupleStruct(String, f64);
759
760 let code = c"('cat', -10.05, 'foo')";
761
762 Python::attach(|py| {
763 let locals = PyDict::new(py);
764 let obj = py.eval(code, None, Some(&locals)).unwrap();
765 assert!(matches!(
766 *depythonize::<TupleStruct>(&obj).unwrap_err().inner,
767 ErrorImpl::IncorrectSequenceLength { expected, got } if expected == 2 && got == 3
768 ));
769 })
770 }
771
772 #[test]
773 fn test_tuple_struct_from_pylist() {
774 #[derive(Debug, Deserialize, PartialEq)]
775 struct TupleStruct(String, f64);
776
777 let expected = TupleStruct("cat".to_string(), -10.05);
778 let expected_json = json!(["cat", -10.05]);
779 let code = c"['cat', -10.05]";
780 test_de(code, &expected, &expected_json);
781 }
782
783 #[test]
784 fn test_tuple() {
785 let expected = ("foo".to_string(), 5);
786 let expected_json = json!(["foo", 5]);
787 let code = c"('foo', 5)";
788 test_de(code, &expected, &expected_json);
789 }
790
791 #[test]
792 fn test_tuple_from_pylist() {
793 let expected = ("foo".to_string(), 5);
794 let expected_json = json!(["foo", 5]);
795 let code = c"['foo', 5]";
796 test_de(code, &expected, &expected_json);
797 }
798
799 #[test]
800 fn test_vec_from_pyset() {
801 let expected = vec!["foo".to_string()];
802 let expected_json = json!(["foo"]);
803 let code = c"{'foo'}";
804 test_de(code, &expected, &expected_json);
805 }
806
807 #[test]
808 fn test_vec_from_pyfrozenset() {
809 let expected = vec!["foo".to_string()];
810 let expected_json = json!(["foo"]);
811 let code = c"frozenset({'foo'})";
812 test_de(code, &expected, &expected_json);
813 }
814
815 #[test]
816 fn test_vec() {
817 let expected = vec![3, 2, 1];
818 let expected_json = json!([3, 2, 1]);
819 let code = c"[3, 2, 1]";
820 test_de(code, &expected, &expected_json);
821 }
822
823 #[test]
824 fn test_vec_from_tuple() {
825 let expected = vec![3, 2, 1];
826 let expected_json = json!([3, 2, 1]);
827 let code = c"(3, 2, 1)";
828 test_de(code, &expected, &expected_json);
829 }
830
831 #[test]
832 fn test_hashmap() {
833 let expected = hashmap! {"foo".to_string() => 4};
834 let expected_json = json!({"foo": 4 });
835 let code = c"{'foo': 4}";
836 test_de(code, &expected, &expected_json);
837 }
838
839 #[test]
840 fn test_enum_variant() {
841 #[derive(Debug, Deserialize, PartialEq)]
842 enum Foo {
843 Variant,
844 }
845
846 let expected = Foo::Variant;
847 let expected_json = json!("Variant");
848 let code = c"'Variant'";
849 test_de(code, &expected, &expected_json);
850 }
851
852 #[test]
853 fn test_enum_tuple_variant() {
854 #[derive(Debug, Deserialize, PartialEq)]
855 enum Foo {
856 Tuple(i32, String),
857 }
858
859 let expected = Foo::Tuple(12, "cat".to_string());
860 let expected_json = json!({"Tuple": [12, "cat"]});
861 let code = c"{'Tuple': [12, 'cat']}";
862 test_de(code, &expected, &expected_json);
863 }
864
865 #[test]
866 fn test_enum_newtype_variant() {
867 #[derive(Debug, Deserialize, PartialEq)]
868 enum Foo {
869 NewType(String),
870 }
871
872 let expected = Foo::NewType("cat".to_string());
873 let expected_json = json!({"NewType": "cat" });
874 let code = c"{'NewType': 'cat'}";
875 test_de(code, &expected, &expected_json);
876 }
877
878 #[test]
879 fn test_enum_struct_variant() {
880 #[derive(Debug, Deserialize, PartialEq)]
881 enum Foo {
882 Struct { foo: String, bar: usize },
883 }
884
885 let expected = Foo::Struct {
886 foo: "cat".to_string(),
887 bar: 25,
888 };
889 let expected_json = json!({"Struct": {"foo": "cat", "bar": 25 }});
890 let code = c"{'Struct': {'foo': 'cat', 'bar': 25}}";
891 test_de(code, &expected, &expected_json);
892 }
893 #[test]
894 fn test_enum_untagged_tuple_variant() {
895 #[derive(Debug, Deserialize, PartialEq)]
896 #[serde(untagged)]
897 enum Foo {
898 Tuple(f32, char),
899 }
900
901 let expected = Foo::Tuple(12.0, 'c');
902 let expected_json = json!([12.0, 'c']);
903 let code = c"[12.0, 'c']";
904 test_de(code, &expected, &expected_json);
905 }
906
907 #[test]
908 fn test_enum_untagged_newtype_variant() {
909 #[derive(Debug, Deserialize, PartialEq)]
910 #[serde(untagged)]
911 enum Foo {
912 NewType(String),
913 }
914
915 let expected = Foo::NewType("cat".to_string());
916 let expected_json = json!("cat");
917 let code = c"'cat'";
918 test_de(code, &expected, &expected_json);
919 }
920
921 #[test]
922 fn test_enum_untagged_struct_variant() {
923 #[derive(Debug, Deserialize, PartialEq)]
924 #[serde(untagged)]
925 enum Foo {
926 Struct { foo: Vec<char>, bar: [u8; 4] },
927 }
928
929 let expected = Foo::Struct {
930 foo: vec!['a', 'b', 'c'],
931 bar: [2, 5, 3, 1],
932 };
933 let expected_json = json!({"foo": ["a", "b", "c"], "bar": [2, 5, 3, 1]});
934 let code = c"{'foo': ['a', 'b', 'c'], 'bar': [2, 5, 3, 1]}";
935 test_de(code, &expected, &expected_json);
936 }
937
938 #[test]
939 fn test_nested_type() {
940 #[derive(Debug, Deserialize, PartialEq)]
941 struct Foo {
942 name: String,
943 bar: Bar,
944 }
945
946 #[derive(Debug, Deserialize, PartialEq)]
947 struct Bar {
948 value: usize,
949 variant: Baz,
950 }
951
952 #[derive(Debug, Deserialize, PartialEq)]
953 enum Baz {
954 Basic,
955 Tuple(f32, u32),
956 }
957
958 let expected = Foo {
959 name: "SomeFoo".to_string(),
960 bar: Bar {
961 value: 13,
962 variant: Baz::Tuple(-1.5, 8),
963 },
964 };
965 let expected_json =
966 json!({"name": "SomeFoo", "bar": { "value": 13, "variant": { "Tuple": [-1.5, 8]}}});
967 let code = c"{'name': 'SomeFoo', 'bar': {'value': 13, 'variant': {'Tuple': [-1.5, 8]}}}";
968 test_de(code, &expected, &expected_json);
969 }
970
971 #[test]
972 fn test_int_limits() {
973 Python::attach(|py| {
974 // serde_json::Value supports u64 and i64 as maximum sizes
975 let _: serde_json::Value = depythonize(&u8::MAX.into_pyobject(py).unwrap()).unwrap();
976 let _: serde_json::Value = depythonize(&u8::MIN.into_pyobject(py).unwrap()).unwrap();
977 let _: serde_json::Value = depythonize(&i8::MAX.into_pyobject(py).unwrap()).unwrap();
978 let _: serde_json::Value = depythonize(&i8::MIN.into_pyobject(py).unwrap()).unwrap();
979
980 let _: serde_json::Value = depythonize(&u16::MAX.into_pyobject(py).unwrap()).unwrap();
981 let _: serde_json::Value = depythonize(&u16::MIN.into_pyobject(py).unwrap()).unwrap();
982 let _: serde_json::Value = depythonize(&i16::MAX.into_pyobject(py).unwrap()).unwrap();
983 let _: serde_json::Value = depythonize(&i16::MIN.into_pyobject(py).unwrap()).unwrap();
984
985 let _: serde_json::Value = depythonize(&u32::MAX.into_pyobject(py).unwrap()).unwrap();
986 let _: serde_json::Value = depythonize(&u32::MIN.into_pyobject(py).unwrap()).unwrap();
987 let _: serde_json::Value = depythonize(&i32::MAX.into_pyobject(py).unwrap()).unwrap();
988 let _: serde_json::Value = depythonize(&i32::MIN.into_pyobject(py).unwrap()).unwrap();
989
990 let _: serde_json::Value = depythonize(&u64::MAX.into_pyobject(py).unwrap()).unwrap();
991 let _: serde_json::Value = depythonize(&u64::MIN.into_pyobject(py).unwrap()).unwrap();
992 let _: serde_json::Value = depythonize(&i64::MAX.into_pyobject(py).unwrap()).unwrap();
993 let _: serde_json::Value = depythonize(&i64::MIN.into_pyobject(py).unwrap()).unwrap();
994
995 let _: u128 = depythonize(&u128::MAX.into_pyobject(py).unwrap()).unwrap();
996 let _: i128 = depythonize(&u128::MIN.into_pyobject(py).unwrap()).unwrap();
997
998 let _: i128 = depythonize(&i128::MAX.into_pyobject(py).unwrap()).unwrap();
999 let _: i128 = depythonize(&i128::MIN.into_pyobject(py).unwrap()).unwrap();
1000 });
1001 }
1002
1003 #[test]
1004 fn test_deserialize_bytes() {
1005 Python::attach(|py| {
1006 let obj = PyBytes::new(py, "hello".as_bytes());
1007 let actual: Vec<u8> = depythonize(&obj).unwrap();
1008 assert_eq!(actual, b"hello");
1009 })
1010 }
1011
1012 #[test]
1013 fn test_char() {
1014 let expected = 'a';
1015 let expected_json = json!("a");
1016 let code = c"'a'";
1017 test_de(code, &expected, &expected_json);
1018 }
1019
1020 #[test]
1021 fn test_unknown_type() {
1022 Python::attach(|py| {
1023 let obj = py
1024 .import("decimal")
1025 .unwrap()
1026 .getattr("Decimal")
1027 .unwrap()
1028 .call0()
1029 .unwrap();
1030 let err = depythonize::<serde_json::Value>(&obj).unwrap_err();
1031 assert!(matches!(
1032 *err.inner,
1033 ErrorImpl::UnsupportedType(name) if name == "Decimal"
1034 ));
1035 });
1036 }
1037
1038 #[test]
1039 fn test_dataclass() {
1040 let code = c"\
1041 from dataclasses import dataclass
1042
1043 @dataclass
1044 class Point:
1045 x: int
1046 y: int
1047
1048 point = Point(1, 2)";
1049
1050 #[derive(Debug, Deserialize, PartialEq)]
1051 struct Point {
1052 x: i32,
1053 y: i32,
1054 }
1055
1056 let expected = Point { x: 1, y: 2 };
1057 let expected_json = json!({"x": 1, "y": 2});
1058
1059 Python::attach(|py| {
1060 let locals = PyDict::new(py);
1061 py.run(code, None, Some(&locals)).unwrap();
1062 let obj = locals.get_item("point").unwrap().unwrap();
1063 test_de_with_obj(&obj, &expected, &expected_json);
1064
1065 let map: HashMap<String, i32> = depythonize(&obj).unwrap();
1066 assert_eq!(map.len(), 2);
1067 assert_eq!(*map.get("x").unwrap(), 1);
1068 assert_eq!(*map.get("y").unwrap(), 2);
1069 });
1070 }
1071
1072 #[test]
1073 fn test_dataclass_missing_field() {
1074 let code = c"\
1075 from dataclasses import dataclass
1076
1077 @dataclass
1078 class Point:
1079 x: int
1080 y: int
1081
1082 point = Point(1, 2)";
1083
1084 #[derive(Debug, Deserialize, PartialEq)]
1085 struct Point {
1086 x: i32,
1087 y: i32,
1088 z: i32,
1089 }
1090
1091 Python::attach(|py| {
1092 let locals = PyDict::new(py);
1093 py.run(code, None, Some(&locals)).unwrap();
1094 let obj = locals.get_item("point").unwrap().unwrap();
1095 let err = depythonize::<Point>(&obj).unwrap_err();
1096 assert!(matches!(
1097 *err.inner,
1098 ErrorImpl::Message(msg) if msg == "missing field `z`"
1099 ));
1100 });
1101 }
1102
1103 #[test]
1104 fn test_dataclass_extra_field() {
1105 let code = c"\
1106 from dataclasses import dataclass
1107
1108 @dataclass
1109 class Point:
1110 x: int
1111 y: int
1112 z: int
1113
1114 point = Point(1, 2, 3)";
1115
1116 #[derive(Debug, Deserialize, PartialEq)]
1117 #[serde(deny_unknown_fields)]
1118 struct Point {
1119 x: i32,
1120 y: i32,
1121 }
1122
1123 Python::attach(|py| {
1124 let locals = PyDict::new(py);
1125 py.run(code, None, Some(&locals)).unwrap();
1126 let obj = locals.get_item("point").unwrap().unwrap();
1127 let err = depythonize::<Point>(&obj).unwrap_err();
1128 assert!(matches!(
1129 *err.inner,
1130 ErrorImpl::Message(msg) if msg == "unknown field `z`, expected `x` or `y`"
1131 ));
1132 });
1133 }
1134 }