httpmock 0.9.0

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

use bytes::Bytes;
#[cfg(feature = "cookies")]
use headers::{Cookie, HeaderMapExt};
use serde::{Deserialize, Serialize};
use serde_json::Value;

pub type ResponseCallback = Arc<dyn Fn(&HttpMockRequest) -> HttpMockResponse + Send + Sync>;
pub type RequestPredicate = Arc<dyn Fn(&HttpMockRequest) -> bool + Send + Sync>;

use crate::{
    common::util::HttpMockBytes,
    server::{RequestMetadata, matchers::generic::MatchingStrategy},
};

#[derive(thiserror::Error, Debug)]
pub enum Error {
    #[error("Cannot deserialize header: {0}")]
    HeaderDeserialization(String),
    #[error("cannot convert to/from static mock: {0}")]
    StaticMockConversion(String),
    #[error("Cannot convert request to/from internal structure: {0}")]
    RequestConversion(String),
    #[error("Response conversion error: {0}")]
    ResponseConversion(String),
}

/// A general abstraction of an HTTP request of `httpmock`.
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct HttpMockRequest {
    scheme: String,
    uri: String,
    method: String,
    headers: Vec<(String, String)>,
    version: String,
    body: HttpMockBytes,
}

impl HttpMockRequest {
    pub(crate) fn new(
        scheme: String,
        uri: String,
        method: String,
        headers: Vec<(String, String)>,
        version: String,
        body: HttpMockBytes,
    ) -> Self {
        // TODO: Many fields from the struct are exposed as structures from http package to the user.
        //  These values here are also converted to these http crate structures every call.
        //  ==> Convert these values here into http crate structures and allow returning an error
        //      here instead of "unwrap" all the time later (see functions below).
        //      Convert into http crate structures once here and store the converted
        //          values in the struct instance here rather than only String values everywhere.
        //     This will require to make the HttpMockRequest serde compatible
        //     (http types are not serializable by default).
        Self {
            scheme,
            uri,
            method,
            headers,
            version,
            body,
        }
    }

    /// Parses and returns the URI of the request.
    ///
    /// # Attention
    ///
    /// - This method returns the full URI of the request as an `http::Uri` object.
    /// - The URI returned by this method does not include the `Host` part. In HTTP/1.1,
    ///   the request line typically contains only the path and query, not the full URL with the host.
    /// - To retrieve the host, you should use the `HttpMockRequest::host` method which extracts the `Host`
    ///   header (for HTTP/1.1) or the `:authority` pseudo-header (for HTTP/2 and HTTP/3).
    ///
    /// # Returns
    ///
    /// An `http::Uri` object representing the full URI of the request.
    pub fn uri(&self) -> http::Uri {
        self.uri.parse().unwrap()
    }

    /// Parses the scheme from the request.
    ///
    /// This function extracts the scheme (protocol) used in the request. If the request contains a relative path,
    /// the scheme will be inferred based on how the server received the request. For instance, if the request was
    /// sent to the server using HTTPS, the scheme will be set to "https"; otherwise, it will be set to "http".
    ///
    /// # Returns
    ///
    /// A `String` representing the scheme of the request, either "https" or "http".
    pub fn scheme(&self) -> String {
        let uri = self.uri();
        if let Some(scheme) = uri.scheme() {
            return scheme.to_string();
        }

        self.scheme.clone()
    }

    /// Returns the URI of the request as a string slice.
    ///
    /// # Attention
    ///
    /// - This method returns the full URI as a string slice.
    /// - The URI string returned by this method does not include the `Host` part. In HTTP/1.1,
    ///   the request line typically contains only the path and query, not the full URL with the host.
    /// - To retrieve the host, you should use the `host` method which extracts the `Host`
    ///   header (for HTTP/1.1) or the `:authority` pseudo-header (for HTTP/2 and HTTP/3).
    ///
    /// # Returns
    ///
    /// A string slice representing the full URI of the request.
    pub fn uri_str(&self) -> &str {
        self.uri.as_ref()
    }

    /// Returns the host that the request was sent to, based on the `Host` header or `:authority` pseudo-header.
    ///
    /// # Attention
    ///
    /// - This method retrieves the host from the `Host` header of the HTTP request for HTTP/1.1 requests.
    ///   For HTTP/2 and HTTP/3 requests, it retrieves the host from the `:authority` pseudo-header.
    /// - If you use the `HttpMockRequest::uri` method to get the full URI, note that
    ///   the URI might not include the host part. In HTTP/1.1, the request line
    ///   typically contains only the path and query, not the full URL.
    ///
    /// # Returns
    ///
    /// An `Option<String>` containing the host if the `Host` header or `:authority` pseudo-header is present, or
    /// `None` if neither is found.
    pub fn host(&self) -> Option<String> {
        // Check the Host header first (HTTP 1.1)
        if let Some((_, host)) = self.headers.iter().find(|(k, _)| k.eq_ignore_ascii_case("host")) {
            return Some(host.split(':').next().unwrap().to_string());
        }

        // If Host header is not found, check the URI authority (HTTP/2 and HTTP/3)
        let uri = self.uri();
        if let Some(authority) = uri.authority() {
            return Some(authority.as_str().split(':').next().unwrap().to_string());
        }

        None
    }

