sendra-core 0.1.0

Core request/response model, YAML loading and HTTP execution for Sendra.
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
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
//! Values a request pulls out of its response and hands to the requests after
//! it.
//!
//! A request file may carry a `capture` block: variable names mapped to a
//! source to read from the response once it arrives. The default source,
//! and originally the only one, is a JSON path evaluated against the
//! response body — a bare string still means exactly that, for every file
//! already written against it. Two more sources are read from a response's
//! envelope rather than its body: a named header, and the status code
//! itself.
//!
//! ```yaml
//! name: Log in
//! method: POST
//! url: https://api.example.com/login
//! capture:
//!   auth_token: $.token          # JSON path (default, bare string)
//!   user_id: $.user.id
//!   session_id:
//!     header: Set-Cookie          # a response header
//!   request_status:
//!     status: true                # the numeric status, as a string
//! ```
//!
//! # Header capture and repeated headers
//!
//! Header names are matched case-insensitively, the way [`assertions`
//! matches them](crate::assertions). A header that does not repeat captures
//! its one value. A header that repeats (`Set-Cookie` is the common case) is
//! **ambiguous** rather than resolved by taking the first or the last: this
//! mirrors the JSON-path rule that a path selecting more than one value is a
//! failure rather than a silent pick (see [`CaptureFailure::Ambiguous`]).
//! An assertion checking `headers: { set-cookie: ... }` passes if *any*
//! repeated value matches, because it is testing a predicate; a capture
//! binds a name to *one* value that later requests will substitute, and
//! guessing which repeat that should be would make the same file behave
//! differently depending on header order a server happens to send in. A
//! file that wants one specific cookie out of several should be more
//! specific than `header: Set-Cookie` can be today — see the module-level
//! non-goal note below.
//!
//! # Only the final response's headers
//!
//! With `follow_redirects` on, header capture reads the headers of the
//! response `evaluate` is called with — the *final* response in the chain.
//! [`Response::redirects`](crate::Response) records each intermediate hop's
//! status and the `Location` it pointed at, but deliberately does not carry
//! that hop's full header set (see the type's own docs), so there is no
//! intermediate `Set-Cookie` or other header for this to reach even if the
//! schema grew a way to ask for one. Capturing the *final* hop's `Location`
//! is possible today (a response that redirected already exposes its own
//! `Location` if it is itself 3xx and redirects were disabled or exhausted),
//! but reaching into an earlier hop is out of scope here: it would need
//! `RedirectHop` extended to carry headers, which is a bigger, separate
//! change. Documented as a non-goal rather than a partial `hop:` key that
//! could only ever address the one field `RedirectHop` already has.
//!
//! Every name captured this way becomes usable as `{{auth_token}}` in **every
//! request after this one, in file order**, through the same substitution pass
//! an environment file feeds. Nothing is written anywhere: a capture lives for
//! the rest of one `sendra run` or `sendra test` invocation and no longer. A
//! fresh process starts with nothing captured, which is the same non-goal
//! environments shipped with.
//!
//! # A capture is not a check
//!
//! [`Captures::evaluate`] returns a [`CaptureReport`] and no `Result`, exactly
//! as [`Assertions::evaluate`](crate::Assertions::evaluate) does, and for the
//! same reason: the response has already arrived, so there is nothing left to
//! abort, and the only useful thing to do with a capture that did not work is
//! to say precisely how it did not work, next to the ones that did.
//!
//! But it is not an assertion either, and the difference decides how a
//! front-end counts it. An assertion is an expectation about the response; a
//! capture is a *dependency of the rest of the run*. So a capture that succeeds
//! says nothing about whether the response was correct — a request that
//! captured a token and asserted nothing was still not checked — while a
//! capture that fails is a genuine failure, because a value the file promised
//! to the requests downstream is not there. See [`CaptureReport::passed`] and
//! the `Summary` type in `sendra-cli` for where that lands.
//!
//! # Why the failures are typed rather than [`SendraError`]s
//!
//! A [`SendraError`] means "this request could not be completed", and every
//! variant of it is raised on a path where there is no response: a file that
//! does not parse, a `{{var}}` with nothing behind it, a refused connection, a
//! `pre_request` script that threw. A capture failure is the opposite shape —
//! the response arrived, was read, and did not contain what the file said it
//! would — and folding it into that enum would have put it in the one category
//! it is definitely not in.
//!
//! Typing it as [`CaptureFailure`] instead also keeps the block's entries
//! independent: three captures against one response produce three results, the
//! way three assertions do, rather than the first failure discarding whatever
//! the other two would have found.

use std::collections::BTreeMap;
use std::path::PathBuf;

