From 5a88f7ed6940b316a0609aca66e257af9cca122d Mon Sep 17 00:00:00 2001 From: Jack Lloyd Date: Mon, 2 Dec 2024 10:03:54 -0500 Subject: [PATCH] Add a test regarding structs with a new Option field This checks that adding an Option field to a struct has the expected behavior, where * For an old writer and new reader, the struct deserializes with a field of None * For a new writer and an old reader, the struct deserializes with the value of the Option ignored. --- rust/candid/tests/serde.rs | 50 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) diff --git a/rust/candid/tests/serde.rs b/rust/candid/tests/serde.rs index 87113a46..375b796a 100644 --- a/rust/candid/tests/serde.rs +++ b/rust/candid/tests/serde.rs @@ -193,6 +193,56 @@ fn test_option() { test_decode(&bytes, &expected); } +#[test] +fn test_struct_with_option() { + #[derive(CandidType, Deserialize, PartialEq, Debug)] + struct Old { + field: i32, + } + + #[derive(CandidType, Deserialize, PartialEq, Debug)] + struct New { + field: i32, + new_field: Option, + } + + let old_bytes = encode(&Old { field: 1 }); + let new_bytes_with_none = encode(&New { + field: 2, + new_field: None, + }); + let new_bytes_with_some = encode(&New { + field: 3, + new_field: Some(4), + }); + + test_decode(&old_bytes, &Old { field: 1 }); + test_decode(&new_bytes_with_none, &Old { field: 2 }); + test_decode(&new_bytes_with_some, &Old { field: 3 }); + + test_decode( + &old_bytes, + &New { + field: 1, + new_field: None, + }, + ); + test_decode( + &new_bytes_with_none, + &New { + field: 2, + new_field: None, + }, + ); + test_decode( + &new_bytes_with_some, + &New { + field: 3, + new_field: Some(4), + }, + ); +} + #[test] fn test_struct() { #[derive(PartialEq, Debug, Deserialize, CandidType)]