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
use iron::{
    response::{Response, WriteBody},
    headers::{Header, HeaderFormat, ContentType, Cookie},
    mime::{Mime, TopLevel, SubLevel},
    Headers,
    typemap::{Key, TypeMap},
    status::Status,
};
use std::{
    error::Error,
    fmt::{Display, Formatter, Result as FmtResult},
    string::FromUtf8Error,
};

/// Wraps a response for easier examination in unit tests
pub struct ResponseExamine {
    body: Option<Vec<u8>>,
    response: Response,
}

impl ResponseExamine {
    /// Create a `ResponseExamine` wrapping `response`
    ///
    /// ### Panics
    /// This reads the body of the response and will panic if a body
    /// exists but cannot be read
    pub fn new(mut response: Response) -> ResponseExamine {
        let body = response.body.as_mut().map(|mut body| {
            let mut data = Vec::new();
            body.write_body(&mut data).expect("write_all");
            data.shrink_to_fit();
            data
        });

        ResponseExamine {
            body, 
            response,
        }
    }

    /// Get a slice containing the bytes making up the body of the response,
    /// should the response have a body
    pub fn get_bytes(&self) -> Option<&[u8]> {
        if let Some(b) = &self.body { Some(b.as_slice()) } else { None }
    }

    // helper to make NoBody errors
    fn get_body_error(&self) -> Result<&Vec<u8>, ResponseError> {
        self.body.as_ref().ok_or(ResponseError::NoBody)
    }

    /// Try to decode the body of the request as a Utf-8 string
    pub fn get_string(&self) -> Result<String, ResponseError> {
        self.get_body_error().and_then(|v| Ok(String::from_utf8(v.clone())?))
    }

    /// Get the given header from the response's header map
    pub fn get_header<H: Header + HeaderFormat>(&self) -> Option<&H> {
        self.response.headers.get::<H>()
    }

    /// Get the response's header map
    pub fn get_headers(&self) -> &Headers {
        &self.response.headers
    }

    /// Get the given extension from the response's extension map
    pub fn get_extension<K: Key>(&self) -> Option<&K::Value> {
        self.response.extensions.get::<K>()
    }

    /// Get the response's extension map
    pub fn get_extensions(&self) -> &TypeMap {
        &self.response.extensions
    }

    /// Get the status code of the response
    pub fn get_status(&self) -> Option<&Status> {
        self.response.status.as_ref()
    }

    /// `true` if the response has a status code and that status code indicates
    /// success, `false` otherwise.
    pub fn is_success(&self) -> bool {
        self.response.status.map_or(false, |s| s.is_success())
    }

    #[cfg(feature = "json")]
    /// Try to decode the body of the request as a json encoded object of the given format
    ///
    /// This will error if there is a content type header set and it's not `Content-Type:
    /// application/json`
    pub fn get_json<T: serde::de::DeserializeOwned>(&self) -> Result<T, ResponseError> {
        self.get_header::<ContentType>().map_or(Ok(()), |got| {
            let expected = ContentType::json();
            if *got == expected { Ok(()) }
            else { Err(ResponseError::BadContentType { expected, got: got.clone() }) }
        })?;
        self.get_body_error().and_then(|v| Ok(serde_json::from_slice(v.as_slice())?))
    }

    #[cfg(feature = "jsonapi")]
    /// Try to decode the body of the request as a Json:API document
    ///
    /// In conformance to the spec this will error if the content type header is not
    /// `Content-Type: application/vnd.api+json`
    pub fn get_document(&self) -> Result<japi::Document, ResponseError> {
        self.get_header::<ContentType>().map_or(Err(ResponseError::NoContentType), |got| {
            let expected = ContentType(Mime(
                TopLevel::Application,
                SubLevel::Ext(String::from("vnd.api+json")),
                Vec::new()));
            if *got == expected { Ok(()) }
            else { Err(ResponseError::BadContentType { expected, got: got.clone() }) }
        })?;
        self.get_body_error().and_then(|v| Ok(serde_json::from_slice(v.as_slice())?))
    }

    #[cfg(feature = "jsonapi")]
    /// Try to decode the body of the request as a Json:API document and then get the 
    /// primary data of that document. 
    ///
    /// In conformance to the spec this will error if the content type header is not
    /// `Content-Type: application/vnd.api+json`. It will also error if there are 
    /// multiple data (even if it's an array containing a single element) or no data.
    pub fn get_primary_data(&self) -> Result<japi::GenericObject, ResponseError> {
        use japi::OptionalVec;
        let document = self.get_document()?;
        match document.data {
            OptionalVec::One(Some(d)) => Ok(d),
            OptionalVec::Many(_) => Err(ResponseError::MultipleData),
            _ => Err(ResponseError::NoData),
        }
    }

    #[cfg(feature = "cookies")]
    /// Get a cookie jar containing all cookies in the `Cookie` header.
    ///
    /// All cookies will be non-original and thus will show up in `.delta()`.
    /// This will error if there was no `Cookie` header set. 
    pub fn get_cookies(&self) -> Result<cookie::CookieJar, ResponseError> {
        let mut jar = cookie::CookieJar::new();

        if let Some(cookies) = self.get_header::<Cookie>() {
            for c in cookies.iter() {
                jar.add(cookie::Cookie::parse(c)?.into_owned());
            }
            Ok(jar)
        } else { Err(ResponseError::NoCookies) }

    }
}