use jsonpath_rust::JsonPath;
use serde::{Deserialize, Serialize};

use crate::environment::describe_environment;
use crate::{Environment, Response};

/// Where one `capture` entry reads its value from.
///
/// A bare string is the original and default form: a JSON path into the
/// response body. The two additive forms are objects, so a bare string can
/// never be confused with them: `header: Set-Cookie` reads a response
/// header, and `status: true` reads the numeric status code.
///
/// `status: false` is rejected at parse time (a request file that says it
/// does not want the status captured this way is not saying anything a
/// schema should represent) rather than left to fail silently at evaluate
/// time — the same call [`FollowRedirects`](crate::config::FollowRedirects)
/// makes for a negative hop count.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(untagged)]
pub enum CaptureSource {
    // `JsonSchema` cannot be derived here: the shape below is not what
    // `#[derive(JsonSchema)]` would infer from this enum plus its
    // `#[serde(untagged)]`, because the real acceptance rule
    // (`status: false` is rejected) lives in the hand-written `Deserialize`
    // impl below, not in the enum's shape. See the manual `impl JsonSchema`
    // a few lines down, which encodes that rule as `"const": true` — one of
    // the few business rules from `Request::validate` and friends that a
    // JSON Schema combinator genuinely can express, rather than merely
    // approximate.
    /// The default, bare-string form: a JSON path into the response body.
    JsonPath(String),
    /// An object form: `header: <name>`. Matched case-insensitively against
    /// [`Response::headers`](crate::Response), the way
    /// [`assertions`](crate::assertions) matches header names.
    Header { header: String },
    /// An object form: `status: true`. Captures the response's numeric
    /// status code, rendered as a string (`"404"`, not `404`).
    Status { status: bool },
}

impl<'de> Deserialize<'de> for CaptureSource {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        // An intermediate shape so `status: false` can be told apart from
        // `status: true` before committing to `CaptureSource::Status`, which
        // (deliberately) has no way to spell "false" — see the type's docs.
        #[derive(Deserialize)]
        #[serde(untagged, deny_unknown_fields)]
        enum Raw {
            JsonPath(String),
            Header { header: String },
            Status { status: bool },
        }

        match Raw::deserialize(deserializer)? {
            Raw::JsonPath(path) => Ok(CaptureSource::JsonPath(path)),
            Raw::Header { header } => Ok(CaptureSource::Header { header }),
            Raw::Status { status: true } => Ok(CaptureSource::Status { status: true }),
            Raw::Status { status: false } => Err(serde::de::Error::custom(
                "`status: false` does not capture anything; use `status: true` or remove this \
                 entry",
            )),
        }
    }
}

/// Hand-written to match the hand-written [`Deserialize`] impl above rather
/// than derived, and — unlike most of the manual impls in this crate — able
/// to express the *whole* acceptance rule, `status: false` included: a JSON
/// Schema validator that enforces `"const": true` on the `status` property
/// will flag `status: false` as a schema violation, the same file Sendra's
/// own parser rejects.
#[cfg(feature = "schema")]
impl schemars::JsonSchema for CaptureSource {
    fn schema_name() -> std::borrow::Cow<'static, str> {
        "CaptureSource".into()
    }

    fn json_schema(_generator: &mut schemars::SchemaGenerator) -> schemars::Schema {
        schemars::json_schema!({
            "description": "Where one `capture` entry reads its value from: a bare string is a \
                JSON path into the response body; `{ header: <name> }` reads a response header; \
                `{ status: true }` captures the numeric status code. `status: false` is invalid.",
            "oneOf": [
                {
                    "type": "string",
                    "description": "A JSON path into the response body."
                },
                {
                    "type": "object",
                    "properties": { "header": { "type": "string" } },
                    "required": ["header"],
                    "additionalProperties": false
                },
                {
                    "type": "object",
                    "properties": { "status": { "type": "boolean", "const": true } },
                    "required": ["status"],
                    "additionalProperties": false
                }
            ]
        })
    }
}

impl CaptureSource {
    /// The label a report shows for this entry — the path text unchanged
    /// for the default JSON-path form (so [`CaptureResult::path`] and
    /// everything reading it, `--json` output included, is untouched for
    /// every file already written against the original bare-string form),
    /// and a short description of the source for the two additive forms.
    fn label(&self) -> String {
        match self {
            CaptureSource::JsonPath(path) => path.clone(),
            CaptureSource::Header { header } => format!("header `{header}`"),
            CaptureSource::Status { .. } => "status".to_string(),
        }
    }
}

