Debian Codegraph @

tests/integration/test_helper.rs

raw symbols ◀ ▶ SCIP
1 Debian patch touch this file
1 use jsonschema::Validator;
2 use pretty_assertions::assert_eq;
3 use schemars::{
4 generate::{Contract, SchemaSettings},
5 JsonSchema, Schema,
6 };
7 use serde::{de::DeserializeOwned, Serialize};
8 use serde_json::{json, Value};
9 use snapbox::{data::DataFormat, IntoJson};
10 use std::{
11 any::type_name, borrow::Borrow, cell::OnceCell, f64, marker::PhantomData, path::Path,
12 sync::OnceLock,
13 };
14
15 pub struct TestHelper<T> {
16 settings: SchemaSettings,
17 name: String,
18 phantom: PhantomData<T>,
19 de_schema: Schema,
20 ser_schema: Schema,
21 de_schema_validator: OnceCell<Validator>,
22 ser_schema_validator: OnceCell<Validator>,
23 validator: fn(&T) -> bool,
24 }
25
26 impl<T> TestHelper<T> {
27 /// Should be used via the `test!(SomeType)` macro
28 pub fn new(name: String, settings: SchemaSettings) -> Self
29 where
30 T: JsonSchema,
31 {
32 let de_schema = schema_for::<T>(&settings, Contract::Deserialize);
33 let ser_schema = schema_for::<T>(&settings, Contract::Serialize);
34 Self {
35 settings,
36 name,
37 phantom: PhantomData,
38 de_schema,
39 ser_schema,
40 de_schema_validator: OnceCell::new(),
41 ser_schema_validator: OnceCell::new(),
42 validator: |_| true,
43 }
44 }
45
46 /// Should be used via the `test!(value: SomeType)` macro
47 pub fn new_for_value(name: String, settings: SchemaSettings, value: T) -> Self
48 where
49 T: Serialize,
50 {
51 let de_schema = schema_for_value(&settings, Contract::Deserialize, &value);
52 let ser_schema = schema_for_value(&settings, Contract::Serialize, &value);
53 Self {
54 settings,
55 name,
56 phantom: PhantomData,
57 de_schema,
58 ser_schema,
59 de_schema_validator: OnceCell::new(),
60 ser_schema_validator: OnceCell::new(),
61 validator: |_| true,
62 }
63 }
64
65 pub fn with_validator(&mut self, validator: fn(&T) -> bool) -> &mut Self {
66 self.validator = validator;
67 self
68 }
69
70 /// Checks the generated schema against the saved schema in the snapshots directory, for manual verification of changes.
71 ///
72 /// Run tests with the SNAPSHOTS env var set to "overwrite" to overwrite any changed snapshots.
73 pub fn assert_snapshot(&self) -> &Self {
•74 let stripped_name = self.name.strip_prefix("schemars/").unwrap_or(&self.name);
75 let common_path = format!("tests/integration/snapshots/schemars/{}.json", stripped_name);
76 let de_path = format!("tests/integration/snapshots/schemars/{}.de.json", stripped_name);
77 let ser_path = format!("tests/integration/snapshots/schemars/{}.ser.json", stripped_name);
78
79 if self.de_schema == self.ser_schema {
80 snapbox::assert_data_eq!(
81 (&self.de_schema).into_json(),
82 snapbox::Data::read_from(Path::new(&common_path), Some(DataFormat::Json)).raw()
83 );
84 _ = std::fs::remove_file(de_path);
85 _ = std::fs::remove_file(ser_path);
86 } else {
87 snapbox::assert_data_eq!(
88 (&self.de_schema).into_json(),
89 snapbox::Data::read_from(Path::new(&de_path), Some(DataFormat::Json)).raw()
90 );
91 snapbox::assert_data_eq!(
92 (&self.ser_schema).into_json(),
93 snapbox::Data::read_from(Path::new(&ser_path), Some(DataFormat::Json)).raw()
94 );
95 _ = std::fs::remove_file(common_path);
96 }
97
98 self
99 }
100
101 /// Checks that the schema generated for this type is identical to that of another type.
102 pub fn assert_identical<T2: JsonSchema>(&self) -> &Self
103 where
104 T: JsonSchema,
105 {
106 snapbox::assert_data_eq!(
107 (&self.de_schema).into_json(),
108 schema_for::<T2>(&self.settings, Contract::Deserialize)
109 .into_json()
110 .raw()
111 );
112 snapbox::assert_data_eq!(
113 (&self.ser_schema).into_json(),
114 schema_for::<T2>(&self.settings, Contract::Serialize)
115 .into_json()
116 .raw()
117 );
118
119 let t = type_name::<T>();
120 let t2 = type_name::<T2>();
121 assert_eq!(
122 T::schema_name(),
123 T2::schema_name(),
124 "`{t}` and `{t2}` have identical schemas, so should have the same schema_name"
125 );
126
127 assert_eq!(
128 T::schema_id(),
129 T2::schema_id(),
130 "`{t}` and `{t2}` have identical schemas, so should have the same schema_id"
131 );
132
133 assert_eq!(
134 T::inline_schema(),
135 T2::inline_schema(),
136 "`{t}` and `{t2}` have identical schemas, so should have the same inline_schema"
137 );
138
139 self
140 }
141
142 pub fn custom(&self, assertion: impl Fn(&Schema, Contract)) -> &Self {
143 assertion(&self.de_schema, Contract::Deserialize);
144 assertion(&self.ser_schema, Contract::Serialize);
145
146 self
147 }
148
149 fn de_schema_validate(&self, instance: &Value) -> bool {
150 self.de_schema_validator
151 .get_or_init(|| build_validator(&self.de_schema))
152 .is_valid(instance)
153 }
154
155 fn ser_schema_validate(&self, instance: &Value) -> bool {
156 self.ser_schema_validator
157 .get_or_init(|| build_validator(&self.ser_schema))
158 .is_valid(instance)
159 }
160 }
161
162 fn build_validator(schema: &Schema) -> Validator {
163 jsonschema::options()
164 .should_validate_formats(true)
165 .build(schema.as_value())
166 .expect("valid schema")
167 }
168
169 impl<T: Serialize> TestHelper<T> {
170 /// Checks that the "serialize" schema allows the given sample values when serialized to JSON.
171 /// If `T implements `DeserializeOwned`, prefer using `assert_allows_ser_roundtrip()`
172 pub fn assert_allows_ser_only(&self, samples: impl IntoIterator<Item = T>) -> &Self {
173 for sample in samples {
174 let json = serde_json::to_value(&sample).unwrap();
175
176 assert!(
177 (self.validator)(&sample),
178 "invalid test case - attempt to serialize value failing validation: {json}"
179 );
180
181 assert!(
182 self.ser_schema_validate(&json),
183 "serialize schema should allow serialized value: {json}"
184 );
185 }
186
187 self
188 }
189 }
190
191 impl<T: Serialize + DeserializeOwned> TestHelper<T> {
192 /// Checks that the "serialize" schema allows the given sample values when serialized to JSON
193 /// and, if the value can then be deserialized, that the "deserialize" schema also allows it.
194 pub fn assert_allows_ser_roundtrip(&self, samples: impl IntoIterator<Item = T>) -> &Self {
195 for sample in samples {
196 let json = serde_json::to_value(&sample).unwrap();
197
198 assert!(
199 (self.validator)(&sample),
200 "invalid test case - attempt to serialize value failing validation: {json}"
201 );
202
203 assert!(
204 self.ser_schema_validate(&json),
205 "serialize schema should allow serialized value: {json}"
206 );
207
208 if T::deserialize(&json).is_ok() {
209 assert!(
210 (self.validator)(&sample),
211 "invalid test case - roundtripped value fails validation: {json}"
212 );
213 assert!(
214 self.de_schema_validate(&json),
215 "deserialize schema should allow value accepted by deserialization: {json}"
216 );
217 } else {
218 assert!(
219 !self.de_schema_validate(&json),
220 "deserialize schema should reject undeserializable value: {json}"
221 );
222 }
223 }
224
225 self
226 }
227
228 /// Checks that the "deserialize" schema allow the given sample values, and the "serialize"
229 /// schema allows the value obtained from deserializing then re-serializing the sample values
230 /// (only for values that can successfully be serialized).
231 ///
232 /// This is intended for types that have different serialize/deserialize schemas, or when you
233 /// want to test specific values that are valid for deserialization but not for serialization.
234 pub fn assert_allows_de_roundtrip(
235 &self,
236 samples: impl IntoIterator<Item = impl Borrow<Value>>,
237 ) -> &Self {
238 for sample in samples {
239 let sample = sample.borrow();
240 let Ok(deserialized) = T::deserialize(sample) else {
241 panic!(
242 "expected deserialize to succeed for {}: {sample}",
243 type_name::<T>()
244 )
245 };
246
247 assert!(
248 (self.validator)(&deserialized),
249 "invalid test case - deserialized value fails validation: {sample}"
250 );
251
252 assert!(
253 self.de_schema_validate(sample),
254 "deserialize schema should allow value accepted by deserialization: {sample}"
255 );
256
257 if let Ok(serialized) = serde_json::to_value(&deserialized) {
258 assert!(
259 self.ser_schema_validate(&serialized),
260 "serialize schema should allow serialized value: {serialized}"
261 );
262 }
263 }
264
265 self
266 }
267
268 /// Checks that the "deserialize" schema allows only the given sample values that successfully
269 /// deserialize and pass validation.
270 ///
271 /// This is intended to be given a range of values (see `arbitrary_values`), allowing limited
272 /// fuzzing.
273 pub fn assert_matches_de_roundtrip(
274 &self,
275 samples: impl IntoIterator<Item = impl Borrow<Value>>,
276 ) -> &Self {
277 for value in samples {
278 let value = value.borrow();
279
280 match T::deserialize(value) {
281 Ok(deserialized) if (self.validator)(&deserialized) => {
282 assert!(
283 self.de_schema_validate(value),
284 "deserialize schema should allow value accepted by deserialization: {value}"
285 );
286
287 if let Ok(serialized) = serde_json::to_value(&deserialized) {
288 assert!(
289 self.ser_schema_validate(&serialized),
290 "serialize schema should allow serialized value: {serialized}"
291 );
292 }
293 }
294 _ => {
295 assert!(
296 !self.de_schema_validate(value),
297 "deserialize schema should reject invalid value: {value}"
298 );
299
300 // This assertion isn't necessarily valid in the general case but it would be
301 // odd (though not necessarily wrong) for it to fail. If this does ever fail
302 // a case that should be legitimate, then this assert can be removed/weakened.
303 assert!(
304 !self.ser_schema_validate(value),
305 "serialize schema should reject invalid value: {value}"
306 );
307 }
308 }
309 }
310
311 self
312 }
313
314 /// Checks that the "deserialize" schema does not allow any of the given sample values.
315 ///
316 /// While `assert_matches_de_roundtrip()` would also work in this case, `assert_rejects_de()`
317 /// has the advantage that it also verifies that the test case itself is actually covering the
318 /// failure case as intended.
319 pub fn assert_rejects_de(&self, values: impl IntoIterator<Item = impl Borrow<Value>>) -> &Self {
320 for value in values {
321 let value = value.borrow();
322
323 assert!(
324 T::deserialize(value).is_err(),
325 "invalid test case - expected deserialize to fail for {}: {value}",
326 type_name::<T>()
327 );
328
329 assert!(
330 !self.de_schema_validate(value),
331 "deserialize schema should reject invalid value: {value}"
332 );
333 }
334
335 self
336 }
337
338 /// Checks that neither "serialize" nor "deserialize" schemas allow any of the given sample
339 /// values when serialized to JSON due to the values failing validation.
340 pub fn assert_rejects_invalid(&self, samples: impl IntoIterator<Item = T>) -> &Self {
341 for sample in samples {
342 let json = serde_json::to_value(&sample).unwrap();
343
344 assert!(
345 !(self.validator)(&sample),
346 "invalid test case - serialized value passes validation: {json}"
347 );
348
349 assert!(
350 !self.de_schema_validate(&json),
351 "deserialize schema should reject invalid value: {json}"
352 );
353 assert!(
354 !self.ser_schema_validate(&json),
355 "serialize schema should reject invalid value: {json}"
356 );
357 }
358
359 self
360 }
361
362 /// Checks that both the "serialize" and "deserialize" schema allow the type's default value
363 /// when serialized to JSON.
364 pub fn assert_allows_ser_roundtrip_default(&self) -> &Self
365 where
366 T: Default,
367 {
368 self.assert_allows_ser_roundtrip([T::default()])
369 }
370 }
371
372 fn schema_for<T: JsonSchema>(base_settings: &SchemaSettings, contract: Contract) -> Schema {
373 base_settings
374 .clone()
375 .with(|s| s.contract = contract)
376 .into_generator()
377 .into_root_schema_for::<T>()
378 }
379
380 fn schema_for_value(
381 base_settings: &SchemaSettings,
382 contract: Contract,
383 value: impl Serialize,
384 ) -> Schema {
385 base_settings
386 .clone()
387 .with(|s| s.contract = contract)
388 .into_generator()
389 .into_root_schema_for_value(&value)
390 .unwrap()
391 }
392
393 /// Returns an iterator over an selection of arbitrary JSON values.
394 ///
395 /// This is intended to be used as `test!(...).assert_matches_de_roundtrip(arbitrary_values())`
396 pub fn arbitrary_values() -> impl Iterator<Item = &'static Value> {
397 fn primitives() -> impl Iterator<Item = Value> {
398 [
399 Value::Null,
400 false.into(),
401 true.into(),
402 0.into(),
403 255.into(),
404 (-1).into(),
405 u64::MAX.into(),
406 f64::consts::PI.into(),
407 "".into(),
408 "0".into(),
409 "3E8".into(),
410 "\tPâté costs “£1”\0".into(),
411 Value::Array(Default::default()),
412 Value::Object(Default::default()),
413 ]
414 .into_iter()
415 }
416
417 // TODO once MSRV has reached 1.80, replace this with LazyLock
418 static VALUES: OnceLock<Vec<Value>> = OnceLock::new();
419
420 VALUES
421 .get_or_init(|| {
422 Vec::from_iter(
423 primitives()
424 .chain(primitives().map(|p| json!([p])))
425 .chain(primitives().map(|p| json!({"key": p}))),
426 )
427 })
428 .iter()
429 }
430
431 /// Returns an iterator over an selection of arbitrary JSON values, except for value that match
432 /// the given filter predicate.
433 ///
434 /// This is to handle known cases of schemas not matching the actual deserialize behaviour.
435 pub fn arbitrary_values_except(
436 filter: impl Fn(&Value) -> bool,
437 _reason: &str,
438 ) -> impl Iterator<Item = &'static Value> {
439 arbitrary_values().filter(move |v| !filter(v))
440 }