    /// Returns the port that the request was sent to, based on the `Host` header or `:authority` pseudo-header.
    ///
    /// # Attention
    ///
    /// 1. This method retrieves the port from the `Host` header of the HTTP request for HTTP/1.1 requests.
    ///    For HTTP/2 and HTTP/3 requests, it retrieves the port from the `:authority` pseudo-header.
    ///    This method attempts to parse the port as a `u16`. If the port cannot be parsed as a `u16`, this method will continue as if the port was not specified (see point 2).
    /// 2. If the port is not specified in the `Host` header or `:authority` pseudo-header, this method will return 443 (https) or 80 (http) based on the used scheme.
    ///
    /// # Returns
    ///
    /// An `u16` containing the port if the `Host` header or `:authority` pseudo-header is present and includes a valid port,
    /// or 443 (https) or 80 (http) based on the used scheme otherwise.
    pub fn port(&self) -> u16 {
        // Check the Host header first (HTTP 1.1)
        if let Some((_, host)) = self.headers.iter().find(|(k, _)| k.eq_ignore_ascii_case("host"))
            && let Some(port_str) = host.split(':').nth(1)
            && let Ok(port) = port_str.parse::<u16>()
        {
            return port;
        }

        // If Host header is not found, check the URI authority (HTTP/2 and HTTP/3)
        let uri = self.uri();
        if let Some(authority) = uri.authority()
            && let Some(port_str) = authority.as_str().split(':').nth(1)
            && let Ok(port) = port_str.parse::<u16>()
        {
            return port;
        }

        if self.scheme().eq("https") {
            return 443;
        }

        80
    }

    pub fn method(&self) -> http::Method {
        http::Method::from_bytes(self.method.as_bytes()).unwrap()
    }

    pub fn method_str(&self) -> &str {
        self.method.as_ref()
    }

    pub fn headers(&self) -> http::HeaderMap<http::HeaderValue> {
        let mut header_map: http::HeaderMap<http::HeaderValue> = http::HeaderMap::new();
        for (key, value) in &self.headers {
            let header_name = http::HeaderName::from_bytes(key.as_bytes()).unwrap();
            let header_value = http::HeaderValue::from_str(value).unwrap();

            header_map.append(header_name, header_value);
        }

        header_map
    }

    pub fn headers_vec(&self) -> &Vec<(String, String)> {
        self.headers.as_ref()
    }

    pub fn query_params(&self) -> Vec<(String, String)> {
        form_urlencoded::parse(self.uri().query().unwrap_or("").as_bytes())
            .into_owned()
            .collect()
    }

    /// Converts this request to an HTTP request with a byte body.
    pub fn to_http_request(&self) -> http::Request<Bytes> {
        self.into()
    }

    pub fn query_param_length(&self) -> usize {
        form_urlencoded::parse(self.uri().query().unwrap_or("").as_bytes()).count()
    }

    pub fn body(&self) -> &HttpMockBytes {
        &self.body
    }

    pub fn body_string(&self) -> String {
        self.body.to_string()
    }

    pub fn body_ref(&self) -> &[u8] {
        self.body.as_ref()
    }

    pub fn body_vec(&self) -> Vec<u8> {
        self.body.to_vec()
    }

    pub fn body_bytes(&self) -> bytes::Bytes {
        self.body.to_bytes()
    }

    pub fn version(&self) -> http::Version {
        match self.version.as_ref() {
            "HTTP/0.9" => http::Version::HTTP_09,
            "HTTP/1.0" => http::Version::HTTP_10,
            "HTTP/1.1" => http::Version::HTTP_11,
            "HTTP/2.0" => http::Version::HTTP_2,
            "HTTP/3.0" => http::Version::HTTP_3,
            // Attention: This scenario is highly unlikely, so we panic here for the users
            // convenience (user does not need to deal with errors for this reason alone).
            _ => panic!("unknown HTTP version: {:?}", self.version),
        }
    }

    pub fn version_ref(&self) -> &str {
        self.version.as_ref()
    }

    #[cfg(feature = "cookies")]
    pub(crate) fn cookies(&self) -> Result<Vec<(String, String)>, Error> {
        let mut result = Vec::new();

        if let Some(cookie) = self.headers().typed_get::<Cookie>() {
            for (key, value) in cookie.iter() {
                result.push((key.to_string(), value.to_string()));
            }
        }

        Ok(result)
    }
}