/// The `capture` block of a request, exactly as it appears on disk: variable
/// name to [`CaptureSource`].
///
/// A map with author-chosen keys, so unlike every *struct* in Sendra's schema
/// there is no `deny_unknown_fields` to apply — every key here is data. The
/// rule that a typo must not pass silently still holds, one level down: a path
/// that selects nothing is a reported failure rather than a variable that
/// quietly does not exist.
///
/// Names are not validated against a pattern. A variable is whatever
/// `{{...}}` can spell, and an environment file has never restricted its own
/// keys either; a name nothing references is harmless, and one that cannot be
/// referenced is a mistake visible the moment it is used.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(transparent)]
pub struct Captures {
    entries: BTreeMap<String, CaptureSource>,
}

impl Captures {
    /// True when the block captures nothing — `capture: {}`.
    pub fn is_empty(&self) -> bool {
        self.entries.is_empty()
    }

    /// The variable names this block defines, sorted.
    pub fn variables(&self) -> Vec<String> {
        self.entries.keys().cloned().collect()
    }

    /// The name-to-source pairs, sorted by name.
    pub fn entries(&self) -> &BTreeMap<String, CaptureSource> {
        &self.entries
    }

    /// Extract every value this block names from `response`.
    ///
    /// `environment` is read for one thing only: a captured name that the
    /// environment file already defines is rejected rather than allowed to
    /// shadow it. See [`CaptureFailure::Shadowed`] for that decision.
    ///
    /// Entries are evaluated in sorted-name order and none short-circuits the
    /// others, so a report always has exactly one result per entry — the same
    /// contract [`AssertionReport`](crate::AssertionReport) makes.
    pub fn evaluate(&self, response: &Response, environment: &Environment) -> CaptureReport {
        if self.entries.is_empty() {
            return CaptureReport::default();
        }

        // Parsed once for the whole block, not once per path: the body does not
        // change between entries, and a body that is not JSON should report the
        // same reason against every one of them.
        let body = serde_json::from_str::<serde_json::Value>(&response.body);

        CaptureReport {
            results: self
                .entries
                .iter()
                .map(|(variable, source)| {
                    capture_one(variable, source, body.as_ref(), response, environment)
                })
                .collect(),
        }
    }
}

impl FromIterator<(String, CaptureSource)> for Captures {
    fn from_iter<T: IntoIterator<Item = (String, CaptureSource)>>(iter: T) -> Self {
        Self {
            entries: iter.into_iter().collect(),
        }
    }
}

/// Why one entry of a `capture` block did not produce a value.
///
/// Typed rather than a bare string so a front-end can branch on it — and so
/// the granularity the assertion JSON paths already draw ("not a valid JSON
/// path" is a broken file, "the body is not JSON" is a fact about this
/// response, "matched nothing" is a fact about the pair) survives into
/// anything reading a run rather than being recoverable only by matching on
/// prose. [`Display`](std::fmt::Display) renders the wording, in core, so every
/// front-end says the same thing about the same failure.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum CaptureFailure {
    /// The name is already defined by the active environment file. See the
    /// note on this variant's message for why that is rejected rather than
    /// resolved in either direction.
    Shadowed {
        /// The environment file that already defines the name, or `None` when
        /// the environment did not come from a file.
        environment: Option<PathBuf>,
    },

    /// The path is not a JSON path at all.
    InvalidPath { reason: String },

    /// The response body did not parse as JSON, so there was nothing to query.
    BodyNotJson {
        /// serde_json's own message, position included.
        reason: String,
        /// The response's `content-type`, when it had one — a body with none at
        /// all is a different mistake from one that announced `text/html`.
        content_type: Option<String>,
    },

    /// The path is valid and the body is JSON, and the path selected nothing.
    NoMatch,

    /// The source selected more than one value, so there is no single value
    /// to bind the name to. Raised for a JSON path matching several values,
    /// and — the same philosophy applied to a second source — for a header
    /// capture whose name repeats in the response (`Set-Cookie` is the
    /// common case). See the module docs for why a capture does not resolve
    /// a repeated header by taking the first or last value, the way an
    /// assertion checking the same header does.
    Ambiguous {
        count: usize,
        /// The first few matches, rendered, for the message.
        sample: Vec<String>,
    },

    /// The path selected exactly one value and that value has no text form a
    /// `{{name}}` could be replaced with: `null`, an array or an object.
    NotAScalar {
        /// `null`, `an array`, `an object`.
        kind: &'static str,
    },

    /// A `header:` capture named a header the response does not carry.
    HeaderNotFound {
        header: String,
        /// The header names the response does carry, for the same reason a
        /// missing assertion header lists them: the answer is usually a
        /// casing or spelling difference, visible once both are on screen.
        present: Vec<String>,
    },
}

