apimock-routing 5.17.0

Routing model for apimock: rule sets, request matching, and read-only views for GUI tooling.
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
//! Tests for `Body::is_match`, `Body::validate`, and the TOML
//! deserialise surface that feeds them.
//!
//! # Coverage scope
//!
//! 5.6.0 added these tests for the same reason as
//! `headers::tests` — to fill a gap left when the routing crate's
//! original test surface stopped at `RuleOp` and `glob`. `Body`
//! evaluates request bodies against jsonpath-keyed conditions, with
//! several behavioural quirks (value coercion to string, multi-path
//! AND, missing-path → false) that are easy to regress without
//! direct tests.
//!
//! # On the path syntax
//!
//! `body.json` keys use the routing crate's dotted-path mini-syntax,
//! not standard JSONPath. The supported shapes are object keys
//! (`a.b.c`) and array indexing (`items.2.name`); the leading `$.`
//! and bracket-notation forms of canonical JSONPath are **not**
//! supported. See `apimock_routing::util::json::json_value_by_jsonpath`
//! for the full contract. These tests use the supported form.

use indexmap::IndexMap;
use std::collections::HashMap;

use hyper::Request;
use serde_json::{Value, json};

use super::Body;
use super::body_kind::BodyKind;
use crate::parsed_request::ParsedRequest;

// ---------------------------------------------------------------------
// Fixture helpers
// ---------------------------------------------------------------------

/// Parse a TOML fragment of the shape that appears under
/// `[when.request.body]` into a `Body` value.
fn parse_body(toml_text: &str) -> Body {
    // Wrap the fragment so the transparent shape can deserialise.
    let wrapped = format!("[body]\n{}", toml_text);
    #[derive(serde::Deserialize)]
    struct Wrapper {
        body: Body,
    }
    let w: Wrapper = toml::from_str(&wrapped).expect("parse body TOML");
    w.body
}

fn make_parsed_request(body_json: Option<Value>) -> ParsedRequest {
    let req = Request::builder()
        .method("POST")
        .uri("/test")
        .body(())
        .expect("build request");
    let (component_parts, _) = req.into_parts();
    ParsedRequest {
        url_path: "/test".to_owned(),
        component_parts,
        body_json,
    }
}

// ---------------------------------------------------------------------
// is_match — request shape
// ---------------------------------------------------------------------

