stubr 0.6.2

Wiremock implemented in Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
use std::hash::{Hash, Hasher};

use itertools::Itertools;
use json_value_merge::Merge;
use serde_json::{json, Value};

use crate::{
    gen::string::StringRndGenerator,
    model::request::{body::BodyMatcherStub, RequestStub},
    verify::mapping::jsonpath::JsonGeneratorIterator,
};

use super::super::jsonpath::JsonPathGenerator;

impl From<&RequestStub> for Vec<u8> {
    fn from(stub: &RequestStub) -> Self {
        stub.body_patterns
            .iter()
            .map(PartialBody::from)
            .find(|it| !it.is_partial())
            .and_then(PartialBody::to_bytes)
            .unwrap_or_else(|| {
                let merged = stub
                    .body_patterns
                    .iter()
                    .map(PartialBody::from)
                    .unique()
                    .fold(Value::default(), |mut acc, it| {
                        if let Some(value) = it.to_partial_value() {
                            acc.merge(value);
                        }
                        acc
                    });
                serde_json::to_vec::<Value>(&merged).unwrap()
            })
    }
}

#[derive(Default, Eq, Clone)]
struct PartialBody {
    path: Option<String>,
    bytes: Option<Vec<u8>>,
    value: Option<Value>,
}

lazy_static! {
    pub static ref EMPTY_JSON_OBJECT: Value = serde_json::json!({});
}

impl PartialBody {
    fn is_partial(&self) -> bool {
        self.path.is_some()
    }

    #[allow(clippy::wrong_self_convention)]
    fn to_bytes(self) -> Option<Vec<u8>> {
        if !self.is_partial() {
            self.bytes
                .to_owned()
                .or_else(|| self.to_value().as_ref().and_then(|it| serde_json::to_vec::<Value>(it).ok()))
        } else {
            None
        }
    }

    #[allow(clippy::wrong_self_convention)]
    fn to_value(self) -> Option<Value> {
        if !self.is_partial() {
            self.value
        } else {
            None
        }
    }

    fn to_partial_value(&self) -> Option<Value> {
        self.path
            .as_deref()
            .and_then(|path| JsonPathGenerator(path).next(self.value.clone().unwrap_or_else(|| json!({}))))
    }
}

impl From<&BodyMatcherStub> for PartialBody {
    fn from(stub: &BodyMatcherStub) -> Self {
        if let Some(binary_equal_to) = stub.binary_equal_to.as_ref() {
            use base64::Engine as _;
            base64::prelude::BASE64_STANDARD
                .decode(binary_equal_to)
                .unwrap_or_else(|_| panic!("'{binary_equal_to}' must be Base64 encoded"))
                .into()
        } else if let Some(expression) = stub.expression.as_ref() {
            if let Some(equal_to_json) = stub.equal_to_json.as_ref() {
                Self {
                    path: Some(expression.to_string()),
                    value: Some(equal_to_json.to_owned()),
                    ..Default::default()
                }
            } else if let Some(contains) = stub.contains.as_ref() {
                let value = StringRndGenerator::generate_string_containing(contains.to_string());
                Self {
                    path: Some(expression.to_string()),
                    value: Some(Value::String(value)),
                    ..Default::default()
                }
            } else {
                Self::default()
            }
        } else if let Some(eq) = stub.equal_to_json.as_ref() {
            eq.to_owned().into()
        } else if let Some(json_path) = stub.matches_json_path.as_ref() {
            Self {
                path: Some(json_path.to_owned()),
                ..Default::default()
            }
        } else {
            Self::default()
        }
    }
}

impl From<Vec<u8>> for PartialBody {
    fn from(bytes: Vec<u8>) -> Self {
        Self {
            bytes: Some(bytes),
            ..Default::default()
        }
    }
}

impl From<Value> for PartialBody {
    fn from(value: Value) -> Self {
        Self {
            value: Some(value),
            ..Default::default()
        }
    }
}

