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
/// Create a `TestRequest` using a DSL that looks kinda like on-the-wire HTTP/1.x requests.
///
/// # Examples
/// ```
/// use actix_web::test::TestRequest;
/// use actix_web_lab::test_request;
///
/// let _req: TestRequest = test_request! {
///     POST "/";
///     "Origin" => "example.com"
///     "Access-Control-Request-Method" => "POST"
///     "Access-Control-Request-Headers" => "Content-Type, X-CSRF-TOKEN";
///     @json {"abc": "123"}
/// };
///
/// let _req: TestRequest = test_request! {
///     POST "/";
///     "Content-Type" => "application/json"
///     "Origin" => "example.com"
///     "Access-Control-Request-Method" => "POST"
///     "Access-Control-Request-Headers" => "Content-Type, X-CSRF-TOKEN";
///     @raw r#"{"abc": "123"}"#
/// };
/// ```
#[macro_export]
macro_rules! test_request {
    ($method:ident $uri:expr) => {{
        ::actix_web::test::TestRequest::default()
            .method(::actix_web::http::Method::$method)
            .uri($uri)
    }};

    ($method:ident $uri:expr; $($hdr_name:expr => $hdr_val:expr)+) => {{
        test_request!($method $uri)
            $(
                .insert_header(($hdr_name, $hdr_val))
            )+
    }};

    ($method:ident $uri:expr; $($hdr_name:expr => $hdr_val:expr)+; @json $payload:tt) => {{
        test_request!($method $uri; $($hdr_name => $hdr_val)+)
            .set_json($crate::__reexports::serde_json::json!($payload))
    }};

    ($method:ident $uri:expr; $($hdr_name:expr => $hdr_val:expr)+; @raw $payload:expr) => {{
        test_request!($method $uri; $($hdr_name => $hdr_val)+)
            .set_payload($payload)
    }};
}

pub use test_request;

#[cfg(test)]
mod tests {
    use actix_web::test::TestRequest;

    use super::*;

    #[test]
    fn request_builder() {
        let _req: TestRequest = test_request! {
            POST "/";
            "Origin" => "example.com"
            "Access-Control-Request-Method" => "POST"
            "Access-Control-Request-Headers" => "Content-Type, X-CSRF-TOKEN";
            @json { "abc": "123" }
        };

        let _req: TestRequest = test_request! {
            POST "/";
            "Content-Type" => "application/json"
            "Origin" => "example.com"
            "Access-Control-Request-Method" => "POST"
            "Access-Control-Request-Headers" => "Content-Type, X-CSRF-TOKEN";
            @raw r#"{"abc": "123"}"#
        };
    }
}