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
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
// 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::sync::{Arc, Mutex};


// External Dependencies ------------------------------------------------------
use colored::*;
use hyper::Client;
use hyper::method::Method;
use hyper::client::Response;
use hyper::status::StatusCode;
use hyper::header::{Header, Headers, HeaderFormat, ContentType};


// Internal Dependencies ------------------------------------------------------
use HttpApi;
use Options;
use mock::{MockResponse, MockProvider, ResponseProvider};
use resource::http::util;
use resource::http::{HttpHeader, HttpBody, HttpQueryString};

/// A HTTP request for API testing.
///
/// The request is automatically started once the instance goes out of scope
/// and any set up expectations are asserted and logged to `stdout` in case of
/// failure.
///
/// `HttpRequest::collect()` can be used to manually start the request.
///
/// # Example Usage
///
/// ```rust
/// # #[macro_use] extern crate noir;
/// # extern crate hyper;
/// # use hyper::status::StatusCode;
/// # use hyper::header::{Accept, Connection, qitem};
/// # use hyper::mime::{Mime, TopLevel, SubLevel};
/// # use noir::{HttpApi, HttpEndpoint, HttpRequest};
/// # #[derive(Copy, Clone, Default)]
/// # struct Api;
/// # impl HttpApi for Api {
/// #     fn hostname(&self) -> &'static str {
/// #         "localhost"
/// #     }
/// #     fn port(&self) -> u16 {
/// #         8080
/// #     }
/// #     fn start(&self) {
/// #         // Start the HTTP server...
/// #     }
/// # }
/// # #[derive(Copy, Clone)]
/// # struct ExternalResource;
/// # impl HttpEndpoint for ExternalResource {
/// #     fn hostname(&self) -> &'static str {
/// #         "rust-lang.org"
/// #     }
/// #     fn port(&self) -> u16 {
/// #         443
/// #     }
/// # }
/// # fn test_request() -> HttpRequest<Api> {
/// Api::get("/")
///     .with_headers(headers![
///         Connection::close(),
///         Accept(vec![
///             qitem(Mime(TopLevel::Text, SubLevel::Plain, vec![]))
///         ])
///     ])
///     .provide(responses![
///         ExternalResource.get("/")
///                         .with_status(StatusCode::Ok)
///                         .with_body("Hello World")
///                         .expected_header(Connection::close())
///     ])
///     .expected_status(StatusCode::Ok)
///     .expected_body("Hello World")
/// # }
/// # fn main() {
/// # test_request().collect().unwrap_err();
/// # }
/// ```
///
/// # Panics
///
/// If any of the set up expectations fail.
pub struct HttpRequest<A: HttpApi> {
    api: A,
    method: Method,
    path: String,
    options: Options,

    api_timed_out: bool,
    dump_response: bool,

    provided_responses: Vec<Box<MockResponse + 'static>>,
    provided_mocks: Vec<Box<MockProvider + 'static>>,

    request_headers: Headers,
    request_body: Option<HttpBody>,

    expected_status: Option<StatusCode>,
    expected_headers: Headers,
    expected_body: Option<HttpBody>,
    expected_exact_body: bool,

    unexpected_headers: Vec<String>,

    run_on_drop: bool
}

impl<A: HttpApi> HttpRequest<A> {

    /// Sets additional headers to be send with the request.
    ///
    /// Use the `headers![...]` macro to easily create a vector containing
    /// concrete types of the `hyper::Header` trait for use with this method.
    pub fn with_headers(mut self, headers: Vec<HttpHeader>) -> Self {
        for header in headers {
            let (name, value) = util::http_header_into_tuple(header);
            self.request_headers.set_raw(name, vec![value]);
        }
        self
    }

    /// Sets one additional header to be send with the request.
    pub fn with_header<H: Header + HeaderFormat>(mut self, header: H) -> Self {
        self.request_headers.set(header);
        self
    }

    /// Sets the request's query string.
    ///
    /// This will override any existing query string previously set or derived
    /// from the request's path.
    pub fn with_query(mut self, query: HttpQueryString) -> Self {
        self.path = util::path_with_query(self.path.as_str(), query);
        self
    }