impl PartialEq for PartialBody {
    fn eq(&self, other: &Self) -> bool {
        self.path.eq(&other.path)
    }
}

impl Hash for PartialBody {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.path.hash(state);
    }
}

#[cfg(test)]
mod verify_body_tests {
    use serde_json::{json, Value};

    use super::*;

    mod equal_to_json {
        use super::*;

        #[test]
        fn equal_to_json_should_generate_strictly_equal() {
            let json = json!({"name": "john", "age": 42});
            let stub = BodyMatcherStub {
                equal_to_json: Some(json.clone()),
                ..Default::default()
            };
            assert_eq!(PartialBody::from(&stub).to_value().unwrap(), json);
        }
    }

    mod binary_equal_to {
        use super::*;

        #[test]
        fn binary_equal_to_should_generate_strictly_equal() {
            let stub = BodyMatcherStub {
                binary_equal_to: Some(String::from("AQID")),
                ..Default::default()
            };
            assert_eq!(PartialBody::from(&stub).to_bytes().unwrap(), vec![1, 2, 3]);
        }

        #[should_panic(expected = "'!!!' must be Base64 encoded")]
        #[test]
        fn binary_equal_to_should_fail_when_not_base64() {
            let _ = PartialBody::from(&BodyMatcherStub {
                binary_equal_to: Some(String::from("!!!")),
                ..Default::default()
            });
        }
    }

    mod expression {
        use super::*;

        #[test]
        fn expression_contains_should_generate_containing() {
            let by_contains = BodyMatcherStub {
                expression: Some(String::from("$.name")),
                contains: Some(String::from("a")),
                ..Default::default()
            };
            let stub = RequestStub {
                body_patterns: vec![by_contains],
                ..Default::default()
            };
            let body = serde_json::from_slice::<Value>(&Vec::<u8>::from(&stub)).unwrap();
            let name = body.as_object().unwrap().get("name").unwrap();
            assert!(name.as_str().unwrap().contains('a'));
        }

        #[test]
        fn expression_equal_to_json_should_generate_strictly_equal() {
            let owner = json!({"name": "john", "age": 42});
            let by_eq = BodyMatcherStub {
                expression: Some(String::from("$.owner")),
                equal_to_json: Some(owner.clone()),
                ..Default::default()
            };
            let stub = RequestStub {
                body_patterns: vec![by_eq],
                ..Default::default()
            };
            let body = serde_json::from_slice::<Value>(&Vec::<u8>::from(&stub)).unwrap();
            assert_eq!(body, json!({ "owner": owner }));
        }
    }

    mod many_expression {
        use super::*;

        #[test]
        fn many_expression_equal_to_json_should_generate_combined() {
            let alice = json!({"name": "alice"});
            let sender = BodyMatcherStub {
                expression: Some(String::from("$.sender")),
                equal_to_json: Some(alice.clone()),
                ..Default::default()
            };
            let bob = json!({"name": "bob"});
            let receiver = BodyMatcherStub {
                expression: Some(String::from("$.receiver")),
                equal_to_json: Some(bob.clone()),
                ..Default::default()
            };
            let stub = RequestStub {
                body_patterns: vec![sender, receiver],
                ..Default::default()
            };
            let body = serde_json::from_slice::<Value>(&Vec::<u8>::from(&stub)).unwrap();
            assert_eq!(body, json!({"sender": alice, "receiver": bob}));
        }

        #[test]
        fn many_expression_equal_to_json_should_merge_paths() {
            let alice = json!({"name": "alice"});
            let alice_stub = BodyMatcherStub {
                expression: Some(String::from("$.person.alice")),
                equal_to_json: Some(alice.clone()),
                ..Default::default()
            };
            let bob = json!({"name": "bob"});
            let bob_stub = BodyMatcherStub {
                expression: Some(String::from("$.person.bob")),
                equal_to_json: Some(bob.clone()),
                ..Default::default()
            };
            let stub = RequestStub {
                body_patterns: vec![alice_stub, bob_stub],
                ..Default::default()
            };
            let body = serde_json::from_slice::<Value>(&Vec::<u8>::from(&stub)).unwrap();
            assert_eq!(body, json!({"person": {"alice": alice, "bob": bob}}));
        }