fn http_headers_to_vec<T>(req: &http::Request<T>) -> Result<Vec<(String, String)>, Error> {
    req.headers()
        .iter()
        .map(|(name, value)| {
            // Attempt to convert the HeaderValue to a &str, returning an error if it fails.
            let value_str = value.to_str().map_err(|e| Error::RequestConversion(e.to_string()))?;
            Ok((name.as_str().to_string(), value_str.to_string()))
        })
        .collect()
}

impl<B> TryFrom<&http::Request<B>> for HttpMockRequest
where
    B: Clone + Into<HttpMockBytes>,
{
    type Error = Error;

    fn try_from(value: &http::Request<B>) -> Result<Self, Self::Error> {
        let metadata = value
            .extensions()
            .get::<RequestMetadata>()
            .unwrap_or_else(|| panic!("request metadata was not added to the request"));

        let headers = http_headers_to_vec(value)?;

        let body = value.body().clone().into();

        Ok(HttpMockRequest::new(
            metadata.scheme.to_string(),
            value.uri().to_string(),
            value.method().to_string(),
            headers,
            format!("{:?}", value.version()),
            body,
        ))
    }
}

impl<B> From<http::Request<B>> for HttpMockRequest
where
    B: Into<HttpMockBytes>,
{
    fn from(req: http::Request<B>) -> Self {
        let scheme = req
            .extensions()
            .get::<RequestMetadata>()
            .expect("request metadata was not added to the request")
            .scheme
            .to_string();
        let headers = http_headers_to_vec(&req).expect("invalid headers in http::Request");
        let (parts, body) = req.into_parts();

        HttpMockRequest::new(
            scheme,
            parts.uri.to_string(),
            parts.method.to_string(),
            headers,
            format!("{:?}", parts.version),
            body.into(),
        )
    }
}

impl From<&HttpMockRequest> for http::Request<bytes::Bytes> {
    fn from(req: &HttpMockRequest) -> Self {
        let mut builder = http::Request::builder()
            .method(req.method())
            .uri(req.uri())
            .version(req.version());

        for (k, v) in req.headers() {
            builder = builder.header(k.map_or(String::new(), |v| v.to_string()), v)
        }

        builder
            .body(req.body().to_bytes())
            .expect("failed to convert HttpMockRequest into http::Request<Bytes>")
    }
}

impl From<&HttpMockRequest> for http::Request<String> {
    fn from(req: &HttpMockRequest) -> Self {
        let mut builder = http::Request::builder()
            .method(req.method())
            .uri(req.uri())
            .version(req.version());

        for (k, v) in req.headers() {
            builder = builder.header(k.map_or(String::new(), |v| v.to_string()), v)
        }

        let body = String::from_utf8(req.body_vec()).expect("request body is not valid UTF-8");
        builder
            .body(body)
            .expect("failed to convert HttpMockRequest into http::Request<String>")
    }
}

impl From<&HttpMockRequest> for http::Request<()> {
    fn from(req: &HttpMockRequest) -> Self {
        let mut builder = http::Request::builder()
            .method(req.method())
            .uri(req.uri())
            .version(req.version());

        for (k, v) in req.headers() {
            builder = builder.header(k.map_or(String::new(), |v| v.to_string()), v)
        }

        builder
            .body(())
            .expect("failed to convert HttpMockRequest into http::Request<()>")
    }
}

/// A general abstraction of an HTTP response for all handlers.
#[derive(Serialize, Deserialize, Clone)]
pub struct HttpMockResponse {
    pub status: Option<u16>,
    pub headers: Option<Vec<(String, String)>>,
    #[serde(default, with = "opt_vector_serde_base64")]
    pub body: Option<HttpMockBytes>,
}

impl HttpMockResponse {
    pub fn builder() -> HttpMockResponseBuilder {
        HttpMockResponseBuilder::new()
    }

    /// Converts this response to an HTTP response with a byte body.
    ///
    /// # Errors
    /// Returns an error if the status is missing or invalid, or a header is invalid.
    ///
    /// # Example
    /// ```
    /// use httpmock::HttpMockResponse;
    ///
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let response = HttpMockResponse::builder().status(200).body("hello").build();
    /// let http_response = response.to_http_response()?;
    /// assert_eq!(http_response.status(), 200);
    /// assert_eq!(http_response.body().as_ref(), b"hello");
    /// # Ok(())
    /// # }
    /// ```
    pub fn to_http_response(&self) -> Result<http::Response<Bytes>, Error> {
        http::Response::<Bytes>::try_from(self)
    }
}

/// Converts an `HttpMockResponse` into a real `http::Response<Bytes>`.
impl TryFrom<HttpMockResponse> for http::Response<bytes::Bytes> {
    type Error = Error;

    fn try_from(res: HttpMockResponse) -> Result<Self, Self::Error> {
        (&res).try_into() // reuse the by-ref impl
    }
}

impl TryFrom<&HttpMockResponse> for http::Response<bytes::Bytes> {
    type Error = Error;