    /// Sets the request body.
    ///
    /// Also sets the `Content-Type` header of the request based on the type
    /// of the `body` argument.
    ///
    /// The set `Content-Type` can be overridden via `HttpRequest::with_header`.
    pub fn with_body<S: Into<HttpBody>>(mut self, body: S) -> Self {
        self.request_body = Some(body.into());
        self
    }

    /// Sets the request's configuration options.
    ///
    /// This allows to change or override the default request behaviour.
    pub fn with_options(mut self, options: Options) -> Self {
        self.options = options;
        self
    }

    /// Sets the expected response status for the request.
    ///
    /// ### Test Failure
    ///
    /// If the actual response status does not match the expected one.
    ///
    /// ### Test Failure Examples
    ///
    /// [expanded](terminal://headers_expected)
    pub fn expected_status(mut self, status_code: StatusCode) -> Self {
        self.expected_status = Some(status_code);
        self
    }

    /// Sets one additional header that should be present on the response.
    ///
    /// ### Test Failure
    ///
    /// If the header is either missing from the response or its value does
    /// not match the expected one.
    pub fn expected_header<H: Header + HeaderFormat>(mut self, header: H) -> Self {
        self.expected_headers.set(header);
        self
    }

    /// Sets one additional header that should be absent from the response.
    ///
    /// ### Test Failure
    ///
    /// If the header is present on the response.
    ///
    /// ### Test Failure Examples
    ///
    /// [expanded](terminal://headers_unexpected)
    pub fn unexpected_header<H: Header + HeaderFormat>(mut self) -> Self {
        self.unexpected_headers.push(<H>::header_name().to_string());
        self
    }

    /// Sets additional headers that should be present on the response.
    ///
    /// Use the `headers![...]` macro to easily create a vector containing
    /// concrete types of the `hyper::Header` trait for use with this method.
    ///
    /// ### Test Failure
    ///
    /// If one or more of the headers are either missing from the response
    /// or their values differ from the expected ones.
    pub fn expected_headers(mut self, headers: Vec<HttpHeader>) -> Self {
        for header in headers {
            let (name, value) = util::http_header_into_tuple(header);
            self.expected_headers.set_raw(name, vec![value]);
        }
        self
    }

    /// Sets the expected response body for the request.
    ///
    /// The expected and the actual body are compared based on the MIME type
    /// of the response.
    ///
    /// ##### text/*
    ///
    /// These Compared as strings, if no other character encoding is set in the
    /// response's MIME type, UTF-8 will be used as the default.
    ///
    /// ##### application/json
    ///
    /// JSON objects are deep compared, but __additional keys on response objects
    /// are ignored__.
    ///
    /// This allows for simpler and more fine grained assertions against JSON
    /// responses.
    ///
    /// ##### All other mime types
    ///
    /// These are compared on a byte by byte basis.
    ///
    /// ### Test Failure
    ///
    /// If the actual response body does not match the expected one.
    ///
    /// ### Test Failure Examples
    ///
    /// [expanded](terminal://body_expected_raw_mismatch)
    /// [collapsed](terminal://body_text_mismatch_diff_added)
    /// [collapsed](terminal://body_with_expected_json_mismatch)
    pub fn expected_body<S: Into<HttpBody>>(mut self, body: S) -> Self {
        self.expected_body = Some(body.into());
        self.expected_exact_body = false;
        self
    }

    /// Sets the expected response body for the request (exact version).
    ///
    /// This method is based on `HttpRequest::expected_body()` but performs
    /// additional comparison based on the mime type of the response:
    ///
    /// ##### application/json
    ///
    /// In contrast to `HttpResponse::expected_body()` __additional keys on
    /// response objects are compared and will fail the test__.
    ///
    /// ##### All other mime types
    ///
    /// See `HttpResponse::expected_body()`.
    ///
    /// ### Test Failure
    ///
    /// If the actual response body does not match the expected one.
    pub fn expected_exact_body<S: Into<HttpBody>>(mut self, body: S) -> Self {
        self.expected_body = Some(body.into());
        self.expected_exact_body = true;
        self
    }

    /// Provides additional mocked responses from endpoints for the time of the
    /// currently executing request.
    ///
    /// Use the `responses![...]` macro to easily create a vector containing
    /// concrete types of the `MockResponse` trait for use with this method.
    ///
    /// ### Test Failure
    ///
    /// If one or more of the provided responses is not called or does not
    /// match its expectations.
    pub fn provide(mut self, mut resources: Vec<Box<MockResponse>>) -> Self {
        self.provided_responses.append(&mut resources);
        self
    }

