momus-core 0.7.28

Generic API test harness — AST types, assertion evaluation, plan runner, template resolution
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
/// Composable assertion nodes for API response validation.
///
/// Assertions form a tree: `AllOf`, `AnyOf`, and `Not` combine sub-assertions,
/// while leaf nodes check specific response properties.
///
/// # Examples
///
/// ```ignore
/// // Status is 200 AND body is a Bundle
/// Assertion::AllOf(vec![
///     Assertion::Status(200),
///     Assertion::JsonPath("$.resourceType", JsonPredicate::Eq(json!("Bundle"))),
/// ])
///
/// // Either 200 or 304 (conditional read)
/// Assertion::AnyOf(vec![
///     Assertion::Status(200),
///     Assertion::Status(304),
/// ])
/// ```
use serde::{Deserialize, Serialize};

// ---------------------------------------------------------------------------
// Top-level assertion tree
// ---------------------------------------------------------------------------

/// A composable response assertion.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Assertion {
    // -- Combinators --------------------------------------------------------
    /// All sub-assertions must pass (logical AND).
    AllOf(Vec<Assertion>),
    /// At least one sub-assertion must pass (logical OR).
    AnyOf(Vec<Assertion>),
    /// The sub-assertion must NOT pass (logical NOT).
    Not(Box<Assertion>),

    // -- HTTP-level assertions ---------------------------------------------
    /// Expected HTTP status code.
    Status(u16),
    /// Status code must be in this set.
    StatusIn(Vec<u16>),

    /// A response header must be present and match a predicate.
    Header {
        name: String,
        predicate: ValuePredicate,
    },

    /// Response body size in bytes.
    BodyLength(BodyLengthPredicate),

    // -- JSON body assertions -----------------------------------------------
    /// Assert a JSONPath expression against the response body.
    JsonPath {
        path: String,
        predicate: JsonPredicate,
    },

    /// Validate the response body against a JSON Schema.
    Schema {
        /// Inline JSON Schema.
        schema: serde_json::Value,
    },

    /// Response body must be valid JSON.
    ValidJson,

    // -- Content-type assertions -------------------------------------------
    /// Response Content-Type must match (substring match).
    ContentType(String),

    // -- Performance assertions --------------------------------------------
    /// Response time must be at most `max_millis` milliseconds.
    ResponseTime(u64),
}

// ---------------------------------------------------------------------------
// Predicates
// ---------------------------------------------------------------------------

/// Predicates for scalar values (headers, simple fields).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ValuePredicate {
    /// Exact string match.
    Eq(String),
    /// Substring / regex match.
    Contains(String),
    /// Regex match.
    Regex(String),
    /// Value is present (header exists).
    Present,
    /// Value is absent (header does not exist).
    Absent,
}

/// Predicates for JSONPath query results.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum JsonPredicate {
    /// The path must exist (returns at least one node).
    Exists,
    /// The path must NOT exist (returns zero nodes).
    NotExists,
    /// The first result must equal this value.
    Eq(serde_json::Value),
    /// The first result must NOT equal this value.
    NotEq(serde_json::Value),
    /// The first result (if numeric) must satisfy a comparison.
    Cmp { op: CmpOp, value: serde_json::Value },
    /// The result array must have this length.
    Length(LengthPredicate),
    /// Every result must satisfy this sub-predicate.
    Every(Box<JsonPredicate>),
    /// At least one result must satisfy this sub-predicate.
    Some(Box<JsonPredicate>),
    /// The result count must satisfy this.
    Count(CountPredicate),
    /// Match the result against a JSON Schema.
    Schema(serde_json::Value),
}

/// Comparison operators for numeric values.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum CmpOp {
    Gt,
    Lt,
    Ge,
    Le,
}

/// Body length predicates.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum BodyLengthPredicate {
    /// Exact byte count.
    Eq(usize),
    /// Minimum byte count.
    Min(usize),
    /// Maximum byte count.
    Max(usize),
    /// Inclusive range.
    Range { min: usize, max: usize },
}

/// Array length predicates.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum LengthPredicate {
    Eq(usize),
    Min(usize),
    Max(usize),
    Range { min: usize, max: usize },
}

/// Count predicates (for JSONPath result counts).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum CountPredicate {
    Eq(usize),
    Min(usize),
    Max(usize),
    Range { min: usize, max: usize },
}

// ---------------------------------------------------------------------------
// Convenience constructors
// ---------------------------------------------------------------------------