    fn try_from(res: &HttpMockResponse) -> Result<Self, Self::Error> {
        let raw_status = res
            .status
            .ok_or_else(|| Error::ResponseConversion("missing status".into()))?;

        let status = http::StatusCode::from_u16(raw_status)
            .map_err(|_| Error::ResponseConversion(format!("invalid status: {}", raw_status)))?;

        let mut builder = http::Response::builder().status(status);

        if let Some(headers) = &res.headers {
            for (name, value) in headers {
                let header_name = http::header::HeaderName::try_from(name.clone())
                    .map_err(|_| Error::ResponseConversion(format!("invalid header name: {}", name)))?;

                let header_value = http::header::HeaderValue::try_from(value.clone()).map_err(|_| {
                    Error::ResponseConversion(format!("invalid header value for '{}': {}", name, value))
                })?;

                builder = builder.header(header_name, header_value);
            }
        }

        let body = res.body.as_ref().map_or(bytes::Bytes::new(), |b| b.0.clone());

        builder
            .body(body)
            .map_err(|e| Error::ResponseConversion(format!("http build error: {}", e)))
    }
}

impl<B> TryFrom<&http::Response<B>> for HttpMockResponse
where
    B: Clone + Into<HttpMockBytes>,
{
    type Error = Error;

    fn try_from(resp: &http::Response<B>) -> Result<Self, Self::Error> {
        // headers -> Vec<(String, String)> (UTF-8 strict)
        let mut headers = Vec::with_capacity(resp.headers().len());
        for (name, value) in resp.headers() {
            let name = name.as_str().to_string();
            let val = value
                .to_str()
                .map_err(|_| Error::ResponseConversion(format!("non-utf8 header value for '{}'", name)))?;
            headers.push((name, val.to_string()));
        }

        let body = resp.body().clone().into();

        Ok(HttpMockResponse {
            status: Some(resp.status().as_u16()),
            headers: Some(headers),
            body: Some(body),
        })
    }
}

impl<B> From<http::Response<B>> for HttpMockResponse
where
    B: Into<HttpMockBytes>,
{
    fn from(resp: http::Response<B>) -> Self {
        let (parts, body) = resp.into_parts();
        let headers = parts
            .headers
            .iter()
            .map(|(name, value)| {
                (
                    name.as_str().to_string(),
                    value
                        .to_str()
                        .unwrap_or_else(|_| panic!("non-UTF-8 value for response header '{name}'"))
                        .to_string(),
                )
            })
            .collect();

        Self {
            status: Some(parts.status.as_u16()),
            headers: Some(headers),
            body: Some(body.into()),
        }
    }
}

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

    struct NonCloneBody(&'static [u8]);

    impl From<NonCloneBody> for HttpMockBytes {
        fn from(body: NonCloneBody) -> Self {
            body.0.into()
        }
    }

    #[test]
    fn owned_message_conversions_accept_non_clone_bodies() {
        let mut request = http::Request::new(NonCloneBody(b"request"));
        request.extensions_mut().insert(RequestMetadata::new("http"));
        let request: HttpMockRequest = request.into();

        let response = http::Response::new(NonCloneBody(b"response"));
        let response: HttpMockResponse = response.into();

        assert_eq!(request.body().as_ref(), b"request");
        assert_eq!(response.body.as_ref().unwrap().as_ref(), b"response");
    }

    #[test]
    fn borrowed_message_conversions_still_accept_clone_bodies() {
        let mut request = http::Request::new(Vec::from(b"request"));
        request.extensions_mut().insert(RequestMetadata::new("http"));
        let request = HttpMockRequest::try_from(&request).unwrap();

        let response = http::Response::new(Vec::from(b"response"));
        let response = HttpMockResponse::try_from(&response).unwrap();

        assert_eq!(request.body().as_ref(), b"request");
        assert_eq!(response.body.as_ref().unwrap().as_ref(), b"response");
    }

    #[test]
    fn unit_is_an_empty_http_body() {
        let response: HttpMockResponse = http::Response::new(()).into();

        assert!(response.body.unwrap().is_empty());
    }
}

#[derive(Default, Debug, Clone)]
pub struct HttpMockResponseBuilder {
    status: Option<u16>,
    headers: Vec<(String, String)>,
    body: Option<HttpMockBytes>,
}

impl HttpMockResponseBuilder {
    pub fn new() -> Self {
        Self::default()
    }

    /// Set an HTTP status (e.g., 200, 404).
    pub fn status(mut self, status: u16) -> Self {
        self.status = Some(status);
        self
    }

    /// Add a single header (appends; duplicates are allowed).
    pub fn header<K, V>(mut self, key: K, val: V) -> Self
    where
        K: Into<String>,
        V: Into<String>,
    {
        self.headers.push((key.into(), val.into()));
        self
    }