    /// Dumps the response headers and body this request.
    ///
    /// ### Test Failure
    ///
    /// Always.
    ///
    /// ### Test Failure Examples
    ///
    /// [expanded](terminal://dump_response_with_raw_body)
    /// [collapsed](terminal://dump_response_with_text_body)
    /// [collapsed](terminal://dump_response_with_json_body)
    pub fn dump(mut self) -> Self {
        self.dump_response = true;
        self
    }

    /// Provides additional mocks which will be active for the time of the
    /// currently executing request.
    ///
    /// Use the `mocks![...]` macro to easily create a vector containing
    /// concrete types of the `MockProvider` trait for use with this method.
    pub fn mocks<T: MockProvider + 'static>(mut self, mocks: Vec<T>) -> Self {
        for res in mocks {
            self.provided_mocks.push(Box::new(res));
        }
        self
    }

    /// Directly execute the test request and collect any error message output.
    pub fn collect(mut self) -> Result<(), String> {
        self.run_on_drop = false;
        self.run()
    }


    // Internal ---------------------------------------------------------------
    fn run(&mut self) -> Result<(), String> {

        // Handle cases where the API test server did not start in time
        if self.api_timed_out {
            return Err(format!(
                "\n{} {} \"{}\" {} {}{}\n\n",
                "API Failure:".red().bold(),
                "Server for".yellow(),
                self.api.url().as_str().cyan(),
                "did not respond within".yellow(),
                "1000ms".green().bold(),
                ".".yellow()
            ));
        }

        // Limit ourselves to one test at a time in order to ensure correct
        // handling of mocked requests and responses
        let (errors, error_count, suppressed_count) = if let Ok(_) = REQUEST_LOCK.lock() {
            self.request()

        } else {
            (vec![format!(
                "{} {}",
                "Internal Error:".red().bold(),
                "Request lock failed.".yellow()

            )], 1, 0)
        };

        if !errors.is_empty() {

            let mut report = String::new();

            // Title
            report.push_str(format!(
                "\n{} {} {} \"{}{}\" {} {} {}\n",
                "Response Failure:".red().bold(),
                format!("{}", self.method).cyan(),
                "request to".yellow(),
                self.api.url().cyan(),
                self.path.cyan(),
                "returned".yellow(),
                format!("{}", error_count).red().bold(),
                "error(s)".yellow()

            ).as_str());

            // Response and Request Errors
            for (index, e) in errors.iter().enumerate() {
                report.push_str(format!(
                    "\n{} {}\n", format!("{:2})", index + 1).blue().bold(),
                    e

                ).as_str());
            }

            // Suppressed error information
            if suppressed_count != 0 {
                report.push_str(format!(
                    "\n{} {} {} {}\n",
                    "Note:".green().bold(),
                    "Suppressed".black().bold(),
                    format!("{}", suppressed_count).blue().bold(),
                    "request error(s) that may have resulted from failed response expectations.".black().bold()

                ).as_str());
            }

            // Padding
            report.push_str("\n\n");

            Err(report)

        } else {
            Ok(())
        }

    }

    fn request(&mut self) -> (Vec<String>, usize, usize) {

        // Convert body into Mime and Vec<u8>
        let (content_mime, body) = if let Some(body) = self.request_body.take() {
            util::http_body_into_parts(body)

        } else {
            (None, None)
        };

        // Set Content-Type based on body data if:
        // A. The body has a Mime
        // B. No other Content-Type has been set on the request
        if let Some(content_mime) = content_mime {
            if !self.request_headers.has::<ContentType>() {
                self.request_headers.set(ContentType(content_mime));
            }
        }

        // Create Client
        let mut client = Client::new();
        client.set_read_timeout(Some(self.options.api_request_timeout));
        client.set_write_timeout(Some(self.options.api_request_timeout));

        // Setup Request
        let mut request = client.request(
            self.method.clone(),
            self.api.url_with_path(self.path.as_str()).as_str()

        ).headers(
            self.request_headers.clone()
        );

        // Set body, if present
        if let Some(body) = body.as_ref() {
            request = request.body(
                &body[..]
            );
        }

        // Provide responses to request interceptors
        ResponseProvider::provide(
            self.provided_responses.drain(0..).collect()
        );

        for mock in &mut self.provided_mocks {
            mock.setup();
        }

        // Send response and validate
        let errors = match request.send() {
            Ok(response) => self.validate(response),
            Err(_) => (vec![format!(
                "{} {} {}{}",
                "API Failure:".red().bold(),
                "No response within".yellow(),
                "1000ms".green().bold(),
                ".".yellow()

            )], 1, 0)
        };

        for mock in &mut self.provided_mocks {
            mock.teardown();
        }

        errors

    }

    fn validate(&mut self, mut response: Response) -> (Vec<String>, usize, usize) {

        let mut errors = Vec::new();
        if self.dump_response {
            util::dump_http_like(
                &mut errors,
                &mut response,
                "Response"
            );
        }

        let status = response.status;
        errors.append(&mut util::validate_http_request(
            &mut response,
            &self.options,
            "Response",
            Some(status),
            self.expected_status,
            &self.expected_headers,
            &mut self.unexpected_headers,
            &self.expected_body,
            self.expected_exact_body
        ));

        let mut response_errors = Vec::new();
        let mut error_count = errors.len();
        let index_offset = match self.options.error_suppress_cascading {
            true => 0,
            false => error_count
        };

        for (
            mut response,
            response_index,
            request_index

        ) in ResponseProvider::provided_responses() {

            let errors = response.validate(response_index, request_index);
            if !errors.is_empty() {
                let header = response.validate_header(errors.len());
                error_count += errors.len();
                response_errors.push(format_response_errors(
                    header,
                    index_offset + response_index + 1,
                    errors
                ));
            }

        }

        for mut request in ResponseProvider::additional_requests() {
            if let Some(error) = request.validate() {
                response_errors.push(error);
                error_count += 1;
            }
        }

        ResponseProvider::reset();

        // Suppress cascading errors that may be the result from response errors
        if !response_errors.is_empty() &&
            self.options.error_suppress_cascading {

            // Remove the suppressed errors
            let suppressed_count = errors.len();
            errors.clear();

            errors.append(&mut response_errors);
            (errors, error_count - suppressed_count, suppressed_count)

        } else {
            errors.append(&mut response_errors);
            (errors, error_count, 0)
        }

    }

}