impl Assertion {
    /// Assert the response status is exactly `code`.
    pub fn status(code: u16) -> Self {
        Assertion::Status(code)
    }

    /// Assert the response status is one of the given codes.
    pub fn status_in(codes: Vec<u16>) -> Self {
        Assertion::StatusIn(codes)
    }

    /// Assert a JSONPath expression exists in the response body.
    pub fn json_path_exists(path: impl Into<String>) -> Self {
        Assertion::JsonPath {
            path: path.into(),
            predicate: JsonPredicate::Exists,
        }
    }

    /// Assert a JSONPath expression equals a value.
    pub fn json_path_eq(path: impl Into<String>, value: serde_json::Value) -> Self {
        Assertion::JsonPath {
            path: path.into(),
            predicate: JsonPredicate::Eq(value),
        }
    }

    /// Assert a response header matches a predicate.
    pub fn header(name: impl Into<String>, predicate: ValuePredicate) -> Self {
        Assertion::Header {
            name: name.into(),
            predicate,
        }
    }

    /// Assert the response Content-Type matches.
    pub fn content_type(ct: impl Into<String>) -> Self {
        Assertion::ContentType(ct.into())
    }

    /// Assert the response body is valid JSON.
    pub fn valid_json() -> Self {
        Assertion::ValidJson
    }

    /// Assert the response body matches a JSON Schema.
    pub fn schema(schema: serde_json::Value) -> Self {
        Assertion::Schema { schema }
    }

    /// Assert the response time is at most `max_millis` milliseconds.
    pub fn response_time(max_millis: u64) -> Self {
        Assertion::ResponseTime(max_millis)
    }
}

// ---------------------------------------------------------------------------
// Assertion evaluation result
// ---------------------------------------------------------------------------

/// The result of evaluating a single assertion.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AssertionResult {
    /// A human-readable description of what was checked.
    pub description: String,
    /// Whether the assertion passed.
    pub passed: bool,
    /// If failed, why.
    pub message: Option<String>,
    /// Nested sub-results (for AllOf/AnyOf/Not).
    #[serde(default)]
    pub children: Vec<AssertionResult>,
}

impl AssertionResult {
    pub fn pass(description: impl Into<String>) -> Self {
        Self {
            description: description.into(),
            passed: true,
            message: None,
            children: vec![],
        }
    }