impl std::fmt::Display for CaptureFailure {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            CaptureFailure::Shadowed { environment } => write!(
                f,
                "{} already defines this variable; rename the capture or the environment entry",
                describe_environment(environment)
            ),
            CaptureFailure::InvalidPath { reason } => write!(f, "not a valid JSON path: {reason}"),
            CaptureFailure::BodyNotJson {
                reason,
                content_type,
            } => write!(
                f,
                "the response body is not JSON: {reason}{}",
                match content_type {
                    Some(content_type) => format!(" (content-type: {content_type})"),
                    None => " (no content-type header)".to_string(),
                }
            ),
            CaptureFailure::NoMatch => f.write_str("matched nothing in the response body"),
            CaptureFailure::Ambiguous { count, sample } => write!(
                f,
                "matched {count} values ({}); a capture needs a source that selects exactly one",
                sample.join(", ")
            ),
            CaptureFailure::NotAScalar { kind } => write!(
                f,
                "matched {kind}, which has no text form to substitute; capture a string, \
                 number or boolean"
            ),
            CaptureFailure::HeaderNotFound { header, present } => write!(
                f,
                "no `{header}` header in the response{}",
                if present.is_empty() {
                    "; the response carries no headers at all".to_string()
                } else {
                    format!(" (the response has: {})", present.join(", "))
                }
            ),
        }
    }
}

/// One entry of a `capture` block, evaluated.
///
/// `value` and `failure` are the two halves of one answer and exactly one of
/// them is ever set; the constructors below are private so a result cannot be
/// built claiming both or neither.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CaptureResult {
    /// The variable name this entry defines.
    pub variable: String,
    /// Where it was read from: the JSON path text, unchanged, for the
    /// default form; a short description (`` header `Set-Cookie` ``,
    /// `status`) for the two additive ones. See
    /// [`CaptureSource::label`](CaptureSource).
    pub path: String,
    value: Option<String>,
    failure: Option<CaptureFailure>,
}

impl CaptureResult {
    pub fn passed(&self) -> bool {
        self.failure.is_none()
    }

    /// The text this entry captured, or `None` if it did not.
    pub fn value(&self) -> Option<&str> {
        self.value.as_deref()
    }

    /// Why the entry produced no value, or `None` if it did.
    pub fn failure(&self) -> Option<&CaptureFailure> {
        self.failure.as_ref()
    }

    fn captured(variable: &str, path: &str, value: String) -> Self {
        Self {
            variable: variable.to_string(),
            path: path.to_string(),
            value: Some(value),
            failure: None,
        }
    }

    fn fail(variable: &str, path: &str, failure: CaptureFailure) -> Self {
        Self {
            variable: variable.to_string(),
            path: path.to_string(),
            value: None,
            failure: Some(failure),
        }
    }
}

/// Every entry of one request's `capture` block, evaluated against its
/// response, in sorted-name order.
///
/// The default is the empty report, which is what a request with no `capture`
/// block produces: nothing captured, nothing failed, and nothing printed.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct CaptureReport {
    results: Vec<CaptureResult>,
}

impl CaptureReport {
    pub fn results(&self) -> &[CaptureResult] {
        &self.results
    }

    /// No `capture` block was declared, or it was empty.
    pub fn is_empty(&self) -> bool {
        self.results.is_empty()
    }

    pub fn len(&self) -> usize {
        self.results.len()
    }

    /// Every entry produced a value (vacuously true when there are none).
    pub fn passed(&self) -> bool {
        self.results.iter().all(CaptureResult::passed)
    }

    pub fn captured_count(&self) -> usize {
        self.results.iter().filter(|result| result.passed()).count()
    }

    pub fn failed_count(&self) -> usize {
        self.results.len() - self.captured_count()
    }

    /// Just the entries that produced no value, in evaluation order.
    pub fn failures(&self) -> impl Iterator<Item = &CaptureResult> {
        self.results.iter().filter(|result| !result.passed())
    }

    /// The name-to-value pairs this request contributes to the run.
    ///
    /// Only the entries that succeeded: a failed capture defines nothing, which
    /// is what makes the downstream `{{name}}` a `VariableNotFound` naming the
    /// variable rather than a request sent with an empty string in it.
    pub fn values(&self) -> BTreeMap<String, String> {
        self.results
            .iter()
            .filter_map(|result| {
                result
                    .value()
                    .map(|value| (result.variable.clone(), value.to_string()))
            })
            .collect()
    }
}

