Skip to content

Commit

Permalink
test(serde): add unit tests for serde optional (#1658)
Browse files Browse the repository at this point in the history
Co-authored-by: zerosnacks <[email protected]>
  • Loading branch information
tcoratger and zerosnacks authored Nov 18, 2024
1 parent 14d6aaa commit 9b0e04d
Showing 1 changed file with 50 additions and 0 deletions.
50 changes: 50 additions & 0 deletions crates/serde/src/optional.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,3 +26,53 @@ where

Ok(value)
}

#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;

#[derive(Debug, Deserialize, PartialEq)]
struct TestStruct {
#[serde(default, deserialize_with = "null_as_default")]
value: Vec<i32>,

#[serde(default, deserialize_with = "reject_if_some")]
should_be_none: Option<String>,
}

#[test]
fn test_null_as_default_with_null() {
let json_data = json!({ "value": null });
let result: TestStruct = serde_json::from_value(json_data).unwrap();
assert_eq!(result.value, Vec::<i32>::new());
}

#[test]
fn test_null_as_default_with_value() {
let json_data = json!({ "value": [1, 2, 3] });
let result: TestStruct = serde_json::from_value(json_data).unwrap();
assert_eq!(result.value, vec![1, 2, 3]);
}

#[test]
fn test_null_as_default_with_missing_field() {
let json_data = json!({});
let result: TestStruct = serde_json::from_value(json_data).unwrap();
assert_eq!(result.value, Vec::<i32>::new());
}

#[test]
fn test_reject_if_some_with_none() {
let json_data = json!({});
let result: TestStruct = serde_json::from_value(json_data).unwrap();
assert_eq!(result.should_be_none, None);
}

#[test]
fn test_reject_if_some_with_some() {
let json_data = json!({ "should_be_none": "unexpected value" });
let result: Result<TestStruct, _> = serde_json::from_value(json_data);
assert!(result.is_err());
}
}

0 comments on commit 9b0e04d

Please sign in to comment.