#[derive(Debug)]
pub enum ResponseError {
    NoBody,
    StringConversion(FromUtf8Error),
    #[cfg(any(feature = "json", feature = "jsonapi"))]
    JsonError(serde_json::error::Error),
    #[cfg(any(feature = "json", feature = "jsonapi"))]
    BadContentType{ expected: ContentType, got: ContentType }, 
    #[cfg(feature = "jsonapi")]
    NoContentType,
    #[cfg(feature = "jsonapi")]
    JsonApiError(japi::ObjectConversionError),
    #[cfg(feature = "jsonapi")]
    MultipleData,
    #[cfg(feature = "jsonapi")]
    NoData,
    #[cfg(feature = "cookies")]
    CookieError(cookie::ParseError),
    #[cfg(feature = "cookies")]
    NoCookies,
}

impl Error for ResponseError {
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        match self {
            ResponseError::StringConversion(e) => Some(e),
            #[cfg(feature = "json")]
            ResponseError::JsonError(e) => Some(e),
            #[cfg(feature = "jsonapi")]
            ResponseError::JsonApiError(e) => Some(e),
            #[cfg(feature = "cookies")]
            ResponseError::CookieError(e) => Some(e),
            _ => None,
        }
    }
}

impl Display for ResponseError {
    fn fmt(&self, f: &mut Formatter) -> FmtResult {
        write!(f, "Response Error: ")?;
        match self {
            ResponseError::NoBody => write!(f, "the response has no body"),
            ResponseError::StringConversion(e) => 
                write!(f, "couldn't convert the body to a string ({})", e),
            #[cfg(any(feature = "json", feature = "jsonapi"))]
            ResponseError::JsonError(e) => 
                write!(f, "couldn't convert the body to a json object ({})", e),
            #[cfg(any(feature = "json", feature = "jsonapi"))]
            ResponseError::BadContentType{ expected, got } =>
                write!(f, "bad content type (expected '{}', got '{}')", expected, got),
            #[cfg(feature = "jsonapi")]
            ResponseError::NoContentType => write!(f, "there was no content type header"),
            #[cfg(feature = "jsonapi")]
            ResponseError::JsonApiError(e) =>
                write!(f, "couldn't convert the body to a json:api object ({})", e),
            #[cfg(feature = "jsonapi")]
            ResponseError::MultipleData => 
                write!(f, "the document contains multiple primary data entries"),
            #[cfg(feature = "jsonapi")]
            ResponseError::NoData => write!(f, "the document contains no primary data"),
            #[cfg(feature = "cookies")]
            ResponseError::CookieError(e) =>
                write!(f, "couldn't convert cookies ({})", e),
            #[cfg(feature = "cookies")]
            ResponseError::NoCookies =>
                write!(f, "the 'Cookie' header was not set"),
        }
    }
}

impl From<FromUtf8Error> for ResponseError {
    fn from(e: FromUtf8Error) -> Self {
        ResponseError::StringConversion(e)
    }
}

#[cfg(any(feature = "json", feature = "jsonapi"))]
impl From<serde_json::error::Error> for ResponseError {
    fn from(e: serde_json::error::Error) -> Self {
        ResponseError::JsonError(e)
    }
}


#[cfg(feature = "jsonapi")]
impl From<japi::ObjectConversionError> for ResponseError {
    fn from(e: japi::ObjectConversionError) -> Self {
        ResponseError::JsonApiError(e)
    }
}

#[cfg(feature = "cookies")]
impl From<cookie::ParseError> for ResponseError {
    fn from(e: cookie::ParseError) -> Self {
        ResponseError::CookieError(e)
    }
}

mod test {
    use crate::RequestBuilder;
    use iron::{
        method::Method,
        headers::Expect,
        prelude::*,
        modifiers::Header as ModHead,
    };
    use super::*;

    pub struct TestExtension;
    impl Key for TestExtension { type Value = u8; }

    #[test]
    fn success() {
        let resp = RequestBuilder::new(Method::Get, "http://127.0.0.1:8080/").unwrap()
            .request_response(|_| {
                let mut resp = 
                    Response::with((Status::Ok, "this is a test", ModHead(Expect::Continue)));
                resp.extensions.insert::<TestExtension>(1);
                Ok(resp)
            }).unwrap();

        assert_eq!(resp.get_bytes().unwrap(), b"this is a test");
        assert_eq!(resp.get_string().unwrap(), "this is a test");

        assert_eq!(resp.get_headers().get::<Expect>(), Some(&Expect::Continue));
        assert_eq!(resp.get_header::<Expect>(), Some(&Expect::Continue));

        assert_eq!(resp.get_extensions().len(), 1);
        assert_eq!(resp.get_extension::<TestExtension>(), Some(&1));

        assert_eq!(resp.get_status(), Some(&Status::Ok));
        assert!(resp.is_success());
    }

