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
use reqwest::header::HeaderMap;
use reqwest::Method;
#[cfg(test)]
use serde_json::Value;

use crate::request_def::body::Body;
use crate::response_handler::ResponseHandler;

#[derive(Debug, PartialEq, Eq)]
pub struct Request {
    pub method: Method,
    pub url: String,
    pub headers: HeaderMap,
    pub body: Body,
    pub response_handler: Option<ResponseHandler>,
}

#[cfg(test)]
impl Request {
    pub fn basic(
        method: &'static str,
        url: &'static str
    ) -> Self {
        use std::str::FromStr;

        Request {
            method: Method::from_str(method).unwrap(),
            url: url.to_owned(),
            headers: HeaderMap::new(),
            body: Body::Plain(String::new()),
            response_handler: None,
        }
    }

    pub fn add_header(
        mut self,
        name: &'static str,
        value: &'static str,
    ) -> Self {
        use std::str::FromStr;
        use reqwest::header::{HeaderName, HeaderValue};

        self.headers.insert(
            HeaderName::from_str(name).unwrap(),
            HeaderValue::from_str(value).unwrap()
        );

        self
    }

    pub fn body(
        mut self,
        body: &'static str,
    ) -> Self {
        self.body = Body::Plain(body.to_owned());

        self
    }

    pub fn gql_body(
        mut self,
        body: Value,
    ) -> Self {
        self.body = Body::Plain(
            serde_json::to_string(&body).unwrap()
        );

        self
    }

    pub fn file_body(
        mut self,
        files: &[(&str, &str)],
    ) -> Self {
        use crate::request_def::body::File;
        use crate::test_utils::root;

        self.body = Body::Files(
            files.into_iter()
                .map(|it| (it.0.to_owned(), it.1))
                .map(|(name, path)| (name, root().join(path)))
                .map(|(name, path)| File { name, path })
                .collect()
        );

        self
    }

    pub fn response_handler_json(
        mut self,
        handler: &'static str,
    ) -> Self {
        self.response_handler = Some(ResponseHandler::Json { json_path: handler.to_owned(), });

        self
    }
}