        #[test]
        fn many_expression_equal_to_json_and_contains_should_generate_combined() {
            let alice = json!({"name": "alice"});
            let sender = BodyMatcherStub {
                expression: Some(String::from("$.sender")),
                equal_to_json: Some(alice.clone()),
                ..Default::default()
            };
            let receiver = BodyMatcherStub {
                expression: Some(String::from("$.receiver")),
                contains: Some(String::from("b")),
                ..Default::default()
            };
            let stub = RequestStub {
                body_patterns: vec![sender, receiver],
                ..Default::default()
            };
            let body = serde_json::from_slice::<Value>(&Vec::<u8>::from(&stub)).unwrap();
            let body = body.as_object().unwrap();
            assert_eq!(body.get("sender").unwrap(), &alice);
            assert!(body.get("receiver").unwrap().as_str().unwrap().contains('b'));
        }

        #[test]
        fn many_contains_should_generate_combined() {
            let sender = BodyMatcherStub {
                expression: Some(String::from("$.sender")),
                contains: Some(String::from("s")),
                ..Default::default()
            };
            let receiver = BodyMatcherStub {
                expression: Some(String::from("$.receiver")),
                contains: Some(String::from("r")),
                ..Default::default()
            };
            let stub = RequestStub {
                body_patterns: vec![sender, receiver],
                ..Default::default()
            };
            let body = serde_json::from_slice::<Value>(&Vec::<u8>::from(&stub)).unwrap();
            let body = body.as_object().unwrap();
            assert!(body.get("sender").unwrap().as_str().unwrap().contains('s'));
            assert!(body.get("receiver").unwrap().as_str().unwrap().contains('r'));
        }
    }

    mod json_path {
        use super::*;

        #[test]
        fn matches_json_path_should_generate_containing_empty_json() {
            let jsonpath = BodyMatcherStub {
                matches_json_path: Some(String::from("$.name")),
                ..Default::default()
            };
            let stub = RequestStub {
                body_patterns: vec![jsonpath],
                ..Default::default()
            };
            let body = serde_json::from_slice::<Value>(&Vec::<u8>::from(&stub)).unwrap();
            assert_eq!(body, json!({"name": {}}));
        }

        #[test]
        fn matches_json_path_and_expression_should_generate_valid_json() {
            let owner = json!({"name": "john", "age": 42});
            let by_jsonpath = BodyMatcherStub {
                matches_json_path: Some(String::from("$.other")),
                ..Default::default()
            };
            let by_eq = BodyMatcherStub {
                expression: Some(String::from("$.owner")),
                equal_to_json: Some(owner.clone()),
                ..Default::default()
            };
            let stub = RequestStub {
                body_patterns: vec![by_jsonpath, by_eq],
                ..Default::default()
            };
            let body = serde_json::from_slice::<Value>(&Vec::<u8>::from(&stub)).unwrap();
            assert_eq!(body, json!({"other": {}, "owner": owner}));
        }
    }

    mod json_path_filtering {
        use super::*;

        mod eq {
            use super::*;

            #[test]
            fn matches_json_path_eq_should_generate_containing_filters() {
                let jsonpath_alice = BodyMatcherStub {
                    matches_json_path: Some(String::from("$.users[?(@.name == 'alice')]")),
                    ..Default::default()
                };
                let stub = RequestStub {
                    body_patterns: vec![jsonpath_alice],
                    ..Default::default()
                };
                let body = serde_json::from_slice::<Value>(&Vec::<u8>::from(&stub)).unwrap();
                assert_eq!(body, json!({"users": [{"name": "alice"}]}));
            }

