| 1 | use crate::prelude::*; |
| 2 | |
| 3 | #[derive(JsonSchema, Deserialize, Serialize, Default)] |
| 4 | #[serde(default)] |
| 5 | struct MyStruct { |
| 6 | integer: u32, |
| 7 | boolean: bool, |
| 8 | option_string: Option<String>, |
| 9 | #[serde(skip_serializing_if = "str::is_empty")] |
| 10 | string_skip_empty: String, |
| 11 | #[serde(with = "struct_2_as_str")] |
| 12 | #[schemars(with = "str", pattern(r"^\d+ (true|false)$"))] |
| 13 | struct2: MyStruct2, |
| 14 | #[serde(skip_serializing)] |
| 15 | not_serialize: NotSerialize, |
| 16 | } |
| 17 | |
| 18 | #[derive(JsonSchema, Deserialize, Serialize, Default)] |
| 19 | #[serde(default = "ten_and_true")] |
| 20 | struct MyStruct2 { |
| 21 | #[serde(default = "six")] |
| 22 | integer: u32, |
| 23 | boolean: bool, |
| 24 | } |
| 25 | |
| 26 | #[allow(dead_code)] |
| 27 | #[derive(JsonSchema, Deserialize, Default)] |
| 28 | struct NotSerialize(i8); |
| 29 | |
| 30 | mod struct_2_as_str { |
| 31 | use super::MyStruct2; |
| 32 | |
| 33 | pub(super) fn serialize<S>(value: &MyStruct2, ser: S) -> Result<S::Ok, S::Error> |
| 34 | where |
| 35 | S: serde::Serializer, |
| 36 | { |
| 37 | ser.collect_str(&format_args!("{} {}", value.integer, value.boolean)) |
| 38 | } |
| 39 | |
| 40 | pub(super) fn deserialize<'de, D>(deser: D) -> Result<MyStruct2, D::Error> |
| 41 | where |
| 42 | D: serde::Deserializer<'de>, |
| 43 | { |
| 44 | use serde::de::{Deserialize, Error}; |
| 45 | let error = || Error::custom("invalid string"); |
| 46 | |
| 47 | let (i, b) = <&str>::deserialize(deser)? |
| 48 | .split_once(' ') |
| 49 | .ok_or_else(error)?; |
| 50 | |
| 51 | Ok(MyStruct2 { |
| 52 | integer: i.parse().map_err(|_| error())?, |
| 53 | boolean: b.parse().map_err(|_| error())?, |
| 54 | }) |
| 55 | } |
| 56 | } |
| 57 | |
| 58 | fn ten_and_true() -> MyStruct2 { |
| 59 | MyStruct2 { |
| 60 | integer: 10, |
| 61 | boolean: true, |
| 62 | } |
| 63 | } |
| 64 | |
| 65 | fn six() -> u32 { |
| 66 | 6 |
| 67 | } |
| 68 | |
| 69 | #[test] |
| 70 | fn default_fields() { |
| 71 | test!(MyStruct) |
| 72 | .assert_snapshot() |
| 73 | .assert_allows_ser_roundtrip([ |
| 74 | MyStruct::default(), |
| 75 | MyStruct { |
| 76 | integer: 123, |
| 77 | boolean: true, |
| 78 | option_string: Some("test".into()), |
| 79 | string_skip_empty: "test".into(), |
| 80 | struct2: ten_and_true(), |
| 81 | not_serialize: NotSerialize(42), |
| 82 | }, |
| 83 | ]) |
| 84 | .assert_allows_de_roundtrip([ |
| 85 | json!({}), |
| 86 | json!({ "not_serialize": 127 }) |
| 87 | ]) |
| 88 | .assert_rejects_de([ |
| 89 | json!({ "not_serialize": "a string" }) |
| 90 | ]) |
| 91 | .assert_matches_de_roundtrip(arbitrary_values_except( |
| 92 | Value::is_array, |
| 93 | "structs with `#derive(Deserialize)` can technically be deserialized from sequences, but that's not intended to be used via JSON, so schemars ignores it", |
| 94 | )); |
| 95 | } |