rift-mock-core 0.25.0

Rift core engine: imposter lifecycle, matching, behaviors, scripting and flow-state — usable in-process without the CLI or admin server.
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
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
//! Server-side verification (issue #494): count — and optionally return — recorded requests
//! matching a predicate set, with an optional closest non-match diff.
//!
//! This reuses the one true predicate evaluator (`stub_matches_inner`) and the recorded-request
//! store rather than reimplementing matching per SDK, so `verify(match, times(n))` in every SDK
//! can defer to the engine instead of shipping the whole journal over the wire and re-evaluating
//! predicates client-side (where `xpath`/`inject` are impractical).

use super::Imposter;
use crate::imposter::predicates::stub_matches_inner;
use crate::imposter::types::{Predicate, PredicateOperation, RecordedRequest};
use serde::{Deserialize, Serialize};
use serde_json::{Map, Value, json};

/// Verification request — the body of `POST /imposters/{port}/verify`. `predicates` are AND'd
/// (the same implicit-AND the request hot path applies to a stub's predicates).
#[derive(Debug, Clone, Default, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct VerifyOptions {
    #[serde(default)]
    pub predicates: Vec<Predicate>,
    /// Scope the count to one space, resolved via the imposter's `flow_id_source` — the same
    /// scoping `GET /savedRequests?match=flow_id=…` applies.
    #[serde(default)]
    pub flow_id: Option<String>,
    /// Return the matching requests, not just the count.
    #[serde(default)]
    pub include_requests: bool,
    /// Return the best-scoring non-match with per-clause failure details (for diff rendering).
    #[serde(default)]
    pub include_closest: bool,
}

/// Verification result. `requests`/`closest` are present only when the corresponding option was set.
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct VerifyOutcome {
    /// Recorded requests (in flow scope) matching every predicate.
    pub matched: usize,
    /// Total recorded requests in flow scope, matched or not.
    pub total: usize,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub requests: Option<Vec<RecordedRequest>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub closest: Option<ClosestMatch>,
}

/// The non-matching request that satisfied the most predicate clauses, with the clauses it failed.
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ClosestMatch {
    pub request: RecordedRequest,
    pub failed_predicates: Vec<FailedPredicate>,
}

/// One predicate the closest request failed, paired with the request's actual value(s) for the
/// fields that predicate references — the raw material for a readable diff.
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct FailedPredicate {
    pub predicate: Predicate,
    pub actual: Value,
}

impl Imposter {
    /// Count (and optionally return) recorded requests matching every predicate, scoped to
    /// `flow_id` when set. Reuses the live predicate evaluator and recorded-request store — no new
    /// state. An `inject` predicate that fails propagates as `Err` (the issue #440 contract the
    /// request hot path also honors) rather than being silently counted as a non-match.
    ///
    /// An `inject` predicate runs with the imposter's own script access, so this is only for a
    /// caller that wrote the imposter or is trusted at least as far; a door that takes predicates
    /// from someone else uses [`Self::verify_from`] (review of #1645).
    pub fn verify(&self, opts: &VerifyOptions) -> anyhow::Result<VerifyOutcome> {
        let files = self.script_file_access();
        self.verify_with(opts, &files)
    }

    /// [`Self::verify`] for predicates a door supplies (review of #1645): an `inject` predicate's
    /// `require()` gets what both the imposter's access and `door` allow
    /// ([`ScriptFileAccess::meet`](crate::imposter::ScriptFileAccess::meet)), so an admin client's
    /// predicate never reads with a `--configfile` imposter's unconfined access, nor runs in its
    /// realm.
    pub fn verify_from(
        &self,
        opts: &VerifyOptions,
        door: &crate::imposter::ScriptFileAccess,
    ) -> anyhow::Result<VerifyOutcome> {
        let files = std::sync::Arc::new(self.script_file_access().meet(door));
        self.verify_with(opts, &files)
    }

