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
// Copyright (c) 2016 Ivo Wetzel

// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

// STD Dependencies -----------------------------------------------------------
use std::str;
use std::io::Read;


// External Dependencies ------------------------------------------------------
use json;
use colored::*;
use hyper::client::Response;
use hyper::header::{Headers, ContentType};
use hyper::mime::{Mime, TopLevel, SubLevel};


// Internal Dependencies ------------------------------------------------------
use util;
use Options;
use super::HttpFormData;
use super::form::{
    http_form_into_body_parts,
    http_form_into_fields,
    parse_form_data
};


/// An abstraction over different data types used for HTTP request bodies.
pub struct HttpBody {
    data: Vec<u8>,
    mime: Option<Mime>
}


// Internal -------------------------------------------------------------------
pub fn http_body_from_parts(data: Vec<u8>, headers: &Headers) -> HttpBody {

    let mime = if let Some(&ContentType(ref mime)) = headers.get::<ContentType>() {
        mime.clone()

    } else {
        Mime(TopLevel::Application, SubLevel::OctetStream, vec![])
    };

    HttpBody {
        data: data,
        mime: Some(mime)
    }

}

pub fn http_body_into_parts(body: HttpBody) -> (Option<Mime>, Option<Vec<u8>>) {
    (body.mime, Some(body.data))
}

#[doc(hidden)]
impl<'a> From<&'a mut Response> for HttpBody {
    fn from(res: &mut Response) -> HttpBody {
        let mut body: Vec<u8> = Vec::new();
        // If the res body is empty, this will fail so we simply ignore it
        res.read_to_end(&mut body).ok();
        http_body_from_parts(body, &res.headers)
    }
}

impl From<Vec<u8>> for HttpBody {
    /// Creates a HTTP body from a byte vector.
    ///
    /// # Test Failure Examples
    ///
    /// [expanded](terminal://body_expected_raw_mismatch)
    fn from(vec: Vec<u8>) -> HttpBody {
        HttpBody {
            data: vec,
            mime: Some(Mime(TopLevel::Application, SubLevel::OctetStream, vec![]))
        }
    }
}

impl From<&'static str> for HttpBody {
    /// Creates a HTTP body from a string slice.
    ///
    /// # Test Failure Examples
    ///
    /// [expanded](terminal://body_text_mismatch_diff_added)
    fn from(string: &'static str) -> HttpBody {
        HttpBody {
            data: string.into(),
            mime: Some(Mime(TopLevel::Text, SubLevel::Plain, vec![]))
        }
    }
}

impl From<String> for HttpBody {
    /// Creates a HTTP body from a `String`.
    ///
    /// # Test Failure Examples
    ///
    /// [expanded](terminal://body_text_mismatch_diff_removed)
    fn from(string: String) -> HttpBody {
        HttpBody {
            data: string.into(),
            mime: Some(Mime(TopLevel::Text, SubLevel::Plain, vec![]))
        }
    }
}

impl From<json::JsonValue> for HttpBody {
    /// Creates a HTTP body from a JSON value.
    ///
    /// # Test Failure Examples
    ///
    /// [expanded](terminal://body_with_expected_json_mismatch)
    fn from(json: json::JsonValue) -> HttpBody {
        HttpBody {
            data: json::stringify(json).into(),
            mime: Some(Mime(TopLevel::Application, SubLevel::Json, vec![]))
        }
    }
}

impl From<HttpFormData> for HttpBody {
    /// Creates a HTTP body from form data.
    ///
    /// # Test Failure Examples
    ///
    /// [expanded](terminal://provided_response_with_expected_body_form_mismatch)
    fn from(form: HttpFormData) -> HttpBody {
        let (mime_type, body) = http_form_into_body_parts(form);
        HttpBody {
            data: body,
            mime: Some(mime_type)
        }
    }
}