            #[test]
            fn matches_many_json_path_eq_should_generate_containing_filters() {
                let jsonpath_alice = BodyMatcherStub {
                    matches_json_path: Some(String::from("$.users[?(@.name == 'alice')]")),
                    ..Default::default()
                };
                let jsonpath_bob = BodyMatcherStub {
                    matches_json_path: Some(String::from("$.users[?(@.name == 'bob')]")),
                    ..Default::default()
                };
                let stub = RequestStub {
                    body_patterns: vec![jsonpath_alice, jsonpath_bob],
                    ..Default::default()
                };
                let body = serde_json::from_slice::<Value>(&Vec::<u8>::from(&stub)).unwrap();
                assert_eq!(body, json!({"users": [{"name": "alice"}, {"name": "bob"}]}));
            }
        }
    }

    mod precedence {
        use super::*;

        #[test]
        fn binary_equal_to_should_have_precedence_over_equal_to_json() {
            let priority = BodyMatcherStub {
                binary_equal_to: Some(String::from("AQID")),
                ..Default::default()
            };
            let other = BodyMatcherStub {
                equal_to_json: Some(json!({"name": "jdoe"})),
                ..Default::default()
            };
            let stub = RequestStub {
                body_patterns: vec![priority, other],
                ..Default::default()
            };
            assert_eq!(Vec::<u8>::from(&stub).to_vec(), vec![1, 2, 3]);
        }

        #[test]
        fn binary_equal_to_should_have_precedence_over_expression() {
            let priority = BodyMatcherStub {
                binary_equal_to: Some(String::from("AQID")),
                ..Default::default()
            };
            let other = BodyMatcherStub {
                expression: Some(String::from("$.owner")),
                equal_to_json: Some(json!({"name": "jdoe"})),
                ..Default::default()
            };
            let stub = RequestStub {
                body_patterns: vec![priority, other],
                ..Default::default()
            };
            assert_eq!(Vec::<u8>::from(&stub).to_vec(), vec![1, 2, 3]);
        }

        #[test]
        fn equal_to_json_should_have_precedence_over_expression() {
            let jdoe = json!({"name": "jdoe"});
            let priority = BodyMatcherStub {
                equal_to_json: Some(jdoe.clone()),
                ..Default::default()
            };
            let other = BodyMatcherStub {
                expression: Some(String::from("$.owner")),
                equal_to_json: Some(jdoe.clone()),
                ..Default::default()
            };
            let stub = RequestStub {
                body_patterns: vec![priority, other],
                ..Default::default()
            };
            let body = serde_json::from_slice::<Value>(&Vec::<u8>::from(&stub)).unwrap();
            assert_eq!(body, jdoe);
        }

        #[test]
        fn expression_equal_to_json_should_have_precedence_over_expression_contains() {
            let jdoe = json!({"name": "jdoe"});
            let priority = BodyMatcherStub {
                expression: Some(String::from("$.owner")),
                equal_to_json: Some(jdoe.clone()),
                ..Default::default()
            };
            let other = BodyMatcherStub {
                expression: Some(String::from("$.owner")),
                contains: Some(String::from("a")),
                ..Default::default()
            };
            let stub = RequestStub {
                body_patterns: vec![priority, other],
                ..Default::default()
            };
            let body = serde_json::from_slice::<Value>(&Vec::<u8>::from(&stub)).unwrap();
            assert_eq!(body, json!({ "owner": jdoe }));
        }

        #[test]
        fn expression_should_have_precedence_over_matches_json_path() {
            let jdoe = json!({"name": "jdoe"});
            let priority = BodyMatcherStub {
                expression: Some(String::from("$.owner")),
                equal_to_json: Some(jdoe.clone()),
                ..Default::default()
            };
            let other = BodyMatcherStub {
                matches_json_path: Some(String::from("$.owner")),
                ..Default::default()
            };
            let stub = RequestStub {
                body_patterns: vec![priority, other],
                ..Default::default()
            };
            let body = serde_json::from_slice::<Value>(&Vec::<u8>::from(&stub)).unwrap();
            assert_eq!(body, json!({ "owner": jdoe }));
        }
    }
}