    /// Replace all headers at once.
    pub fn headers<I, K, V>(mut self, headers: I) -> Self
    where
        I: IntoIterator<Item = (K, V)>,
        K: Into<String>,
        V: Into<String>,
    {
        self.headers = headers.into_iter().map(|(k, v)| (k.into(), v.into())).collect();
        self
    }

    /// Set a body from anything convertible into `HttpMockBytes`.
    pub fn body<B>(mut self, body: B) -> Self
    where
        B: Into<HttpMockBytes>,
    {
        self.body = Some(body.into());
        self
    }

    /// Explicitly clear the body.
    pub fn no_body(mut self) -> Self {
        self.body = None;
        self
    }

    /// Finalize into `HttpMockResponse`.
    pub fn build(self) -> HttpMockResponse {
        HttpMockResponse {
            status: self.status,
            headers: if self.headers.is_empty() {
                None
            } else {
                Some(self.headers)
            },
            body: self.body,
        }
    }
}

/// A general abstraction of an HTTP response for all handlers.
#[derive(Serialize, Deserialize, Clone, Default)]
pub struct MockServerHttpResponse {
    pub status: Option<u16>,
    pub headers: Option<Vec<(String, String)>>,
    #[serde(default, with = "opt_vector_serde_base64")]
    pub body: Option<HttpMockBytes>,
    pub delay: Option<u64>,
    #[serde(skip)]
    pub respond_with: Option<ResponseCallback>,
}

impl TryFrom<&http::Response<Bytes>> for MockServerHttpResponse {
    type Error = Error;

    fn try_from(value: &http::Response<Bytes>) -> Result<Self, Self::Error> {
        let mut headers = Vec::with_capacity(value.headers().len());

        for (key, value) in value.headers() {
            let value = value
                .to_str()
                .map_err(|err| Error::HeaderDeserialization(err.to_string()))?;

            headers.push((key.as_str().to_string(), value.to_string()))
        }

        Ok(Self {
            status: Some(value.status().as_u16()),
            headers: if !headers.is_empty() { Some(headers) } else { None },
            body: if !value.body().is_empty() {
                Some(HttpMockBytes::from(value.body().clone()))
            } else {
                None
            },
            delay: None,
            respond_with: None,
        })
    }
}

/// Serializes and deserializes the response body to/from a Base64 string.
mod opt_vector_serde_base64 {
    use base64::{Engine, engine::general_purpose::STANDARD as BASE64};
    use bytes::Bytes;
    use serde::{Deserialize, Deserializer, Serializer};

    use crate::common::util::HttpMockBytes;

    // See the following references:
    // https://github.com/serde-rs/serde/blob/master/serde/src/ser/impls.rs#L99
    // https://github.com/serde-rs/serde/issues/661
    pub fn serialize<T, S>(bytes: &Option<T>, serializer: S) -> Result<S::Ok, S::Error>
    where
        T: AsRef<[u8]>,
        S: Serializer,
    {
        match bytes {
            Some(value) => serializer.serialize_bytes(BASE64.encode(value).as_bytes()),
            None => serializer.serialize_none(),
        }
    }

    // See the following references:
    // https://github.com/serde-rs/serde/issues/1444
    pub fn deserialize<'de, D>(deserializer: D) -> Result<Option<HttpMockBytes>, D::Error>
    where
        D: Deserializer<'de>,
    {
        #[derive(Deserialize)]
        struct Wrapper(#[serde(deserialize_with = "from_base64")] HttpMockBytes);

        let v = Option::deserialize(deserializer)?;
        Ok(v.map(|Wrapper(a)| a))
    }

    fn from_base64<'de, D>(deserializer: D) -> Result<HttpMockBytes, D::Error>
    where
        D: Deserializer<'de>,
    {
        let value = Vec::deserialize(deserializer)?;
        let decoded = BASE64.decode(value).map_err(serde::de::Error::custom)?;
        Ok(HttpMockBytes::from(Bytes::from(decoded)))
    }
}

/// Prints the response body as UTF8 string
impl fmt::Debug for MockServerHttpResponse {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("MockServerHttpResponse")
            .field("status", &self.status)
            .field("headers", &self.headers)
            .field(
                "body",
                &self
                    .body
                    .as_ref()
                    .map(|x| String::from_utf8_lossy(x.as_ref()).to_string()),
            )
            .field("delay", &self.delay)
            .finish()
    }
}

/// (De)serializes a [`regex::Regex`] as its pattern string.
mod regex_string {
    use serde::{Deserialize, Deserializer, Serializer, de::Error};

    pub fn serialize<S: Serializer>(value: &regex::Regex, serializer: S) -> Result<S::Ok, S::Error> {
        serializer.serialize_str(value.as_str())
    }

    pub fn deserialize<'de, D: Deserializer<'de>>(deserializer: D) -> Result<regex::Regex, D::Error> {
        let pattern = std::borrow::Cow::<str>::deserialize(deserializer)?;
        pattern.parse().map_err(Error::custom)
    }
}