#[test]
fn is_match_no_body_returns_false() {
    let body = parse_body(r#"json."x" = { value = "y" }"#);
    let req = make_parsed_request(None);
    assert!(!body.is_match(&req));
}

#[test]
fn is_match_no_json_kind_returns_false() {
    // A Body whose outer map has no Json key (constructed by hand —
    // TOML can't currently express this since BodyKind only has Json).
    let body = Body(HashMap::new());
    let req = make_parsed_request(Some(json!({"x": "y"})));
    assert!(!body.is_match(&req));
}

#[test]
fn is_match_empty_json_kind_returns_false() {
    // Json key exists but its inner map is empty.
    let mut outer = HashMap::new();
    outer.insert(BodyKind::Json, IndexMap::new());
    let body = Body(outer);
    let req = make_parsed_request(Some(json!({"x": "y"})));
    assert!(!body.is_match(&req));
}

// ---------------------------------------------------------------------
// is_match — operator coverage on jsonpath hits
// ---------------------------------------------------------------------

#[test]
fn is_match_jsonpath_hit_equal() {
    let body = parse_body(r#"json."action" = { op = "equal", value = "go" }"#);
    let req = make_parsed_request(Some(json!({"action": "go"})));
    assert!(body.is_match(&req));
}

#[test]
fn is_match_jsonpath_hit_starts_with() {
    let body = parse_body(r#"json."tag" = { op = "starts_with", value = "v1" }"#);
    let req = make_parsed_request(Some(json!({"tag": "v1.2.3"})));
    assert!(body.is_match(&req));
}

#[test]
fn is_match_jsonpath_hit_contains() {
    let body = parse_body(r#"json."message" = { op = "contains", value = "error" }"#);
    let req = make_parsed_request(Some(json!({"message": "an error occurred"})));
    assert!(body.is_match(&req));
}

#[test]
fn is_match_jsonpath_miss_returns_false() {
    let body = parse_body(r#"json."missing" = { value = "x" }"#);
    let req = make_parsed_request(Some(json!({"present": "x"})));
    assert!(!body.is_match(&req));
}

// ---------------------------------------------------------------------
// is_match — non-string JSON value coercion
// ---------------------------------------------------------------------

#[test]
fn is_match_jsonpath_value_number_coerced_to_string() {
    // The matcher stringifies non-String JSON values via `to_string()`
    // and compares with `RuleOp::is_match`. For Number, `to_string()`
    // produces e.g. "42".
    let body = parse_body(r#"json."count" = { value = "42" }"#);
    let req = make_parsed_request(Some(json!({"count": 42})));
    assert!(body.is_match(&req));
}

#[test]
fn is_match_jsonpath_value_object_coerced_to_string() {
    // `to_string()` on a JSON Object yields a compact JSON encoding
    // like `{"k":"v"}`. We pin that as the matcher's expectation so a
    // GUI rule writer knows what to compare against.
    let body = parse_body(r#"json."obj" = { value = "{\"k\":\"v\"}" }"#);
    let req = make_parsed_request(Some(json!({"obj": {"k": "v"}})));
    assert!(body.is_match(&req));
}

// ---------------------------------------------------------------------
// is_match — multi-condition AND
// ---------------------------------------------------------------------

#[test]
fn is_match_multiple_jsonpaths_all_match() {
    let body = parse_body(
        r#"json."action" = { value = "go" }
json."user" = { op = "starts_with", value = "alice" }"#,
    );
    let req = make_parsed_request(Some(json!({"action": "go", "user": "alice42"})));
    assert!(body.is_match(&req));
}

#[test]
fn is_match_multiple_jsonpaths_one_fails() {
    let body = parse_body(
        r#"json."action" = { value = "go" }
json."user" = { op = "starts_with", value = "alice" }"#,
    );
    let req = make_parsed_request(Some(json!({"action": "go", "user": "bob"})));
    assert!(!body.is_match(&req));
}

// ---------------------------------------------------------------------
// validate
// ---------------------------------------------------------------------

#[test]
fn validate_empty_outer_returns_false() {
    let body = Body(HashMap::new());
    assert!(!body.validate());
}

#[test]
fn validate_empty_inner_returns_false() {
    let mut outer = HashMap::new();
    outer.insert(BodyKind::Json, IndexMap::new());
    let body = Body(outer);
    assert!(!body.validate());
}

#[test]
fn validate_non_empty_returns_true() {
    let body = parse_body(r#"json."x" = { value = "y" }"#);
    assert!(body.validate());
}

// ---------------------------------------------------------------------
// TOML deserialise — surface confirmation
// ---------------------------------------------------------------------

#[test]
fn deserialize_simple_jsonpath() {
    let body = parse_body(r#"json."foo" = { value = "bar" }"#);
    let inner = body.0.get(&BodyKind::Json).expect("json kind present");
    assert!(inner.contains_key("foo"));
    assert_eq!(inner["foo"].value, "bar");
}

#[test]
fn deserialize_nested_jsonpath() {
    let body = parse_body(r#"json."user.address.city" = { value = "Tokyo" }"#);
    let inner = body.0.get(&BodyKind::Json).unwrap();
    assert!(inner.contains_key("user.address.city"));
}

#[test]
fn deserialize_multiple_jsonpaths() {
    let body = parse_body(
        r#"json."a" = { value = "1" }
json."b" = { op = "equal", value = "2" }
json."c" = { op = "starts_with", value = "3" }"#,
    );
    let inner = body.0.get(&BodyKind::Json).unwrap();
    assert_eq!(inner.len(), 3);
}

// ── RFC 010: null/Exists semantics ────────────────────────────────────

#[test]
fn exists_matches_null_value() {
    // A field present with value null satisfies Exists (RFC 010 §null semantics).
    let body = parse_body(r#"json."user_id" = { op = "exists", value = "" }"#);
    let req = make_parsed_request(Some(json!({"user_id": null})));
    assert!(
        body.is_match(&req),
        "Exists should match when field is present with null value"
    );
}

#[test]
fn absent_does_not_match_null_value() {
    // Absent requires the field to be truly missing, not present-but-null.
    let body = parse_body(r#"json."user_id" = { op = "absent", value = "" }"#);
    let req = make_parsed_request(Some(json!({"user_id": null})));
    assert!(
        !body.is_match(&req),
        "Absent should NOT match when field is present with null value"
    );
}

#[test]
fn absent_matches_truly_missing_field() {
    let body = parse_body(r#"json."missing" = { op = "absent", value = "" }"#);
    let req = make_parsed_request(Some(json!({"present": 1})));
    assert!(
        body.is_match(&req),
        "Absent should match when field is truly absent"
    );
}

#[test]
fn exists_does_not_match_missing_field() {
    let body = parse_body(r#"json."missing" = { op = "exists", value = "" }"#);
    let req = make_parsed_request(Some(json!({"other": 1})));
    assert!(
        !body.is_match(&req),
        "Exists should not match a missing field"
    );
}

// ── RFC 021: negated body string operators ────────────────────────────

#[test]
fn not_contains_matches_when_absent() {
    let body = parse_body(r#"json."status" = { op = "not_contains", value = "error" }"#);
    assert!(body.is_match(&make_parsed_request(Some(json!({"status": "success"})))));
    assert!(!body.is_match(&make_parsed_request(Some(json!({"status": "error_code"})))));
}

#[test]
fn not_starts_with_matches() {
    let body = parse_body(r#"json."role" = { op = "not_starts_with", value = "admin" }"#);
    assert!(body.is_match(&make_parsed_request(Some(json!({"role": "viewer"})))));
    assert!(!body.is_match(&make_parsed_request(Some(json!({"role": "admin_user"})))));
}

#[test]
fn not_ends_with_matches() {
    let body = parse_body(r#"json."id" = { op = "not_ends_with", value = "_tmp" }"#);
    assert!(body.is_match(&make_parsed_request(Some(json!({"id": "abc123"})))));
    assert!(!body.is_match(&make_parsed_request(Some(json!({"id": "abc_tmp"})))));
}

#[test]
fn not_regex_matches() {
    // Use a simple anchored pattern without backslash escaping.
    let body = parse_body(r#"json."role" = { op = "not_regex", value = "^admin" }"#);
    assert!(body.is_match(&make_parsed_request(Some(json!({"role": "viewer"})))));
    assert!(!body.is_match(&make_parsed_request(Some(json!({"role": "admin_user"})))));
}

// ── RFC 022: MapHasKey / MapDoesNotHaveKey ────────────────────────────

#[test]
fn map_has_key_matches_when_key_present() {
    let body = parse_body(r#"json."meta" = { op = "map_has_key", value = "created_at" }"#);
    let req = make_parsed_request(Some(json!({"meta": {"created_at": 1234, "other": "x"}})));
    assert!(body.is_match(&req));
}

#[test]
fn map_has_key_no_match_when_key_absent() {
    let body = parse_body(r#"json."meta" = { op = "map_has_key", value = "admin_flag" }"#);
    let req = make_parsed_request(Some(json!({"meta": {"created_at": 1234}})));
    assert!(!body.is_match(&req));
}

#[test]
fn map_has_key_no_match_when_value_not_object() {
    let body = parse_body(r#"json."meta" = { op = "map_has_key", value = "key" }"#);
    let req = make_parsed_request(Some(json!({"meta": "not_an_object"})));
    assert!(!body.is_match(&req));
}

#[test]
fn map_does_not_have_key_matches_when_key_absent() {
    let body =
        parse_body(r#"json."config" = { op = "map_does_not_have_key", value = "override" }"#);
    let req = make_parsed_request(Some(json!({"config": {"debug": true}})));
    assert!(body.is_match(&req));
}

#[test]
fn map_does_not_have_key_no_match_when_key_present() {
    let body =
        parse_body(r#"json."config" = { op = "map_does_not_have_key", value = "override" }"#);
    let req = make_parsed_request(Some(json!({"config": {"override": true, "debug": true}})));
    assert!(!body.is_match(&req));
}

#[test]
fn map_does_not_have_key_no_match_when_not_object() {
    let body = parse_body(r#"json."config" = { op = "map_does_not_have_key", value = "key" }"#);
    let req = make_parsed_request(Some(json!({"config": [1, 2, 3]})));
    assert!(!body.is_match(&req));
}

// ── RFC 028: StructuralContains ───────────────────────────────────────

#[test]
fn structural_contains_matches_superset_element() {
    let body = parse_body(
        r#"json."items" = { op = "structural_contains", value = "{\"type\":\"admin\"}" }"#,
    );
    let req = make_parsed_request(Some(json!({
        "items": [{"type":"user","id":1},{"type":"admin","id":2,"extra":"data"}]
    })));
    assert!(
        body.is_match(&req),
        "array contains an element that is a superset of needle"
    );
}

#[test]
fn structural_contains_no_match_when_no_superset() {
    let body = parse_body(
        r#"json."items" = { op = "structural_contains", value = "{\"type\":\"admin\"}" }"#,
    );
    let req = make_parsed_request(Some(json!({
        "items": [{"type":"user","id":1},{"type":"viewer","id":2}]
    })));
    assert!(!body.is_match(&req), "no element is a superset of needle");
}

#[test]
fn structural_contains_nested_object_match() {
    let body = parse_body(
        r#"json."users" = { op = "structural_contains", value = "{\"role\":{\"level\":3}}" }"#,
    );
    let req = make_parsed_request(Some(json!({
        "users": [
            {"name":"alice","role":{"level":1}},
            {"name":"bob","role":{"level":3,"dept":"eng"}}
        ]
    })));
    assert!(body.is_match(&req), "nested object subset match");
}

#[test]
fn structural_contains_scalar_needle_falls_back_to_equality() {
    // Non-object needle behaves like ArrayContains.
    let body = parse_body(r#"json."tags" = { op = "structural_contains", value = "\"admin\"" }"#);
    assert!(body.is_match(&make_parsed_request(Some(json!({"tags":["user","admin"]})))));
    assert!(!body.is_match(&make_parsed_request(Some(
        json!({"tags":["user","viewer"]})
    ))));
}

#[test]
fn structural_contains_no_match_when_not_array() {
    let body = parse_body(r#"json."items" = { op = "structural_contains", value = "{}" }"#);
    let req = make_parsed_request(Some(json!({"items":"not_an_array"})));
    assert!(!body.is_match(&req));
}