/// One entry of a `capture` block, against the already-parsed body.
///
/// The checks are ordered most-general-first, which is the same order
/// `check_json_path` in [`assertions`](crate::assertions) uses and for the same
/// reason: told about several problems at once, a reader wants the one that is
/// wrong about every response rather than the one that is wrong about this one.
/// A name that collides with the environment is wrong before a request is ever
/// sent; a path that does not parse is wrong about every response there could
/// be; a body that is not JSON is a fact about this response; a path that
/// matched nothing is a fact about the two together.
fn capture_one(
    variable: &str,
    source: &CaptureSource,
    body: Result<&serde_json::Value, &serde_json::Error>,
    response: &Response,
    environment: &Environment,
) -> CaptureResult {
    let label = source.label();
    let fail = |failure| CaptureResult::fail(variable, &label, failure);

    if environment.variables.contains_key(variable) {
        return fail(CaptureFailure::Shadowed {
            environment: environment.source.clone(),
        });
    }

    match source {
        CaptureSource::JsonPath(path) => capture_json_path(variable, path, body, response),
        CaptureSource::Header { header } => capture_header(variable, header, response),
        CaptureSource::Status { .. } => {
            CaptureResult::captured(variable, &label, response.status.to_string())
        }
    }
}

/// The JSON-path source: the original, default form, unchanged since it was
/// the only one.
fn capture_json_path(
    variable: &str,
    path: &str,
    body: Result<&serde_json::Value, &serde_json::Error>,
    response: &Response,
) -> CaptureResult {
    let fail = |failure| CaptureResult::fail(variable, path, failure);

    // Checked here rather than when the file is loaded, even though it could
    // be, for the reason `assertions` gives: loading a request file should
    // never depend on the path grammar of this dependency, or a stricter
    // release would start rejecting files that used to load.
    if let Err(err) = jsonpath_rust::parser::parse_json_path(path) {
        return fail(CaptureFailure::InvalidPath {
            reason: err.to_string(),
        });
    }

    let body = match body {
        Ok(body) => body,
        Err(err) => {
            return fail(CaptureFailure::BodyNotJson {
                reason: err.to_string(),
                content_type: content_type(response).map(str::to_owned),
            })
        }
    };

    let selected = match body.query(path) {
        Ok(selected) => selected,
        Err(err) => {
            return fail(CaptureFailure::InvalidPath {
                reason: err.to_string(),
            })
        }
    };

    match selected.as_slice() {
        [only] => match scalar_text(only) {
            Ok(text) => CaptureResult::captured(variable, path, text),
            Err(kind) => fail(CaptureFailure::NotAScalar { kind }),
        },
        [] => fail(CaptureFailure::NoMatch),
        many => fail(CaptureFailure::Ambiguous {
            count: many.len(),
            sample: many
                .iter()
                .take(3)
                .map(|value| serde_json::to_string(value).unwrap_or_else(|_| value.to_string()))
                .collect(),
        }),
    }
}

/// The `header:` source. Names are matched case-insensitively, the way
/// [`assertions`](crate::assertions) matches them; a name that repeats in the
/// response is [`CaptureFailure::Ambiguous`] rather than a first-or-last
/// pick — see the module docs.
fn capture_header(variable: &str, header: &str, response: &Response) -> CaptureResult {
    let label = format!("header `{header}`");
    let fail = |failure| CaptureResult::fail(variable, &label, failure);

    let matches: Vec<&str> = response
        .headers
        .iter()
        .filter(|(name, _)| name.eq_ignore_ascii_case(header))
        .map(|(_, value)| value.as_str())
        .collect();

    match matches.as_slice() {
        [only] => CaptureResult::captured(variable, &label, only.to_string()),
        [] => fail(CaptureFailure::HeaderNotFound {
            header: header.to_string(),
            present: response
                .headers
                .iter()
                .map(|(name, _)| name.clone())
                .collect(),
        }),
        many => fail(CaptureFailure::Ambiguous {
            count: many.len(),
            sample: many.iter().take(3).map(|value| value.to_string()).collect(),
        }),
    }
}