/// A general abstraction of an HTTP request for all handlers.
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct HttpMockRegex(#[serde(with = "regex_string")] pub regex::Regex);

impl Ord for HttpMockRegex {
    fn cmp(&self, other: &Self) -> Ordering {
        self.0.as_str().cmp(other.0.as_str())
    }
}

impl PartialOrd for HttpMockRegex {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

impl PartialEq for HttpMockRegex {
    fn eq(&self, other: &Self) -> bool {
        self.0.as_str() == other.0.as_str()
    }
}

impl Eq for HttpMockRegex {}

impl From<regex::Regex> for HttpMockRegex {
    fn from(value: regex::Regex) -> Self {
        HttpMockRegex(value)
    }
}

impl From<&str> for HttpMockRegex {
    fn from(value: &str) -> Self {
        let re = regex::Regex::from_str(value).expect("cannot parse value as regex");
        HttpMockRegex::from(re)
    }
}

impl From<String> for HttpMockRegex {
    fn from(value: String) -> Self {
        HttpMockRegex::from(value.as_str())
    }
}

impl fmt::Display for HttpMockRegex {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.0)
    }
}

/// A general abstraction of an HTTP request for all handlers.
#[derive(Serialize, Deserialize, Clone, Default)]
pub struct RequestRequirements {
    pub scheme: Option<String>,
    pub scheme_not: Option<String>, // NEW
    pub host: Option<String>,
    pub host_not: Option<Vec<String>>,        // NEW
    pub host_contains: Option<Vec<String>>,   // NEW
    pub host_excludes: Option<Vec<String>>,   // NEW
    pub host_prefix: Option<Vec<String>>,     // NEW
    pub host_suffix: Option<Vec<String>>,     // NEW
    pub host_prefix_not: Option<Vec<String>>, // NEW
    pub host_suffix_not: Option<Vec<String>>, // NEW
    pub host_matches: Option<Vec<HttpMockRegex>>,
    pub port: Option<u16>,
    pub port_not: Option<Vec<u16>>, // NEW
    pub method: Option<String>,
    pub method_not: Option<Vec<String>>, // NEW
    pub path: Option<String>,
    pub path_not: Option<Vec<String>>,        // NEW
    pub path_includes: Option<Vec<String>>,   // NEW
    pub path_excludes: Option<Vec<String>>,   // NEW
    pub path_prefix: Option<Vec<String>>,     // NEW
    pub path_suffix: Option<Vec<String>>,     // NEW
    pub path_prefix_not: Option<Vec<String>>, // NEW
    pub path_suffix_not: Option<Vec<String>>, // NEW
    pub path_matches: Option<Vec<HttpMockRegex>>,
    pub query_param: Option<Vec<(String, String)>>,
    pub query_param_not: Option<Vec<(String, String)>>, // NEW
    pub query_param_exists: Option<Vec<String>>,
    pub query_param_missing: Option<Vec<String>>,              // NEW
    pub query_param_includes: Option<Vec<(String, String)>>,   // NEW
    pub query_param_excludes: Option<Vec<(String, String)>>,   // NEW
    pub query_param_prefix: Option<Vec<(String, String)>>,     // NEW
    pub query_param_suffix: Option<Vec<(String, String)>>,     // NEW
    pub query_param_prefix_not: Option<Vec<(String, String)>>, // NEW
    pub query_param_suffix_not: Option<Vec<(String, String)>>, // NEW
    pub query_param_matches: Option<Vec<(HttpMockRegex, HttpMockRegex)>>, // NEW
    pub query_param_count: Option<Vec<(HttpMockRegex, HttpMockRegex, usize)>>, // NEW
    pub header: Option<Vec<(String, String)>>,                 // CHANGED from headers to header
    pub header_not: Option<Vec<(String, String)>>,             // NEW
    pub header_exists: Option<Vec<String>>,
    pub header_missing: Option<Vec<String>>,                              // NEW
    pub header_includes: Option<Vec<(String, String)>>,                   // NEW
    pub header_excludes: Option<Vec<(String, String)>>,                   // NEW
    pub header_prefix: Option<Vec<(String, String)>>,                     // NEW
    pub header_suffix: Option<Vec<(String, String)>>,                     // NEW
    pub header_prefix_not: Option<Vec<(String, String)>>,                 // NEW
    pub header_suffix_not: Option<Vec<(String, String)>>,                 // NEW
    pub header_matches: Option<Vec<(HttpMockRegex, HttpMockRegex)>>,      // NEW
    pub header_count: Option<Vec<(HttpMockRegex, HttpMockRegex, usize)>>, // NEW
    pub cookie: Option<Vec<(String, String)>>,                            // CHANGED from cookies to cookie
    pub cookie_not: Option<Vec<(String, String)>>,                        // NEW
    pub cookie_exists: Option<Vec<String>>,
    pub cookie_missing: Option<Vec<String>>,                              // NEW
    pub cookie_includes: Option<Vec<(String, String)>>,                   // NEW
    pub cookie_excludes: Option<Vec<(String, String)>>,                   // NEW
    pub cookie_prefix: Option<Vec<(String, String)>>,                     // NEW
    pub cookie_suffix: Option<Vec<(String, String)>>,                     // NEW
    pub cookie_prefix_not: Option<Vec<(String, String)>>,                 // NEW
    pub cookie_suffix_not: Option<Vec<(String, String)>>,                 // NEW
    pub cookie_matches: Option<Vec<(HttpMockRegex, HttpMockRegex)>>,      // NEW
    pub cookie_count: Option<Vec<(HttpMockRegex, HttpMockRegex, usize)>>, // NEW          // NEW
    pub body: Option<HttpMockBytes>,
    pub body_not: Option<Vec<HttpMockBytes>>,        // NEW
    pub body_includes: Option<Vec<HttpMockBytes>>,   // CHANG
    pub body_excludes: Option<Vec<HttpMockBytes>>,   // NEW
    pub body_prefix: Option<Vec<HttpMockBytes>>,     // NEW
    pub body_suffix: Option<Vec<HttpMockBytes>>,     // NEW
    pub body_prefix_not: Option<Vec<HttpMockBytes>>, //
    pub body_suffix_not: Option<Vec<HttpMockBytes>>, //
    pub body_matches: Option<Vec<HttpMockRegex>>,    // NEW
    pub json_body: Option<Value>,
    pub json_body_not: Option<Value>, // NEW
    pub json_body_includes: Option<Vec<Value>>,
    pub json_body_excludes: Option<Vec<Value>>, // NEW
    pub form_urlencoded_tuple: Option<Vec<(String, String)>>,
    pub form_urlencoded_tuple_not: Option<Vec<(String, String)>>, // NEW
    pub form_urlencoded_tuple_exists: Option<Vec<String>>,
    pub form_urlencoded_tuple_missing: Option<Vec<String>>, // NEW
    pub form_urlencoded_tuple_includes: Option<Vec<(String, String)>>, // NEW
    pub form_urlencoded_tuple_excludes: Option<Vec<(String, String)>>, // NEW
    pub form_urlencoded_tuple_prefix: Option<Vec<(String, String)>>, // NEW
    pub form_urlencoded_tuple_suffix: Option<Vec<(String, String)>>, // NEW
    pub form_urlencoded_tuple_prefix_not: Option<Vec<(String, String)>>, // NEW
    pub form_urlencoded_tuple_suffix_not: Option<Vec<(String, String)>>, // NEW
    pub form_urlencoded_tuple_matches: Option<Vec<(HttpMockRegex, HttpMockRegex)>>, // NEW
    pub form_urlencoded_tuple_count: Option<Vec<(HttpMockRegex, HttpMockRegex, usize)>>, // NEW
    #[serde(skip)]
    pub is_true: Option<Vec<RequestPredicate>>, // NEW + DEPRECATE matches() -> point to using "is_true" instead
    #[serde(skip)]
    pub is_false: Option<Vec<RequestPredicate>>, // NEW
}

