| 1 | use crate::prelude::*; |
| 2 | use pretty_assertions::assert_eq; |
| 3 | use schemars::Schema; |
| 4 | use std::fmt::Write; |
| 5 | |
| 6 | // This test ensures that `extend` and `transform` attributes are applied after other attributes, |
| 7 | // and transforms are applied in the order they are defined. |
| 8 | |
| 9 | #[derive(JsonSchema, Deserialize, Serialize)] |
| 10 | #[schemars(transform = suffix_description, description = "[Overwritten]", extend("description" = "The enum", "suffix" = "..."))] |
| 11 | #[serde(untagged)] |
| 12 | enum Untagged { |
| 13 | #[schemars(transform = suffix_description, description = "The variant", extend("suffix" = "?"))] |
| 14 | A { |
| 15 | #[schemars(transform = suffix_description, description = "The field", extend("suffix" = "!"))] |
| 16 | #[schemars(range(min = 1), transform = remove_minimum_and_default)] |
| 17 | #[serde(default)] |
| 18 | i: i32, |
| 19 | }, |
| 20 | } |
| 21 | |
| 22 | fn suffix_description(schema: &mut Schema) { |
| 23 | let minimum = schema.get("minimum").map(Value::to_string); |
| 24 | |
| 25 | let Some(Value::String(suffix)) = schema.remove("suffix") else { |
| 26 | panic!("expected `suffix` to be present and a string"); |
| 27 | }; |
| 28 | let Some(Value::String(description)) = schema.get_mut("description") else { |
| 29 | panic!("expected `description` to be present and a string"); |
| 30 | }; |
| 31 | |
| 32 | description.push_str(&suffix); |
| 33 | |
| 34 | if let Some(minimum) = minimum { |
| 35 | write!(description, " (At least {})", minimum).unwrap(); |
| 36 | } |
| 37 | } |
| 38 | |
| 39 | fn remove_minimum_and_default(schema: &mut Schema) { |
| 40 | schema.remove("minimum"); |
| 41 | schema.remove("default"); |
| 42 | } |
| 43 | |
| 44 | #[test] |
| 45 | fn attributes_applied_in_order() { |
| 46 | test!(Untagged).assert_snapshot().custom(|schema, _| { |
| 47 | assert_eq!(schema.pointer("/description"), Some(&json!("The enum..."))); |
| 48 | assert_eq!( |
| 49 | schema.pointer("/anyOf/0/description"), |
| 50 | Some(&json!("The variant?")) |
| 51 | ); |
| 52 | assert_eq!( |
| 53 | schema.pointer("/anyOf/0/properties/i/description"), |
| 54 | Some(&json!("The field! (At least 1)")) |
| 55 | ); |
| 56 | assert_eq!(schema.pointer("/anyOf/0/properties/i/default"), None); |
| 57 | assert_eq!(schema.pointer("/anyOf/0/properties/i/minimum"), None); |
| 58 | }); |
| 59 | } |