    pub fn fail(description: impl Into<String>, message: impl Into<String>) -> Self {
        Self {
            description: description.into(),
            passed: false,
            message: Some(message.into()),
            children: vec![],
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn status_assertion_constructors() {
        let a = Assertion::status(200);
        assert_eq!(a, Assertion::Status(200));

        let b = Assertion::status_in(vec![200, 304]);
        assert_eq!(b, Assertion::StatusIn(vec![200, 304]));
    }

    #[test]
    fn json_path_constructors() {
        let a = Assertion::json_path_exists("$.resourceType");
        assert_eq!(
            a,
            Assertion::JsonPath {
                path: "$.resourceType".into(),
                predicate: JsonPredicate::Exists,
            }
        );

        let b = Assertion::json_path_eq("$.total", serde_json::json!(42));
        assert_eq!(
            b,
            Assertion::JsonPath {
                path: "$.total".into(),
                predicate: JsonPredicate::Eq(serde_json::json!(42)),
            }
        );
    }

    #[test]
    fn assertion_result_pass() {
        let r = AssertionResult::pass("status is 200");
        assert!(r.passed);
        assert!(r.message.is_none());
    }

    #[test]
    fn assertion_result_fail() {
        let r = AssertionResult::fail("status is 200", "got 404");
        assert!(!r.passed);
        assert_eq!(r.message.unwrap(), "got 404");
    }

    #[test]
    fn assertion_result_with_children() {
        let r = AssertionResult {
            description: "all of".into(),
            passed: false,
            message: Some("failed: status is 200".into()),
            children: vec![AssertionResult::fail("status is 200", "got 404")],
        };
        assert!(!r.passed);
        assert_eq!(r.children.len(), 1);
        assert!(!r.children[0].passed);
    }

    #[test]
    fn test_assertion_serialization_roundtrip() {
        let assertions = vec![
            Assertion::Status(200),
            Assertion::StatusIn(vec![200, 304]),
            Assertion::Header {
                name: "content-type".into(),
                predicate: ValuePredicate::Contains("json".into()),
            },
            Assertion::BodyLength(BodyLengthPredicate::Min(10)),
            Assertion::JsonPath {
                path: "$.resourceType".into(),
                predicate: JsonPredicate::Eq(serde_json::json!("Patient")),
            },
            Assertion::Schema {
                schema: serde_json::json!({"type": "object"}),
            },
            Assertion::ValidJson,
            Assertion::ContentType("json".into()),
            Assertion::ResponseTime(500),
            Assertion::AllOf(vec![Assertion::Status(200), Assertion::ValidJson]),
            Assertion::AnyOf(vec![Assertion::Status(200), Assertion::Status(304)]),
            Assertion::Not(Box::new(Assertion::Status(404))),
        ];

        for assertion in &assertions {
            let json = serde_json::to_string(assertion).unwrap();
            let deserialized: Assertion = serde_json::from_str(&json).unwrap();
            assert_eq!(
                *assertion, deserialized,
                "round-trip failed for {:?}",
                assertion
            );
        }
    }

    #[test]
    fn test_value_predicate_serialization_roundtrip() {
        let predicates = vec![
            ValuePredicate::Eq("value".into()),
            ValuePredicate::Contains("sub".into()),
            ValuePredicate::Regex("^pattern$".into()),
            ValuePredicate::Present,
            ValuePredicate::Absent,
        ];

        for predicate in &predicates {
            let json = serde_json::to_string(predicate).unwrap();
            let deserialized: ValuePredicate = serde_json::from_str(&json).unwrap();
            assert_eq!(*predicate, deserialized);
        }
    }

    #[test]
    fn test_json_predicate_serialization_roundtrip() {
        let predicates = vec![
            JsonPredicate::Exists,
            JsonPredicate::NotExists,
            JsonPredicate::Eq(serde_json::json!("test")),
            JsonPredicate::NotEq(serde_json::json!(42)),
            JsonPredicate::Cmp {
                op: CmpOp::Gt,
                value: serde_json::json!(10),
            },
            JsonPredicate::Length(LengthPredicate::Eq(3)),
            JsonPredicate::Every(Box::new(JsonPredicate::Exists)),
            JsonPredicate::Some(Box::new(JsonPredicate::Eq(serde_json::json!(1)))),
            JsonPredicate::Count(CountPredicate::Min(1)),
            JsonPredicate::Schema(serde_json::json!({"type": "object"})),
        ];

        for predicate in &predicates {
            let json = serde_json::to_string(predicate).unwrap();
            let deserialized: JsonPredicate = serde_json::from_str(&json).unwrap();
            assert_eq!(*predicate, deserialized);
        }
    }

    #[test]
    fn test_predicate_serialization_roundtrip() {
        let predicates: Vec<BodyLengthPredicate> = vec![
            BodyLengthPredicate::Eq(100),
            BodyLengthPredicate::Min(10),
            BodyLengthPredicate::Max(1000),
            BodyLengthPredicate::Range { min: 10, max: 100 },
        ];
        for pred in &predicates {
            let json = serde_json::to_string(pred).unwrap();
            let deserialized: BodyLengthPredicate = serde_json::from_str(&json).unwrap();
            assert_eq!(*pred, deserialized);
        }

        let length_preds: Vec<LengthPredicate> = vec![
            LengthPredicate::Eq(5),
            LengthPredicate::Min(1),
            LengthPredicate::Max(10),
            LengthPredicate::Range { min: 1, max: 10 },
        ];
        for pred in &length_preds {
            let json = serde_json::to_string(pred).unwrap();
            let deserialized: LengthPredicate = serde_json::from_str(&json).unwrap();
            assert_eq!(*pred, deserialized);
        }

        let count_preds: Vec<CountPredicate> = vec![
            CountPredicate::Eq(3),
            CountPredicate::Min(0),
            CountPredicate::Max(100),
            CountPredicate::Range { min: 1, max: 5 },
        ];
        for pred in &count_preds {
            let json = serde_json::to_string(pred).unwrap();
            let deserialized: CountPredicate = serde_json::from_str(&json).unwrap();
            assert_eq!(*pred, deserialized);
        }
    }

    #[test]
    fn test_assertion_result_serialization_roundtrip() {
        let result = AssertionResult {
            description: "all of".into(),
            passed: false,
            message: Some("failed: status is 200".into()),
            children: vec![AssertionResult::fail("status is 200", "got 404")],
        };
        let json = serde_json::to_string(&result).unwrap();
        let deserialized: AssertionResult = serde_json::from_str(&json).unwrap();
        assert_eq!(deserialized.description, result.description);
        assert_eq!(deserialized.passed, result.passed);
        assert_eq!(deserialized.children.len(), result.children.len());
    }
}