/// A Request that is made to set a new mock.
#[derive(Serialize, Deserialize, Clone)]
pub struct MockDefinition {
    pub request: RequestRequirements,
    pub response: MockServerHttpResponse,
    /// The number of calls after which the mock stops matching requests, if any. The server
    /// validates it and moves it to [`ActiveMock::up_to_n_times`] when adding the mock.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub up_to_n_times: Option<usize>,
}

#[derive(Serialize, Deserialize, Clone)]
pub struct ActiveMock {
    pub id: usize,
    pub call_counter: usize,
    pub definition: MockDefinition,
    pub is_static: bool,
    /// The validated limit on the number of calls the mock serves, if any. Clients use its
    /// presence to detect servers that do not support the limit.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub up_to_n_times: Option<NonZero<usize>>,
}

impl ActiveMock {
    /// Returns whether the mock has served all the calls it is allowed to serve.
    pub fn is_exhausted(&self) -> bool {
        self.up_to_n_times.is_some_and(|limit| self.call_counter >= limit.get())
    }
}

/// A request to limit the number of calls an existing mock serves.
#[derive(Serialize, Deserialize, Clone)]
pub struct UpToNTimesConfig {
    pub up_to_n_times: usize,
}

#[cfg(feature = "proxy")]
#[derive(Serialize, Deserialize, Clone)]
pub struct ActiveForwardingRule {
    pub id: usize,
    pub config: ForwardingRuleConfig,
}

#[cfg(feature = "proxy")]
#[derive(Serialize, Deserialize, Clone)]
pub struct ActiveProxyRule {
    pub id: usize,
    pub config: ProxyRuleConfig,
}