pub fn validate_http_body(
    errors: &mut Vec<String>,
    options: &Options,
    actual_body: HttpBody,
    context: &str,
    expected_body: &HttpBody,
    expected_exact_body: bool
) {

    // Quick check before we perform heavy weight parsing
    // This might cause false negative for JSON, but we'll perform a deep
    // compare anyway.
    if actual_body.data == expected_body.data {
        return;
    }

    // Parse and compare different body types
    let body = parse_http_body(&actual_body);
    errors.push(match body {

        Ok(actual) => match actual {
            ParsedHttpBody::Text(actual) => {
                match str::from_utf8(expected_body.data.as_slice()) {
                    Ok(expected) => {

                        let (expected, actual, diff) = util::diff::text(
                            expected,
                            actual
                        );

                        format!(
                            "{} {}\n\n        \"{}\"\n\n    {}\n\n        \"{}\"\n\n    {}\n\n        \"{}\"",
                            context.yellow(),
                            "text body does not match, expected:".yellow(),
                            expected.green().bold(),
                            "but got:".yellow(),
                            actual.red().bold(),
                            "difference:".yellow(),
                            diff
                        )

                    },
                    Err(err) => format!(
                        "{} {}\n\n        {}",
                        context.yellow(),
                        "body, expected text provided by test contains invalid UTF-8:".yellow(),
                        format!("{:?}", err).red().bold()
                    )
                }
            },
            ParsedHttpBody::Json(actual) => {
                let expected_json = util::json::parse(
                    expected_body.data.as_slice(),
                    "body JSON provided by test"
                );
                match expected_json {
                    Ok(expected) => {

                        let errors = util::json::compare(
                            &expected,
                            &actual,
                            options.json_compare_depth,
                            expected_exact_body
                        );

                        // Exit early when there are no errors
                        if errors.is_ok() {
                            return;
                        }

                        format!(
                            "{} {}\n\n        {}",
                            context.yellow(),
                            "body JSON does not match:".yellow(),
                            util::json::format(errors.unwrap_err())
                        )

                    },
                    Err(err) => {
                        format!(
                            "{} {} {}",
                            context.yellow(),
                            "body, expected".yellow(),
                            err
                        )
                    }
                }
            },
            ParsedHttpBody::Form(actual) => {
                match parse_http_body(expected_body) {
                    Ok(ParsedHttpBody::Form(expected)) => {

                        let expected = http_form_into_fields(expected);
                        let actual = http_form_into_fields(actual);
                        let errors = util::form::compare(
                            &expected,
                            &actual,
                            expected_exact_body,
                            options
                        );

                        // Exit early when there are no errors
                        if errors.is_ok() {
                            return;
                        }

                        format!(
                            "{} {}\n\n        {}",
                            context.yellow(),
                            "body form data does not match:".yellow(),
                            util::form::format(errors.unwrap_err())
                        )

                    },
                    _ => unreachable!()
                }
            },
            ParsedHttpBody::Raw(actual) => {
                format!(
                    "{} {}\n\n       [{}]\n\n    {}\n\n       [{}]",

                    context.yellow(),

                    format!(
                        "{} {}{}",
                        "raw body data does not match, expected the following".yellow(),
                        format!("{} bytes", expected_body.data.len()).green().bold(),
                        ":".yellow()
                    ),
                    util::raw::format_green(expected_body.data.as_slice()),
                    format!(
                        "{} {} {}",
                        "but got the following".yellow(),
                        format!("{} bytes", actual.len()).red().bold(),
                        "instead:".yellow()
                    ),
                    util::raw::format_red(actual),
                )
            }
        },

        Err(err) => {
            format!("{} {}", context.yellow(), err)
        }

    });

}

pub enum ParsedHttpBody<'a> {
    Text(&'a str),
    Json(json::JsonValue),
    Form(HttpFormData),
    Raw(&'a [u8])
}

pub fn parse_http_body(body: &HttpBody) -> Result<ParsedHttpBody, String> {

    if let Some(mime) = body.mime.as_ref() {
        match mime.clone() {
            Mime(TopLevel::Text, _, _) => {
                match str::from_utf8(body.data.as_slice()) {
                    Ok(text) => Ok(ParsedHttpBody::Text(text)),
                    Err(err) => Err(format!(
                        "{}\n\n        {}",
                        "text body contains invalid UTF-8:".yellow(),
                        format!("{:?}", err).red().bold()
                    ))
                }
            },
            Mime(TopLevel::Application, SubLevel::Json, _) => {
                match util::json::parse(body.data.as_slice(), "body JSON") {
                    Ok(json) => Ok(ParsedHttpBody::Json(json)),
                    Err(err) => Err(err)
                }
            },
            Mime(TopLevel::Application, SubLevel::FormData, attrs) |
            Mime(TopLevel::Application, SubLevel::WwwFormUrlEncoded, attrs) => {

                // Get form-data boundary, if present
                let boundary = attrs.get(0).map(|b| {
                    b.1.as_str().to_string()
                });

                match parse_form_data(body.data.as_slice(), boundary) {
                    Ok(data) => Ok(ParsedHttpBody::Form(data)),
                    Err(err) => Err(format!(
                        "{}\n\n        {}",
                        "form body could not be parsed:".yellow(),
                         err.red().bold()
                    ))
                }

            },
            _ => {
                Ok(ParsedHttpBody::Raw(&body.data[..]))
            }
        }

    } else {
        Ok(ParsedHttpBody::Raw(&body.data[..]))
    }
}