/// The text a captured JSON value is substituted as, or the name of the kind
/// that has no such text.
///
/// A string captures **unquoted** — `"ada"` becomes `ada`, not `"ada"` — because
/// substitution replaces `{{name}}` inside a URL, a header or a body, and the
/// quotes are JSON's punctuation rather than part of the value.
///
/// Numbers and booleans capture as `serde_json` renders them, which is the
/// value and not the spelling: `42` is `42` and `true` is `true`, but a body
/// that said `1.50` captures as `1.5`, because the body was parsed into an
/// `f64` before anything here saw it. That is a real difference from an
/// environment file, where `port: 8080` is the *string* `8080` and nothing is
/// normalised — and it is the honest one to expose, since the value really did
/// make a round trip through a number. Pretending otherwise would need
/// `serde_json`'s `arbitrary_precision`, which changes how every JSON assertion
/// in the crate compares numbers; an endpoint whose exact digits matter should
/// send them as a JSON string.
///
/// `null`, arrays and objects are refused. `null` has no text form that is not
/// a guess between `""` and `null`. An array or an object has one — compact
/// JSON — but substitution's entire safety argument is that a substituted value
/// cannot change the shape of what it lands in, and pushing `{"a":1}` into a
/// URL or a header is exactly that hazard. Refusing is the reversible choice:
/// it can be relaxed later, while a build that had already been serialising
/// objects into URLs could not be tightened.
fn scalar_text(value: &serde_json::Value) -> Result<String, &'static str> {
    use serde_json::Value;
    match value {
        Value::String(text) => Ok(text.clone()),
        Value::Number(number) => Ok(number.to_string()),
        Value::Bool(flag) => Ok(flag.to_string()),
        Value::Null => Err("null"),
        Value::Array(_) => Err("an array"),
        Value::Object(_) => Err("an object"),
    }
}

