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
// 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::cmp;
use std::time::Duration;
use std::error::Error as ErrorTrait;
use std::net::{SocketAddr, Shutdown};
use std::io::{Error, ErrorKind, Write, Read};


// External Dependencies ------------------------------------------------------
use hyper;
use httparse;
use hyper::net::{NetworkConnector, NetworkStream};


// Internal Dependencies ------------------------------------------------------
use mock::MockResponseProvider;
use resource::http::HttpRequest;


/// A macro for intercepting `hyper::Client::new()` calls made during tests.
///
/// During testing (`#[cfg(test)]`) the macro will be replaced with
/// `hyper::Client::with_connector(...)`
///
/// Outside of testing the macro will be compiled out and reduce itself to a
/// normal `hyper::Client::new()` call.
///
/// # Example Usage
///
/// ```rust
/// # extern crate hyper;
/// # #[macro_use] extern crate noir;
///
/// # fn main() {
/// let client = hyper_client!();
/// let request = client.get(
///     "https://example.com/"
/// );
/// # }
/// ```
#[macro_export]
macro_rules! hyper_client {
    () => {
        if cfg!(test) {
            $crate::mock::http::mocked_hyper_client()

        } else {
            hyper::Client::new()
        }
    }
}


#[cfg_attr(feature = "clippy", allow(inline_always))]
#[inline(always)]
#[doc(hidden)]
pub fn mocked_hyper_client() -> hyper::Client {
    hyper::Client::with_connector(MockConnector)
}


// Noir Internal --------------------------------------------------------------
struct MockConnector;
impl NetworkConnector for MockConnector {

    type Stream = MockStream;

    fn connect(
        &self,
        host: &str,
        port: u16,
        _: &str

    ) -> Result<Self::Stream, hyper::Error> {
        Ok(MockStream::new(host, port))
    }

}

struct MockStream {
    host: String,
    port: u16,
    request: Vec<u8>,
    response: Result<Vec<u8>, Error>,
    response_index: usize
}

impl MockStream {
    pub fn new(host: &str, port: u16) -> MockStream {
        MockStream {
            host: host.to_string(),
            port: port,
            request: Vec::new(),
            response: Ok(Vec::new()),
            response_index: 0
        }
    }
}

impl Write for MockStream {

    fn write(&mut self, buf: &[u8]) -> Result<usize, Error> {
        self.request.extend_from_slice(buf);
        Ok(buf.len())
    }

    fn flush(&mut self) -> Result<(), Error> {

        let mut headers = [httparse::EMPTY_HEADER; 16];
        let mut req = httparse::Request::new(&mut headers);

        match req.parse(&self.request[..]) {
            Ok(httparse::Status::Complete(size)) => {

                let request = Box::new(HttpRequest::new(
                    self.host.to_string(),
                    self.port,
                    req,
                    self.request[size..].to_vec()
                ));

                match MockResponseProvider::response_from_request(request) {
                    Ok(response) => {
                        self.response = response;
                        Ok(())
                    },
                    Err(err) => Err(err)
                }

            },
            _ => unreachable!()
        }

    }

}

impl Read for MockStream {
    fn read(&mut self, buf: &mut [u8]) -> Result<usize, Error> {
        match self.response.as_ref() {
            Ok(response) => {

                let bytes_available = response.len() - self.response_index;
                let bytes_to_read = buf.len();
                let bytes_read = cmp::min(bytes_to_read, bytes_available);

                let bytes = &response[
                    self.response_index..self.response_index + bytes_read
                ];

                for (index, b) in bytes.iter().enumerate() {
                    buf[index] = *b;
                }

                self.response_index += bytes_read;

                Ok(bytes_read)

            },
            Err(err) => Err(Error::new(err.kind(), err.description()))
        }
    }
}

impl NetworkStream for MockStream {

    fn peer_addr(&mut self) -> Result<SocketAddr, Error> {
        Err(Error::new(ErrorKind::NotConnected, "noir: Address not mocked."))
    }

    fn set_read_timeout(&self, _: Option<Duration>) -> Result<(), Error> {
        Ok(())
    }

    fn set_write_timeout(&self, _: Option<Duration>) -> Result<(), Error> {
        Ok(())
    }

    fn close(&mut self, _: Shutdown) -> Result<(), Error> {
        Ok(())
    }

}