| 1 | use crate::prelude::*; |
| 2 | use schemars::generate::SchemaSettings; |
| 3 | use std::collections::BTreeMap; |
| 4 | |
| 5 | #[derive(Deserialize, Serialize, Default, Clone)] |
| 6 | #[serde(rename_all = "camelCase")] |
| 7 | pub struct MyStruct { |
| 8 | pub my_int: i32, |
| 9 | pub my_bool: bool, |
| 10 | pub my_nullable_enum: Option<MyEnum>, |
| 11 | pub my_inner_struct: MyInnerStruct, |
| 12 | #[serde(skip)] |
| 13 | pub _skip: i32, |
| 14 | #[serde(skip_serializing_if = "Option::is_none")] |
| 15 | pub skip_if_none: Option<MyEnum>, |
| 16 | } |
| 17 | |
| 18 | #[derive(Deserialize, Serialize, Default, Clone)] |
| 19 | pub struct MyInnerStruct { |
| 20 | pub my_map: BTreeMap<String, f64>, |
| 21 | pub my_vec: Vec<f32>, |
| 22 | pub my_empty_map: BTreeMap<String, f64>, |
| 23 | pub my_empty_vec: Vec<f32>, |
| 24 | pub my_tuple: (char, u8), |
| 25 | } |
| 26 | |
| 27 | #[derive(JsonSchema, Deserialize, Serialize, Clone)] |
| 28 | pub enum MyEnum { |
| 29 | NewType(String), |
| 30 | Struct { floats: Vec<f32> }, |
| 31 | } |
| 32 | |
| 33 | fn struct_value() -> MyStruct { |
| 34 | MyStruct { |
| 35 | my_int: 123, |
| 36 | my_bool: true, |
| 37 | my_nullable_enum: None, |
| 38 | my_inner_struct: MyInnerStruct { |
| 39 | my_map: [("k".to_owned(), 1.23)].into_iter().collect(), |
| 40 | my_vec: vec![1.0, 2.0, 3.0], |
| 41 | my_empty_map: BTreeMap::new(), |
| 42 | my_empty_vec: Vec::new(), |
| 43 | my_tuple: ('💩', 42), |
| 44 | }, |
| 45 | _skip: 123, |
| 46 | skip_if_none: None, |
| 47 | } |
| 48 | } |
| 49 | |
| 50 | #[test] |
| 51 | fn custom_struct() { |
| 52 | let value = struct_value(); |
| 53 | |
| 54 | test!(value: value.clone()) |
| 55 | .assert_snapshot() |
| 56 | .assert_allows_ser_roundtrip([value, MyStruct::default()]); |
| 57 | } |
| 58 | |
| 59 | #[test] |
| 60 | fn custom_struct_openapi3() { |
| 61 | let value = struct_value(); |
| 62 | |
| 63 | test!(value: value.clone(), SchemaSettings::openapi3()).assert_snapshot(); |
| 64 | |
| 65 | // schemars uses a nonstandard meta-schema for openapi 3.0 which the jsonschema crate doesn't |
| 66 | // accept, so we swap it out for the standard draft-04 meta-schema. |
| 67 | let draft04 = "http://json-schema.org/draft-04/schema"; |
| 68 | test!(value: value.clone(), SchemaSettings::openapi3().with(|o| o.meta_schema = Some(draft04.into()))) |
| 69 | .assert_allows_ser_roundtrip([value, MyStruct::default()]); |
| 70 | } |
| 71 | |
| 72 | #[test] |
| 73 | fn json_value() { |
| 74 | let value = json!({ |
| 75 | "zero": 0, |
| 76 | "zeroPointZero": 0.0, |
| 77 | "bool": true, |
| 78 | "null": null, |
| 79 | "object": { |
| 80 | "strings": ["foo", "bar"], |
| 81 | "mixed": [1, true] |
| 82 | }, |
| 83 | }); |
| 84 | |
| 85 | test!(value: value.clone()) |
| 86 | .assert_snapshot() |
| 87 | .assert_allows_ser_roundtrip([value]); |
| 88 | } |