/// Automatically starts the request and logs any errors from set up expectations
/// to `stdout`.
///
/// # Panics
///
/// If any of the set up expectations fail.
impl<A: HttpApi> Drop for HttpRequest<A> {
    fn drop(&mut self) {
        if self.run_on_drop {
            if let Err(report) = self.run() {
                print!("{}", report);
                panic!("Request failed, see above for details.");
            }
        }
    }
}


// Helper ---------------------------------------------------------------------
fn format_response_errors(
    header: String, offset: usize, errors: Vec<String>

) -> String {

    let mut formatted = format!(
        "{} {}",
        "Request Failure:".red().bold(),
        header
    );

    for (index, e) in errors.iter().enumerate() {
        formatted.push_str("\n\n");
        formatted.push_str(
            e.lines()
             .enumerate()
             .map(|(i, line)| {
                if i == 0 {
                    format!(
                        "    {} {}",
                        format!(
                            "{:2}.{})",
                            offset,
                            index + 1

                        ).blue().bold(),
                        line
                    )

                } else {
                    format!("      {}", line)
                }

            }).collect::<Vec<String>>().join("\n").as_str()
        );
    }

    formatted

}


// Internal -------------------------------------------------------------------
pub fn http_request<A: HttpApi>(
    api: A,
    method: Method,
    path: &'static str,
    api_timed_out: bool

) -> HttpRequest<A> {
    HttpRequest {
        api: api,
        method: method,
        path: path.to_string(),
        options: Default::default(),

        api_timed_out: api_timed_out,
        dump_response: false,

        provided_responses: Vec::new(),
        provided_mocks: Vec::new(),

        request_headers: Headers::new(),
        request_body: None,

        expected_status: None,
        expected_headers: Headers::new(),
        expected_body: None,
        expected_exact_body: false,

        unexpected_headers: Vec::new(),

        run_on_drop: true
    }
}

lazy_static! {
    static ref REQUEST_LOCK: Arc<Mutex<()>> = {
        Arc::new(Mutex::new(()))
    };
}