Debian Codegraph @

tests/integration/test_helper.rs

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