#[cfg(feature = "record")]
#[derive(Serialize, Deserialize, Clone)]
pub struct ActiveRecording {
    pub id: usize,
    pub config: RecordingRuleConfig,
    pub mocks: Vec<MockDefinition>,
}

#[derive(Serialize, Deserialize)]
pub struct ClosestMatch {
    pub request: HttpMockRequest,
    pub request_index: usize,
    pub mismatches: Vec<Mismatch>,
}

#[derive(Serialize, Deserialize)]
pub struct ErrorResponse {
    pub message: String,
}

impl ErrorResponse {
    pub fn new<T>(message: &T) -> ErrorResponse
    where
        T: ToString,
    {
        ErrorResponse {
            message: message.to_string(),
        }
    }
}

// *************************************************************************************************
// Diff and Change correspond to difference::Changeset and Difference structs. They are duplicated
// here only for the reason to make them serializable/deserializable using serde.
// *************************************************************************************************
#[derive(PartialEq, Debug, Serialize, Deserialize)]
pub enum Diff {
    Same(String),
    Add(String),
    Rem(String),
}

#[derive(Debug, Serialize, Deserialize)]
pub struct DiffResult {
    pub differences: Vec<Diff>,
    pub distance: f32,
    pub tokenizer: Tokenizer,
}

#[derive(PartialEq, Debug, Serialize, Deserialize, Clone, Copy)]
pub enum Tokenizer {
    Line,
    Word,
    Character,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct KeyValueComparisonKeyValuePair {
    pub key: String,
    pub value: Option<String>,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct KeyValueComparisonAttribute {
    pub operator: String,
    pub expected: String,
    pub actual: Option<String>,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct KeyValueComparison {
    pub key: Option<KeyValueComparisonAttribute>,
    pub value: Option<KeyValueComparisonAttribute>,
    pub expected_count: Option<usize>,
    pub actual_count: Option<usize>,
    pub all: Vec<KeyValueComparisonKeyValuePair>,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct FunctionComparison {
    pub index: usize,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct SingleValueComparison {
    pub operator: String,
    pub expected: String,
    pub actual: String,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct Mismatch {
    pub entity: String,
    pub matcher_method: String,
    pub comparison: Option<SingleValueComparison>,
    pub key_value_comparison: Option<KeyValueComparison>,
    pub function_comparison: Option<FunctionComparison>,
    pub matching_strategy: Option<MatchingStrategy>,
    pub best_match: bool,
    pub diff: Option<DiffResult>,
}

// *************************************************************************************************
// Configs and Builders
// *************************************************************************************************

#[cfg(feature = "record")]
#[derive(Serialize, Deserialize, Clone, Default)]
pub struct RecordingRuleConfig {
    pub request_requirements: RequestRequirements,
    pub record_headers: Vec<String>,
    pub record_response_delays: bool,
}

#[cfg(feature = "proxy")]
#[derive(Serialize, Deserialize, Clone, Default)]
pub struct ProxyRuleConfig {
    pub request_requirements: RequestRequirements,
    pub request_header: Vec<(String, String)>,
}

#[cfg(feature = "proxy")]
#[derive(Serialize, Deserialize, Clone, Default)]
pub struct ForwardingRuleConfig {
    pub target_base_url: String,
    pub request_requirements: RequestRequirements,
    pub request_header: Vec<(String, String)>,
}

/// Represents an HTTP method.
#[derive(Serialize, Deserialize, Debug)]
pub enum Method {
    GET,
    HEAD,
    POST,
    PUT,
    DELETE,
    CONNECT,
    OPTIONS,
    TRACE,
    PATCH,
}

impl PartialEq<Method> for http::method::Method {
    fn eq(&self, other: &Method) -> bool {
        self.to_string().to_uppercase() == other.to_string().to_uppercase()
    }
}

impl FromStr for Method {
    type Err = String;

    fn from_str(input: &str) -> Result<Self, Self::Err> {
        match input.to_uppercase().as_str() {
            "GET" => Ok(Method::GET),
            "HEAD" => Ok(Method::HEAD),
            "POST" => Ok(Method::POST),
            "PUT" => Ok(Method::PUT),
            "DELETE" => Ok(Method::DELETE),
            "CONNECT" => Ok(Method::CONNECT),
            "OPTIONS" => Ok(Method::OPTIONS),
            "TRACE" => Ok(Method::TRACE),
            "PATCH" => Ok(Method::PATCH),
            _ => Err(format!("Invalid HTTP method {}", input)),
        }
    }
}

impl From<&str> for Method {
    fn from(value: &str) -> Self {
        value
            .parse()
            .unwrap_or_else(|error| panic!("Cannot parse HTTP method from string {:?}: {:?}", value, error))
    }
}

impl std::fmt::Display for Method {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        std::fmt::Debug::fmt(self, f)
    }
}