    fn verify_with(
        &self,
        opts: &VerifyOptions,
        files: &std::sync::Arc<crate::imposter::ScriptFileAccess>,
    ) -> anyhow::Result<VerifyOutcome> {
        let scoped = self.get_recorded_requests_filtered(|r| match &opts.flow_id {
            Some(flow_id) => self.resolve_flow_id_recorded(&r.headers) == *flow_id,
            None => true,
        });
        let total = scoped.len();

        let mut matched = Vec::new();
        let mut non_matches = Vec::new();
        for req in scoped {
            if self.request_matches_predicates(&req, &opts.predicates, files)? {
                matched.push(req);
            } else if opts.include_closest {
                non_matches.push(req);
            }
        }

        let closest = if opts.include_closest {
            self.closest_non_match(non_matches, &opts.predicates, files)?
        } else {
            None
        };

        let matched_count = matched.len();
        Ok(VerifyOutcome {
            matched: matched_count,
            total,
            requests: opts.include_requests.then_some(matched),
            closest,
        })
    }

    /// Evaluate all `predicates` (implicit AND) against a recorded request, adapting the stored
    /// shape back to the matcher's inputs: the multi-value header map is handed to the shared
    /// predicate engine as-is (issue #1026), so a repeated header matches if *any* of its values
    /// satisfies the predicate — the same answer live stub matching, intercept rules and
    /// `savedRequests` filtering all give (issues #1025, #1026) — and the already-parsed query map
    /// is threaded directly so no query string is re-encoded.
    fn request_matches_predicates(
        &self,
        req: &RecordedRequest,
        predicates: &[Predicate],
        files: &std::sync::Arc<crate::imposter::ScriptFileAccess>,
    ) -> anyhow::Result<bool> {
        let form = Self::parse_form_data(&req.headers, req.body.as_deref());
        let body_json = crate::behaviors::LazyJson::new(req.body.as_deref());
        let client_ip = req.client_ip();
        // `RecordedRequest.query` is the fixed std-hasher journal/serde boundary (out of scope for
        // #704); `stub_matches_inner`'s `query_map` parameter is concretely `FastMap` (it is always
        // sourced from `parse_query`/`parse_query_string` elsewhere), so copy across here.
        let query_map: crate::util::MultiValueMap = req
            .query
            .iter()
            .map(|(k, v)| (k.clone(), v.clone()))
            .collect();
        // One recorded request evaluated against (possibly several, e.g. via `closest_non_match`)
        // predicates — same parse-once-per-evaluation shape as `body_json` above, applied to the
        // XML DOM (issue #711): an XPath predicate re-evaluated for this same request reuses one
        // parse rather than re-parsing per predicate.
        let xml_dom = req.body.as_deref().map(crate::behaviors::LazyXmlDom::new);
        stub_matches_inner(
            predicates,
            &req.method,
            &req.path,
            None,
            &req.headers,
            req.body.as_deref(),
            Some(&req.request_from),
            client_ip.as_deref(),
            form.as_ref(),
            &self.script_scope(),
            files,
            &body_json,
            xml_dom.as_ref(),
            Some(&query_map),
        )
    }

    /// The non-matching request satisfying the most top-level predicate clauses (ties → most
    /// recent, i.e. latest in the oldest-first journal), with the per-clause failure details a
    /// caller renders as a diff. `None` when there are no non-matches or no predicates to score.
    fn closest_non_match(
        &self,
        non_matches: Vec<RecordedRequest>,
        predicates: &[Predicate],
        files: &std::sync::Arc<crate::imposter::ScriptFileAccess>,
    ) -> anyhow::Result<Option<ClosestMatch>> {
        if non_matches.is_empty() || predicates.is_empty() {
            return Ok(None);
        }

        let mut best: Option<(usize, RecordedRequest)> = None;
        for req in non_matches {
            let mut satisfied = 0;
            for predicate in predicates {
                if self.request_matches_predicates(&req, std::slice::from_ref(predicate), files)? {
                    satisfied += 1;
                }
            }
            // `>=` so a later (more recent — the journal is oldest-first) request wins on a tie.
            let replace = match &best {
                None => true,
                Some((best_score, _)) => satisfied >= *best_score,
            };
            if replace {
                best = Some((satisfied, req));
            }
        }

        let (_, request) = best.expect("non_matches is non-empty");
        let mut failed_predicates = Vec::new();
        for predicate in predicates {
            if !self.request_matches_predicates(&request, std::slice::from_ref(predicate), files)? {
                failed_predicates.push(FailedPredicate {
                    predicate: predicate.clone(),
                    actual: actual_projection(&request, predicate),
                });
            }
        }
        Ok(Some(ClosestMatch {
            request,
            failed_predicates,
        }))
    }
}

