diff --git a/src/lib.rs b/src/lib.rs index 6c89ff2a..b08ff80b 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1089,4 +1089,72 @@ impl DerefMut for AlignedBuf { } #[cfg(test)] -mod tests; +mod tests { + use serde_ext::Deserialize; + use crate::Deserializer; + + static JSON: &str = r#"{ + "code": 200, + "success": true, + "payload": { + "features": [ + "serde", + "json" + ] + } + }"#; + + #[derive(Deserialize, PartialEq, Debug)] + struct TestPayload { + features: Vec + } + + #[derive(Deserialize, PartialEq, Debug)] + struct TestEnvelope { + code: usize, + success: bool, + payload: TestPayload + } + + #[test] + fn test_deser_to_value() { + let mut json = JSON.as_bytes().to_vec(); + let d = Deserializer::from_slice(&mut json).expect("Invalid JSON"); + + let original_index = d.idx; + let original_nodes = d.tape.len(); + + let v = d.as_value(); + + assert!(v.contains_key("payload"), "Failed to find payload key"); + let v = v.get("payload").unwrap(); + assert!(v.is_object(), "payload not recognized as object: {:?}", v); + assert!(v.contains_key("features"), "Failed to find features key"); + let v = v.get("features").unwrap(); + assert!(v.is_array(), "features not recognized as array: {:?}", v); + + // proving that value peeking doesn't affect the deserializer + + assert_eq!(original_index, d.idx, "Deserializer has been internally modified"); + assert_eq!(original_nodes, d.tape.len(), "Deserializer has been internally modified"); + } + + #[test] + fn test_deser_restart() { + let mut json = JSON.as_bytes().to_vec(); + let mut d = Deserializer::from_slice(&mut json).expect("Invalid JSON"); + + let original_index = d.idx; + let original_nodes = d.tape.len(); + + let test1 = TestEnvelope::deserialize(&mut d).expect("Deserialization failed"); + + assert!(original_index != d.idx, "Deserializer has NOT been internally modified"); + assert_eq!(original_nodes, d.tape.len(), "Deserializer nodes are NOT intact"); + + d.restart(); + + let test2 = TestEnvelope::deserialize(&mut d).expect("Deserialization failed"); + + assert_eq!(test2, test1, "Deserializer is not idempotent"); + }}