    #[test]
    fn fail() {
        let resp = RequestBuilder::new(Method::Get, "http://127.0.0.1:8080/").unwrap()
            .request_response(|_| {
                Ok(Response::with(Status::ImATeapot))
            }).unwrap();
        assert!(!resp.is_success());
    }

    #[test]
    fn no_status() {
        let resp = RequestBuilder::new(Method::Get, "http://127.0.0.1:8080/").unwrap()
            .request_response(|_| {
                Ok(Response::with(""))
            }).unwrap();
        assert!(!resp.is_success());
    }

    #[cfg(feature = "json")]
    #[test]
    fn json_no_content_type() {
        use serde_json::{json, Value};
        let resp = RequestBuilder::new(Method::Get, "http://127.0.0.1:8080/").unwrap()
            .request_response(|_| {
                Ok(Response::with("{\"test\":1}"))
            }).unwrap();
        assert_eq!(resp.get_json::<Value>().unwrap(), json!({"test":1}));
    }

    #[cfg(feature = "json")]
    #[test]
    fn json() {
        use serde_json::{json, Value};
        let resp = RequestBuilder::new(Method::Get, "http://127.0.0.1:8080/").unwrap()
            .request_response(|_| {
                Ok(Response::with(("{\"test\":1}", ModHead(ContentType::json()))))
            }).unwrap();
        assert_eq!(resp.get_json::<Value>().unwrap(), json!({"test":1}));
    }

    #[cfg(feature = "json")]
    #[test]
    fn json_wrong_content_type() {
        use serde_json::{json, Value};
        let resp = RequestBuilder::new(Method::Get, "http://127.0.0.1:8080/").unwrap()
            .request_response(|_| {
                Ok(Response::with(("{\"test\":1}", ModHead(ContentType::jpeg()))))
            }).unwrap();
        assert!(resp.get_json::<Value>().is_err());
    }

    #[cfg(feature = "jsonapi")]
    #[test]
    fn jsonapi() {
        use japi::*;
        use serde_json;
        let go : GenericObject = Identifier::new("a".into(), "b".into()).into();
        let d = Document { 
            data: OptionalVec::One(Some(go.clone())),
            ..Default::default()
        };
        let content_type = ContentType(Mime(
                TopLevel::Application,
                SubLevel::Ext(String::from("vnd.api+json")),
                Vec::new()));
        let resp = RequestBuilder::new(Method::Get, "http://127.0.0.1:8080/").unwrap()
            .request_response(|_| {
                Ok(Response::with((serde_json::to_string(&d).unwrap(), ModHead(content_type.clone())))) 
            }).unwrap();
        assert_eq!(resp.get_document().unwrap(), d);
        assert_eq!(resp.get_primary_data().unwrap(), go);
    }

    #[cfg(feature = "jsonapi")]
    #[test]
    fn jsonapi_no_content_type() {
        use japi::*;
        use serde_json;
        let go : GenericObject = Identifier::new("a".into(), "b".into()).into();
        let d = Document { 
            data: OptionalVec::One(Some(go.clone())),
            ..Default::default()
        };
        let resp = RequestBuilder::new(Method::Get, "http://127.0.0.1:8080/").unwrap()
            .request_response(|_| {
                Ok(Response::with(serde_json::to_string(&d).unwrap())) 
            }).unwrap();
        assert!(resp.get_document().is_err());
        assert!(resp.get_primary_data().is_err());
    }

    #[cfg(feature = "jsonapi")]
    #[test]
    fn jsonapi_wrong_content_type() {
        use japi::*;
        use serde_json;
        let go : GenericObject = Identifier::new("a".into(), "b".into()).into();
        let d = Document { 
            data: OptionalVec::One(Some(go.clone())),
            ..Default::default()
        };
        let resp = RequestBuilder::new(Method::Get, "http://127.0.0.1:8080/").unwrap()
            .request_response(|_| {
                Ok(Response::with((serde_json::to_string(&d).unwrap(), ModHead(ContentType::json())))) 
            }).unwrap();
        assert!(resp.get_document().is_err());
        assert!(resp.get_primary_data().is_err());
    }

    #[cfg(feature = "cookies")]
    #[test]
    fn cookies() {
        let resp = RequestBuilder::new(Method::Get, "http://127.0.0.1:8080/").unwrap()
            .request_response(|_| {
                Ok(Response::with(ModHead(Cookie(vec![
                    String::from("foo=bar"), String::from("bar=baz")]))))
            }).unwrap();
        let jar = resp.get_cookies().unwrap();
        assert_eq!(jar.get("foo").unwrap().value(), "bar");
        assert_eq!(jar.get("bar").unwrap().value(), "baz");
        assert_eq!(jar.iter().count(), 2);
    }

    #[cfg(feature = "cookies")]
    #[test]
    fn no_cookies() {
        let resp = RequestBuilder::new(Method::Get, "http://127.0.0.1:8080/").unwrap()
            .request_response(|_| {
                Ok(Response::with("oops no cookies"))
            }).unwrap();
        assert!(resp.get_cookies().is_err());
    }
}