fn content_type(response: &Response) -> Option<&str> {
    response
        .headers
        .iter()
        .find(|(name, _)| name.eq_ignore_ascii_case("content-type"))
        .map(|(_, value)| value.as_str())
}

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

    use std::time::Duration;

    fn response(headers: &[(&str, &str)], body: &str) -> Response {
        Response {
            status: 200,
            status_text: "OK".to_string(),
            headers: headers
                .iter()
                .map(|(name, value)| (name.to_string(), value.to_string()))
                .collect(),
            body: body.to_string(),
            elapsed: Duration::from_millis(1),
            redirects: Vec::new(),
        }
    }

    fn json_response() -> Response {
        response(
            &[("content-type", "application/json")],
            r#"{"token": "abc123", "user": {"id": 42, "admin": true}, "tags": ["a", "b"],
                "price": 1.50, "nothing": null}"#,
        )
    }

    fn captures(yaml: &str) -> Captures {
        serde_yaml::from_str(yaml).expect("test capture block should parse")
    }

    /// The report for `yaml` against `json_response`, with no environment to
    /// collide with.
    fn report(yaml: &str) -> CaptureReport {
        captures(yaml).evaluate(&json_response(), &Environment::default())
    }

    fn only(report: &CaptureReport) -> &CaptureResult {
        assert_eq!(report.len(), 1, "expected one result: {report:?}");
        &report.results()[0]
    }

    #[test]
    fn captures_a_string_without_its_json_quotes() {
        let report = report("auth_token: $.token\n");
        assert_eq!(only(&report).value(), Some("abc123"));
        assert!(report.passed());
        assert_eq!(
            report.values(),
            BTreeMap::from([("auth_token".to_string(), "abc123".to_string())])
        );
    }

    #[test]
    fn captures_numbers_and_booleans_as_their_value_not_their_spelling() {
        // `1.50` in the body captures as `1.5`: the body was parsed into an
        // `f64` before this saw it, and pinning that here is what stops the
        // documented behaviour and the real one drifting apart.
        let report = report("id: $.user.id\nadmin: $.user.admin\nprice: $.price\n");
        assert_eq!(
            report.values(),
            BTreeMap::from([
                ("admin".to_string(), "true".to_string()),
                ("id".to_string(), "42".to_string()),
                ("price".to_string(), "1.5".to_string()),
            ])
        );
    }

    #[test]
    fn a_path_that_matches_nothing_is_a_reported_failure() {
        let report = report("missing: $.nope\n");
        assert!(!report.passed());
        assert_eq!(only(&report).failure(), Some(&CaptureFailure::NoMatch));
        assert_eq!(only(&report).value(), None);
        assert!(report.values().is_empty(), "nothing is defined by a miss");
        assert!(
            only(&report)
                .failure()
                .unwrap()
                .to_string()
                .contains("matched nothing"),
            "the message is the one a user reads"
        );
    }

    #[test]
    fn a_path_matching_several_values_is_ambiguous_rather_than_first_wins() {
        let report = report("tag: $.tags[*]\n");
        match only(&report).failure() {
            Some(CaptureFailure::Ambiguous { count, sample }) => {
                assert_eq!(*count, 2);
                assert_eq!(sample, &[r#""a""#.to_string(), r#""b""#.to_string()]);
            }
            other => panic!("expected Ambiguous, got {other:?}"),
        }
    }

    #[test]
    fn null_arrays_and_objects_have_no_text_form_to_substitute() {
        for (path, kind) in [
            ("$.nothing", "null"),
            ("$.tags", "an array"),
            ("$.user", "an object"),
        ] {
            let report = report(&format!("v: {path}\n"));
            assert_eq!(
                only(&report).failure(),
                Some(&CaptureFailure::NotAScalar { kind }),
                "{path} should not capture"
            );
        }
    }

    #[test]
    fn a_body_that_is_not_json_reports_the_parser_message_and_the_content_type() {
        let captures = captures("v: $.token\n");
        let report = captures.evaluate(
            &response(&[("content-type", "text/html")], "<html></html>"),
            &Environment::default(),
        );
        match only(&report).failure() {
            Some(CaptureFailure::BodyNotJson {
                reason,
                content_type,
            }) => {
                assert!(!reason.is_empty());
                assert_eq!(content_type.as_deref(), Some("text/html"));
            }
            other => panic!("expected BodyNotJson, got {other:?}"),
        }
    }

    #[test]
    fn a_body_with_no_content_type_says_so_rather_than_naming_one() {
        let report =
            captures("v: $.token\n").evaluate(&response(&[], "not json"), &Environment::default());
        let message = only(&report).failure().unwrap().to_string();
        assert!(message.contains("no content-type header"), "got {message}");
    }

    #[test]
    fn a_path_that_is_not_a_json_path_is_told_apart_from_one_that_missed() {
        let report = report("v: not a path\n");
        assert!(
            matches!(
                only(&report).failure(),
                Some(CaptureFailure::InvalidPath { .. })
            ),
            "got {:?}",
            only(&report).failure()
        );
    }

    #[test]
    fn a_name_the_environment_already_defines_is_refused_rather_than_shadowing_it() {
        // The precedence decision, at the point it is made: neither value
        // silently wins, because the same `{{auth_token}}` would otherwise mean
        // the environment's value before this request and the captured one
        // after it.
        let environment = Environment::from_yaml_str("auth_token: from-the-file\n").unwrap();
        let report = captures("auth_token: $.token\n").evaluate(&json_response(), &environment);

        assert!(!report.passed());
        assert!(
            matches!(
                only(&report).failure(),
                Some(CaptureFailure::Shadowed { .. })
            ),
            "got {:?}",
            only(&report).failure()
        );
        assert!(
            report.values().is_empty(),
            "a refused capture defines nothing, so the environment's value stands"
        );
    }

    #[test]
    fn a_collision_is_checked_before_the_path_is_even_read() {
        // A shadowed name is wrong about every response there could be, so it
        // is the failure worth reporting even when the path is also broken.
        let environment = Environment::from_yaml_str("v: x\n").unwrap();
        let report = captures("v: not a path\n").evaluate(&json_response(), &environment);
        assert!(
            matches!(
                only(&report).failure(),
                Some(CaptureFailure::Shadowed { .. })
            ),
            "got {:?}",
            only(&report).failure()
        );
    }

    #[test]
    fn one_entry_failing_does_not_stop_the_others() {
        let report = report("good: $.token\nbad: $.nope\nalso_good: $.user.id\n");
        assert_eq!(report.len(), 3, "one result per entry, always");
        assert_eq!(report.captured_count(), 2);
        assert_eq!(report.failed_count(), 1);
        assert_eq!(report.failures().count(), 1);
        assert_eq!(
            report.values(),
            BTreeMap::from([
                ("also_good".to_string(), "42".to_string()),
                ("good".to_string(), "abc123".to_string()),
            ])
        );
    }

    #[test]
    fn an_empty_block_captures_nothing_and_reports_nothing() {
        let report = captures("{}\n").evaluate(&json_response(), &Environment::default());
        assert!(report.is_empty());
        assert!(report.passed(), "vacuously");
        assert!(report.values().is_empty());
    }

    // --- header and status capture ------------------------------------------

    #[test]
    fn a_bare_string_still_means_a_json_path_unchanged() {
        // The regression this whole section guards against: `entries()` used
        // to map straight to a path `String`; it now maps to a
        // `CaptureSource`, and a bare-string entry must still deserialise to
        // `JsonPath` holding that exact text, byte for byte.
        let parsed = captures("auth_token: $.token\n");
        assert_eq!(
            parsed.entries()["auth_token"],
            CaptureSource::JsonPath("$.token".to_string())
        );

        let report = report("auth_token: $.token\nuser_id: $.user.id\n");
        assert_eq!(
            report.values(),
            BTreeMap::from([
                ("auth_token".to_string(), "abc123".to_string()),
                ("user_id".to_string(), "42".to_string()),
            ])
        );
        // The label shown in a report is the path text, unchanged, for
        // `--json` output and everything else that reads `CaptureResult::path`.
        assert_eq!(
            only(&captures("v: $.token\n").evaluate(&json_response(), &Environment::default()))
                .path,
            "$.token"
        );
    }

    #[test]
    fn captures_a_response_header_case_insensitively() {
        let response = response(&[("X-Request-Id", "abc-123")], "{}");
        let report =
            captures("id: { header: x-request-id }\n").evaluate(&response, &Environment::default());
        assert_eq!(only(&report).value(), Some("abc-123"));
        assert!(report.passed());
    }

    #[test]
    fn a_missing_header_is_a_reported_failure_naming_what_is_there() {
        let response = response(&[("Content-Type", "application/json")], "{}");
        let report =
            captures("id: { header: x-request-id }\n").evaluate(&response, &Environment::default());
        match only(&report).failure() {
            Some(CaptureFailure::HeaderNotFound { header, present }) => {
                assert_eq!(header, "x-request-id");
                assert_eq!(present, &["Content-Type".to_string()]);
            }
            other => panic!("expected HeaderNotFound, got {other:?}"),
        }
        let message = only(&report).failure().unwrap().to_string();
        assert!(message.contains("Content-Type"), "got {message}");
    }

    #[test]
    fn a_repeated_header_is_ambiguous_rather_than_first_or_last_wins() {
        // Same philosophy as a JSON path matching several values: a capture
        // binds a name to one value, and picking silently between repeats
        // would make the same file behave differently depending on header
        // order. This deliberately differs from how `assertions` treats a
        // repeated header (passes if any value matches) because an
        // assertion checks a predicate and a capture commits to an identity.
        let response = response(&[("Set-Cookie", "a=1"), ("Set-Cookie", "b=2")], "{}");
        let report = captures("session: { header: Set-Cookie }\n")
            .evaluate(&response, &Environment::default());
        match only(&report).failure() {
            Some(CaptureFailure::Ambiguous { count, sample }) => {
                assert_eq!(*count, 2);
                assert_eq!(sample, &["a=1".to_string(), "b=2".to_string()]);
            }
            other => panic!("expected Ambiguous, got {other:?}"),
        }
        assert!(report.values().is_empty());
    }

    #[test]
    fn captures_the_status_code_as_a_string() {
        let response = response(&[], "{}");
        let report =
            captures("code: { status: true }\n").evaluate(&response, &Environment::default());
        assert_eq!(only(&report).value(), Some("200"));
        assert!(report.passed());
    }

    #[test]
    fn status_false_is_rejected_when_the_file_is_loaded() {
        // A structural nonsense, not a fact about any particular response —
        // rejected at parse time, the same call `follow_redirects: -1` makes,
        // rather than surfacing as a per-response capture failure.
        let err = serde_yaml::from_str::<Captures>("code: { status: false }\n").unwrap_err();
        assert!(err.to_string().contains("status: false"), "got {err}");
    }

    #[test]
    fn an_object_capture_with_neither_header_nor_status_fails_to_parse() {
        let err = serde_yaml::from_str::<Captures>("v: { nonsense: true }\n").unwrap_err();
        // Not asserting exact wording (that's serde's untagged-enum message),
        // only that the file does not load silently with an empty source.
        assert!(!err.to_string().is_empty());
    }

    #[test]
    fn header_and_status_capture_are_shadowed_the_same_as_json_path() {
        let environment = Environment::from_yaml_str("session: from-the-file\n").unwrap();
        let response = response(&[("Set-Cookie", "a=1")], "{}");
        let report =
            captures("session: { header: Set-Cookie }\n").evaluate(&response, &environment);
        assert!(
            matches!(
                only(&report).failure(),
                Some(CaptureFailure::Shadowed { .. })
            ),
            "got {:?}",
            only(&report).failure()
        );
    }

    #[test]
    fn a_capture_block_mixing_all_three_sources_evaluates_each_independently() {
        let response = response(&[("X-Trace-Id", "trace-1")], r#"{"token": "abc123"}"#);
        let report = captures(
            "auth_token: $.token\ntrace: { header: x-trace-id }\ncode: { status: true }\n",
        )
        .evaluate(&response, &Environment::default());
        assert_eq!(report.len(), 3);
        assert!(report.passed());
        assert_eq!(
            report.values(),
            BTreeMap::from([
                ("auth_token".to_string(), "abc123".to_string()),
                ("trace".to_string(), "trace-1".to_string()),
                ("code".to_string(), "200".to_string()),
            ])
        );
    }
}