/// The request's actual values for the fields a failed predicate references, as a JSON object —
/// the raw material for a readable diff. For a field-based op (`equals`/`contains`/…) only the
/// referenced fields are projected; for a compound (`and`/`or`/`not`), an `inject`, or a
/// selector-based predicate no single field is implicated, so the whole request is returned.
fn actual_projection(req: &RecordedRequest, predicate: &Predicate) -> Value {
    if predicate.parameters.selector.is_some() {
        return request_view(req);
    }
    let fields = match &predicate.operation {
        PredicateOperation::Equals(f)
        | PredicateOperation::DeepEquals(f)
        | PredicateOperation::Contains(f)
        | PredicateOperation::StartsWith(f)
        | PredicateOperation::EndsWith(f)
        | PredicateOperation::Matches(f)
        | PredicateOperation::Exists(f) => f,
        PredicateOperation::Not(_)
        | PredicateOperation::Or(_)
        | PredicateOperation::And(_)
        | PredicateOperation::Inject(_) => return request_view(req),
    };
    let mut out = Map::new();
    for key in fields.keys() {
        if let Some(value) = request_field(req, key) {
            out.insert(key.clone(), value);
        }
    }
    Value::Object(out)
}

/// A canonical JSON view of the whole recorded request (used when a predicate implicates no single
/// field).
fn request_view(req: &RecordedRequest) -> Value {
    let mut m = Map::new();
    m.insert("method".to_string(), json!(req.method));
    m.insert("path".to_string(), json!(req.path));
    m.insert("query".to_string(), shown(&req.query));
    m.insert("headers".to_string(), json!(req.headers));
    m.insert("requestFrom".to_string(), json!(req.request_from));
    if let Some(body) = &req.body {
        m.insert("body".to_string(), json!(body));
    }
    Value::Object(m)
}

/// The recorded request's value for a single predicate field key (Mountebank field names).
fn request_field(req: &RecordedRequest, key: &str) -> Option<Value> {
    match key {
        "method" => Some(json!(req.method)),
        "path" => Some(json!(req.path)),
        // A repeated key's values as an array, a single one as a string: the recorded shape.
        "query" => Some(shown(&req.query)),
        "headers" => Some(json!(req.headers)),
        "body" => Some(json!(req.body)),
        "requestFrom" => Some(json!(req.request_from)),
        // The `ip` predicate matches against the bare IP (`RecordedRequest::client_ip`), so report that as the
        // actual — not the `ip:port` `request_from` the matcher never compares against.
        "ip" => Some(json!(req.client_ip().unwrap_or_default())),
        "form" => Some(shown(
            &Imposter::parse_form_data(&req.headers, req.body.as_deref()).unwrap_or_default(),
        )),
        _ => None,
    }
}

