Debian Codegraph @

tests/integration/transform.rs

raw symbols SCIP
1 use crate::prelude::*;
2 use pretty_assertions::assert_eq;
3 use schemars::{
4 transform::{RecursiveTransform, Transform},
5 Schema,
6 };
7 use serde_json::Map;
8
9 fn insert_upper_type(schema: &mut Schema) {
10 if let Some(Value::String(ty)) = schema.get("type") {
11 schema.insert("x-upperType".to_owned(), ty.to_uppercase().into());
12 }
13 }
14
15 fn insert_property_count(schema: &mut Schema) {
16 let count = schema
17 .get("properties")
18 .and_then(Value::as_object)
19 .map_or(0, Map::len);
20 schema.insert("x-propertyCount".to_owned(), count.into());
21 }
22
23 #[derive(JsonSchema, Deserialize, Serialize, Default)]
24 #[schemars(transform = RecursiveTransform(insert_upper_type), transform = insert_property_count)]
25 struct Struct {
26 value: Value,
27 #[schemars(transform = insert_property_count)]
28 int: i32,
29 }
30
31 #[test]
32 fn transform_struct() {
33 test!(Struct)
34 .assert_snapshot()
35 .assert_allows_ser_roundtrip_default()
36 .custom(assert_upper_type_valid);
37 }
38
39 #[derive(JsonSchema, Deserialize, Serialize, Default)]
40 #[schemars(transform = RecursiveTransform(insert_upper_type), transform = insert_property_count)]
41 enum External {
42 #[default]
43 #[schemars(transform = insert_property_count)]
44 Unit,
45 #[schemars(transform = insert_property_count)]
46 NewType(Value),
47 }
48
49 #[test]
50 fn transform_enum() {
51 test!(External)
52 .assert_snapshot()
53 .assert_allows_ser_roundtrip_default()
54 .custom(assert_upper_type_valid);
55 }
56
57 fn assert_upper_type_valid(schema: &Schema, _: schemars::generate::Contract) {
58 let mut schema = schema.clone();
59
60 RecursiveTransform(|s: &mut Schema| {
61 assert_eq!(
62 s.remove("x-upperType").map(|v| v.to_string()),
63 s.get("type").map(|v| v.to_string().to_uppercase()),
64 );
65 })
66 .transform(&mut schema);
67
68 assert!(!schema.to_value().to_string().contains("x-upperType"));
69 }