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
//! Traits describing parts of the `reqwest` library, so that we can override
//! them in tests.
//!
//! You do not need to care about this module
//! if you just want to use this crate.
use std::error;
use std::fmt;
use std::io;

use reqwest;

/// Represents the result of sending an HTTP request.
///
/// Modelled after `reqwest::Response`.
pub trait HttpResponse: io::Read + fmt::Debug
where
    Self: ::std::marker::Sized,
{
    /// Obtain access to the headers of the response.
    fn headers(&self) -> &reqwest::header::HeaderMap;

    /// Obtain a copy of the response's status.
    fn status(&self) -> reqwest::StatusCode;

    /// Return an error if the response's status is in the range 400-599.
    fn error_for_status(self) -> Result<Self, Box<error::Error>>;
}

impl HttpResponse for reqwest::Response {
    fn headers(&self) -> &reqwest::header::HeaderMap {
        self.headers()
    }
    fn status(&self) -> reqwest::StatusCode {
        self.status()
    }
    fn error_for_status(self) -> Result<Self, Box<error::Error>> {
        Ok(self.error_for_status()?)
    }
}

/// Represents a thing that can send requests.
///
/// Modelled after `reqwest::Client`.
pub trait Client {
    /// Sending a request produces this kind of response.
    type Response: HttpResponse;

    /// Send the given request and return the response (or an error).
    fn execute(
        &self,
        request: reqwest::Request,
    ) -> Result<Self::Response, Box<error::Error>>;
}

impl Client for reqwest::Client {
    type Response = reqwest::Response;

    fn execute(
        &self,
        request: reqwest::Request,
    ) -> Result<Self::Response, Box<error::Error>> {
        Ok(self.execute(request)?)
    }
}

#[cfg(test)]
pub mod tests {
    use reqwest;

    use std::cell;
    use std::fmt;
    use std::io;

    use std::error::Error;
    use std::io::Read;

    #[derive(Debug, Eq, PartialEq, Hash)]
    pub struct FakeError;

    impl fmt::Display for FakeError {
        fn fmt(
            &self,
            f: &mut ::std::fmt::Formatter,
        ) -> Result<(), ::std::fmt::Error> {
            f.write_str("FakeError")?;
            Ok(())
        }
    }

    impl Error for FakeError {
        fn description(&self) -> &str {
            "Something Ooo occurred"
        }
        fn cause(&self) -> Option<&Error> {
            None
        }
    }

    #[derive(Clone, Debug)]
    pub struct FakeResponse {
        pub status: reqwest::StatusCode,
        pub headers: reqwest::header::HeaderMap,
        pub body: io::Cursor<Vec<u8>>,
    }

    impl super::HttpResponse for FakeResponse {
        fn headers(&self) -> &reqwest::header::HeaderMap {
            &self.headers
        }
        fn status(&self) -> reqwest::StatusCode {
            self.status
        }
        fn error_for_status(self) -> Result<Self, Box<Error>> {
            if !self.status.is_client_error() && !self.status.is_server_error()
            {
                Ok(self)
            } else {
                Err(Box::new(FakeError))
            }
        }
    }

    impl Read for FakeResponse {
        fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
            self.body.read(buf)
        }
    }

    pub struct FakeClient {
        pub expected_url: reqwest::Url,
        pub expected_headers: reqwest::header::HeaderMap,
        pub response: FakeResponse,
        called: cell::Cell<bool>,
    }

    impl FakeClient {
        pub fn new(
            expected_url: reqwest::Url,
            expected_headers: reqwest::header::HeaderMap,
            response: FakeResponse,
        ) -> FakeClient {
            let called = cell::Cell::new(false);
            FakeClient {
                expected_url,
                expected_headers,
                response,
                called,
            }
        }

        pub fn assert_called(self) {
            assert_eq!(self.called.get(), true);
        }
    }

    impl super::Client for FakeClient {
        type Response = FakeResponse;

        fn execute(
            &self,
            request: reqwest::Request,
        ) -> Result<Self::Response, Box<Error>> {
            assert_eq!(request.method(), &reqwest::Method::GET);
            assert_eq!(request.url(), &self.expected_url);
            assert_eq!(request.headers(), &self.expected_headers);

            self.called.set(true);

            Ok(self.response.clone())
        }
    }

    pub struct BrokenClient<F>
    where
        F: Fn() -> Box<Error>,
    {
        pub expected_url: reqwest::Url,
        pub expected_headers: reqwest::header::HeaderMap,
        pub make_error: F,
        called: cell::Cell<bool>,
    }

    impl<F> BrokenClient<F>
    where
        F: Fn() -> Box<Error>,
    {
        pub fn new(
            expected_url: reqwest::Url,
            expected_headers: reqwest::header::HeaderMap,
            make_error: F,
        ) -> BrokenClient<F> {
            let called = cell::Cell::new(false);
            BrokenClient {
                expected_url,
                expected_headers,
                make_error,
                called,
            }
        }

        pub fn assert_called(self) {
            assert_eq!(self.called.get(), true);
        }
    }

    impl<F> super::Client for BrokenClient<F>
    where
        F: Fn() -> Box<Error>,
    {
        type Response = FakeResponse;

        fn execute(
            &self,
            request: reqwest::Request,
        ) -> Result<Self::Response, Box<Error>> {
            assert_eq!(request.method(), &reqwest::Method::GET);
            assert_eq!(request.url(), &self.expected_url);
            assert_eq!(request.headers(), &self.expected_headers);

            self.called.set(true);

            Err((self.make_error)())
        }
    }

}