/// A query or form as the journal prints it (issue #1553): one value is a string, several an
/// array.
fn shown<'a>(map: impl IntoIterator<Item = (&'a String, &'a Vec<String>)>) -> Value {
    Value::Object(
        map.into_iter()
            .map(|(k, v)| (k.clone(), crate::util::values_as_json(v)))
            .collect(),
    )
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::imposter::ResponseMode;
    use crate::imposter::types::ImposterConfig;
    use serde_json::json;

    fn imposter(flow_id_source: Option<&str>) -> Imposter {
        let mut cfg = json!({ "port": 0, "protocol": "http", "recordRequests": true, "stubs": [] });
        if let Some(src) = flow_id_source {
            cfg["_rift"] = json!({ "flowState": { "flowIdSource": src } });
        }
        let config: ImposterConfig = serde_json::from_value(cfg).expect("config");
        Imposter::new(config).expect("imposter")
    }

    fn rec(
        method: &str,
        path: &str,
        headers: &[(&str, &str)],
        body: Option<&str>,
    ) -> RecordedRequest {
        let mut hs: crate::imposter::Headers = crate::imposter::Headers::new();
        for (k, v) in headers {
            hs.entry((*k).to_string())
                .or_default()
                .push((*v).to_string());
        }
        RecordedRequest {
            clock_ms: None,
            clock_source: None,
            body_omitted: false,
            mode: ResponseMode::Text,
            request_from: "127.0.0.1:5000".to_string(),
            method: method.to_string(),
            path: path.to_string(),
            query: Default::default(),
            headers: hs,
            body: body.map(str::to_string),
            timestamp: "2026-01-01T00:00:00Z".to_string(),
            match_outcome: None,
            status: None,
            latency_ms: None,
            node: None,
        }
    }

    fn preds(v: Value) -> Vec<Predicate> {
        serde_json::from_value(v).expect("predicates")
    }

    #[test]
    fn matched_and_total_count_all_predicates_anded() {
        let imp = imposter(None);
        imp.record_request(rec("GET", "/a", &[], None));
        imp.record_request(rec("POST", "/a", &[], None));
        imp.record_request(rec("GET", "/b", &[], None));

        let opts = VerifyOptions {
            predicates: preds(json!([{ "equals": { "method": "GET", "path": "/a" } }])),
            ..Default::default()
        };
        let out = imp.verify(&opts).expect("verify");
        assert_eq!(out.total, 3);
        assert_eq!(out.matched, 1);
        assert!(out.requests.is_none(), "requests omitted unless requested");
        assert!(out.closest.is_none(), "closest omitted unless requested");
    }

    // Issue #1553: verify re-runs predicates over the recorded query, which keeps every value of a
    // repeated key, so it answers as live matching does — including the closest-miss report,
    // which shows the key as an array.
    #[test]
    fn an_array_predicate_matches_a_recorded_repeated_key() {
        let imp = imposter(None);
        let mut req = rec("GET", "/q", &[], None);
        req.query.insert(
            "key".to_string(),
            vec!["first".to_string(), "second".to_string()],
        );
        imp.record_request(req);

        let count = |predicates: Value| {
            let opts = VerifyOptions {
                predicates: preds(predicates),
                ..Default::default()
            };
            imp.verify(&opts).expect("verify").matched
        };
        assert_eq!(
            count(json!([{ "equals": { "query": { "key": ["second", "first"] } } }])),
            1
        );
        assert_eq!(
            count(json!([{ "deepEquals": { "query": { "key": ["second", "first"] } } }])),
            1
        );
        assert_eq!(
            count(json!([{ "equals": { "query": { "key": "second" } } }])),
            1
        );
        assert_eq!(
            count(json!([{ "equals": { "query": { "key": "first,second" } } }])),
            0
        );

        let opts = VerifyOptions {
            predicates: preds(json!([{ "equals": { "query": { "key": "third" } } }])),
            include_closest: true,
            ..Default::default()
        };
        let closest = imp.verify(&opts).expect("verify").closest.expect("closest");
        assert_eq!(
            closest.failed_predicates[0].actual,
            json!({ "query": { "key": ["first", "second"] } })
        );
    }

    #[test]
    fn empty_predicates_match_everything() {
        let imp = imposter(None);
        imp.record_request(rec("GET", "/a", &[], None));
        imp.record_request(rec("GET", "/b", &[], None));
        let out = imp.verify(&VerifyOptions::default()).expect("verify");
        assert_eq!(out.matched, 2);
        assert_eq!(out.total, 2);
    }

    #[test]
    fn include_requests_returns_the_matching_requests() {
        let imp = imposter(None);
        imp.record_request(rec("GET", "/keep", &[], None));
        imp.record_request(rec("GET", "/drop", &[], None));
        imp.record_request(rec("GET", "/keep", &[], None));

        let opts = VerifyOptions {
            predicates: preds(json!([{ "equals": { "path": "/keep" } }])),
            include_requests: true,
            ..Default::default()
        };
        let out = imp.verify(&opts).expect("verify");
        let reqs = out.requests.expect("requests present");
        assert_eq!(reqs.len(), 2);
        assert!(reqs.iter().all(|r| r.path == "/keep"));
    }

    #[test]
    fn closest_picks_most_satisfied_clauses_and_reports_failures() {
        let imp = imposter(None);
        // Satisfies neither clause.
        imp.record_request(rec("DELETE", "/x", &[], None));
        // Satisfies method only (1 of 2) — the closest.
        imp.record_request(rec("GET", "/x", &[], None));

        let opts = VerifyOptions {
            predicates: preds(json!([
                { "equals": { "method": "GET" } },
                { "equals": { "path": "/wanted" } }
            ])),
            include_closest: true,
            ..Default::default()
        };
        let out = imp.verify(&opts).expect("verify");
        assert_eq!(out.matched, 0);
        let closest = out.closest.expect("closest present");
        assert_eq!(closest.request.path, "/x");
        assert_eq!(closest.request.method, "GET");
        // Only the path clause failed; the method clause was satisfied.
        assert_eq!(closest.failed_predicates.len(), 1);
        assert_eq!(closest.failed_predicates[0].actual, json!({ "path": "/x" }));
    }

    #[test]
    fn closest_breaks_ties_toward_the_most_recent() {
        let imp = imposter(None);
        // Both satisfy the method clause (1 of 1 failing overall since path never matches),
        // so the tie is broken toward the later-recorded request.
        imp.record_request(rec("GET", "/first", &[], None));
        imp.record_request(rec("GET", "/second", &[], None));

        let opts = VerifyOptions {
            predicates: preds(json!([
                { "equals": { "method": "GET" } },
                { "equals": { "path": "/never" } }
            ])),
            include_closest: true,
            ..Default::default()
        };
        let out = imp.verify(&opts).expect("verify");
        let closest = out.closest.expect("closest present");
        assert_eq!(
            closest.request.path, "/second",
            "ties resolve to most recent"
        );
    }

    #[test]
    fn flow_id_scopes_total_and_matched() {
        let imp = imposter(Some("header:X-Space"));
        imp.record_request(rec("GET", "/a", &[("X-Space", "blue")], None));
        imp.record_request(rec("GET", "/a", &[("X-Space", "green")], None));
        imp.record_request(rec("GET", "/a", &[("X-Space", "blue")], None));

        let opts = VerifyOptions {
            predicates: preds(json!([{ "equals": { "path": "/a" } }])),
            flow_id: Some("blue".to_string()),
            ..Default::default()
        };
        let out = imp.verify(&opts).expect("verify");
        assert_eq!(out.total, 2, "total is scoped to the flow");
        assert_eq!(out.matched, 2);
    }

    #[test]
    fn flow_id_scopes_under_the_default_imposter_port_source() {
        // With no flow_id_source declared, every request's flow is the imposter port ("0" here).
        let imp = imposter(None);
        imp.record_request(rec("GET", "/a", &[], None));
        imp.record_request(rec("GET", "/a", &[], None));

        let matching = VerifyOptions {
            flow_id: Some("0".to_string()),
            ..Default::default()
        };
        assert_eq!(imp.verify(&matching).expect("verify").total, 2);

        let other = VerifyOptions {
            flow_id: Some("999".to_string()),
            ..Default::default()
        };
        let out = imp.verify(&other).expect("verify");
        assert_eq!(out.total, 0, "a non-matching flow scopes everything out");
        assert_eq!(out.matched, 0);
    }

    #[test]
    fn ip_predicate_matches_against_the_recorded_client_ip() {
        // Regression: the `ip` field must compare against the bare IP recovered from `request_from`
        // (`ip:port`), not an empty string — otherwise every `ip` predicate silently mis-counts.
        let imp = imposter(None);
        imp.record_request(rec("GET", "/a", &[], None)); // request_from = 127.0.0.1:5000

        let opts = VerifyOptions {
            predicates: preds(json!([{ "equals": { "ip": "127.0.0.1" } }])),
            ..Default::default()
        };
        assert_eq!(imp.verify(&opts).expect("verify").matched, 1);
    }

    #[test]
    fn multi_value_header_matches_on_any_value() {
        // Issue #1026, flipping the pre-#994 pin: verify shares the predicate engine with live
        // matching and intercept rules, so a repeated header matches if ANY of its values does.
        // The absent-value case is what discriminates this from a "take the first instead of the
        // last" non-fix, which would satisfy the two positive cases on its own.
        let imp = imposter(None);
        imp.record_request(rec(
            "GET",
            "/a",
            &[("X-Dup", "first"), ("X-Dup", "second")],
            None,
        ));

        for value in ["first", "second"] {
            let opts = VerifyOptions {
                predicates: preds(json!([{ "equals": { "headers": { "X-Dup": value } } }])),
                ..Default::default()
            };
            assert_eq!(
                imp.verify(&opts).expect("verify").matched,
                1,
                "{value} is one of the values the client sent, so it must match"
            );
        }

        let absent = VerifyOptions {
            predicates: preds(json!([{ "equals": { "headers": { "X-Dup": "third" } } }])),
            ..Default::default()
        };
        assert_eq!(
            imp.verify(&absent).expect("verify").matched,
            0,
            "a value the client never sent must not match"
        );
    }

    #[test]
    fn multi_value_header_not_predicate_sees_every_value() {
        // Issue #1026: `not` inherits the flip. Under the old last-wins collapse this request
        // satisfied `not(equals X-Dup: first)` because `first` was shadowed; now that `first` is
        // visible, the negation must fail.
        let imp = imposter(None);
        imp.record_request(rec(
            "GET",
            "/a",
            &[("X-Dup", "first"), ("X-Dup", "second")],
            None,
        ));

        let opts = VerifyOptions {
            predicates: preds(
                json!([{ "not": { "equals": { "headers": { "X-Dup": "first" } } } }]),
            ),
            ..Default::default()
        };
        assert_eq!(
            imp.verify(&opts).expect("verify").matched,
            0,
            "the shadowed value is no longer shadowed, so `not` must not match"
        );

        let unsent = VerifyOptions {
            predicates: preds(
                json!([{ "not": { "equals": { "headers": { "X-Dup": "third" } } } }]),
            ),
            ..Default::default()
        };
        assert_eq!(
            imp.verify(&unsent).expect("verify").matched,
            1,
            "`not` on a value that was never sent still matches"
        );
    }

    #[test]
    fn deep_equals_on_a_repeated_header_needs_its_values_and_counts_the_name_once() {
        // Issue #1026: `deepEquals` is the one header operator that also compares the expected
        // object's key count against `RequestHeaders::len()`, and the multi-value impl counts
        // *names*, not values. A repeated header must therefore stay one name — otherwise a
        // request carrying two values of one header could never satisfy a one-key `deepEquals`.
        // Issue #1553: the repeated name is an array, so `deepEquals` needs its values as a
        // multiset, as Mountebank compares it; one of them alone no longer matches.
        let imp = imposter(None);
        imp.record_request(rec(
            "GET",
            "/a",
            &[("X-Dup", "first"), ("X-Dup", "second")],
            None,
        ));

        for (value, expected) in [
            (json!(["second", "first"]), 1),
            (json!("first"), 0),
            (json!(["first"]), 0),
        ] {
            let opts = VerifyOptions {
                predicates: preds(json!([{ "deepEquals": { "headers": { "X-Dup": value } } }])),
                ..Default::default()
            };
            assert_eq!(
                imp.verify(&opts).expect("verify").matched,
                expected,
                "one repeated name counts once; {value} against both of its values"
            );
        }

        let unsent = VerifyOptions {
            predicates: preds(
                json!([{ "deepEquals": { "headers": { "X-Dup": ["first", "third"] } } }]),
            ),
            ..Default::default()
        };
        assert_eq!(
            imp.verify(&unsent).expect("verify").matched,
            0,
            "a value the client never sent must not match"
        );

        let extra_name = VerifyOptions {
            predicates: preds(json!([
                { "deepEquals": { "headers": { "X-Dup": ["first", "second"], "X-Other": "x" } } }
            ])),
            ..Default::default()
        };
        assert_eq!(
            imp.verify(&extra_name).expect("verify").matched,
            0,
            "deepEquals still requires the name counts to agree"
        );
    }

    #[test]
    fn closest_form_projection_parses_with_a_repeated_content_type() {
        // Issue #1026: Content-Type is single-valued (RFC 9110), so a repeated one is a malformed
        // request; the form projection takes the FIRST value rather than giving up on the parse.
        let imp = imposter(None);
        imp.record_request(rec(
            "POST",
            "/a",
            &[
                ("Content-Type", "application/x-www-form-urlencoded"),
                ("Content-Type", "text/plain"),
            ],
            Some("a=1&b=2"),
        ));

        let opts = VerifyOptions {
            predicates: preds(json!([{ "equals": { "form": { "a": "9" } } }])),
            include_closest: true,
            ..Default::default()
        };
        let closest = imp.verify(&opts).expect("verify").closest.expect("closest");
        let actual = &closest.failed_predicates[0].actual;
        assert_eq!(
            actual.get("form").and_then(|f| f.get("a")),
            Some(&json!("1")),
            "the first Content-Type wins, so the body still parses as a form: {actual}"
        );
    }

    #[test]
    fn header_name_with_no_values_reads_as_absent() {
        // Issue #1026: `RecordedRequest.headers` is public API, so a name mapped to an empty list
        // is reachable. The multi-value `RequestHeaders` impl filters those, and verify must
        // inherit that — the name reads as absent to `exists`, not as present-with-no-value.
        let imp = imposter(None);
        let mut req = rec("GET", "/a", &[], None);
        req.headers.insert("X-Empty".to_string(), Vec::new());
        imp.record_request(req);

        let opts = VerifyOptions {
            predicates: preds(json!([{ "exists": { "headers": { "X-Empty": true } } }])),
            ..Default::default()
        };
        assert_eq!(
            imp.verify(&opts).expect("verify").matched,
            0,
            "a header name carrying no values must not read as present"
        );
    }

    #[test]
    fn closest_actual_falls_back_to_the_whole_request_for_a_compound_predicate() {
        // A compound (`or`) predicate implicates no single field, so `actual` is the whole-request
        // view rather than a field-keyed projection.
        let imp = imposter(None);
        imp.record_request(rec("GET", "/c", &[], None));

        let opts = VerifyOptions {
            predicates: preds(json!([
                { "or": [{ "equals": { "path": "/a" } }, { "equals": { "path": "/b" } }] }
            ])),
            include_closest: true,
            ..Default::default()
        };
        let closest = imp.verify(&opts).expect("verify").closest.expect("closest");
        assert_eq!(closest.failed_predicates.len(), 1);
        let actual = &closest.failed_predicates[0].actual;
        assert!(
            actual.get("method").is_some() && actual.get("path").is_some(),
            "compound predicate reports the whole request view, got {actual}"
        );
    }

    #[test]
    fn closest_actual_falls_back_to_the_whole_request_for_a_selector_predicate() {
        // A jsonpath/xpath selector rewrites the effective body, so no single request field is
        // implicated — `actual` is the whole-request view.
        let imp = imposter(None);
        imp.record_request(rec("POST", "/a", &[], Some(r#"{"foo":"bar"}"#)));

        let opts = VerifyOptions {
            predicates: preds(json!([
                { "equals": { "body": "nope" }, "jsonpath": { "selector": "$.foo" } }
            ])),
            include_closest: true,
            ..Default::default()
        };
        let closest = imp.verify(&opts).expect("verify").closest.expect("closest");
        let actual = &closest.failed_predicates[0].actual;
        assert!(
            actual.get("method").is_some() && actual.get("headers").is_some(),
            "selector predicate reports the whole request view, got {actual}"
        );
    }
}