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
//! A crate for testing [Iron](https://crates.io/crates/iron) handlers and middleware
//!
//! This crate generates requests in a very similar way to
//! [iron-test](https://crates.io/crates/iron-test) but allows the testing of
//! individual middleware in isolation.  
//!
//! ## Example
//! ```
//! #[test]
//! fn anneal_demo() {
//!     RequestBuilder::new(Method::Post, "https://127.0.0.1:8080/")
//!         .set_header(headers::ContentType::json())
//!         .set_body("this is a body".into())
//!         .request(|mut req| {
//!             let mut headers = Headers::new();
//!             headers.set(headers::ContentLength(14));
//!             headers.set(headers::UserAgent("anneal".into()));
//!             headers.set(headers::ContentType::json());
//!             assert_eq!(req.headers, headers);
//!             assert_eq!(req.method,  Method::Post);
//!             assert_eq!(req.url, "https://127.0.0.1:8080/".parse().unwrap());
//!             assert_eq!(req.local_addr, "127.0.0.1:8080".parse().unwrap());
//!             assert_eq!(req.remote_addr, "127.0.0.1:3000".parse().unwrap());
//!             assert_eq!(req.version, HttpVersion::Http11);
//!
//!             let mut s = String::new();
//!             req.body.read_to_string(&mut s).unwrap();
//!             assert_eq!(s, "this is a body");
//!         })
//! }
//! ```
//!
//! ## Features
//! `cookies`: adds a method to add a `CookieJar` from 
//! [cookie](https://crates.io/crates/cookie) to the request
//! 
//! `json`: adds a method to set the body to a json object via 
//! [serde_json](https://crates.io/crates/serde_json)
//!
//! `jsonapi`: adds a pair of methods for adding 
//! [json-api](https://github.com/qaul/json-api) documents to a request body

use hyper::{
    self,
    buffer::BufReader,
    client::{
        Body,
        Client, 
        IntoUrl,
    },
    error::ParseError,
    net::NetworkStream,
    Url,
};
use iron::{
    method::Method,
    middleware::BeforeMiddleware,
    headers::{
        self,
        Header, 
        HeaderFormat
    },
    Headers,
    Request,
    Response,
    IronResult,
    request::HttpRequest,
    Protocol,
};
use std::{
    io::Cursor,
    net::{
        IpAddr,
        Ipv4Addr,
        SocketAddr,
    },
};
use url::Host;

mod transfer_connector;
use transfer_connector::TransferConnector;

mod response_examine;
pub use response_examine::ResponseExamine;

pub struct RequestBuilder {
    body: Option<Vec<u8>>,
    headers: Headers,
    method: Method,
    url: Url,
    client_address: SocketAddr,
    chain: Vec<Box<dyn BeforeMiddleware>>,
}

/// Builds a GET request to `http://127.0.0.1:8080/`
impl Default for RequestBuilder {
    fn default() -> Self {
        Self::new(Method::Get, "http://127.0.0.1:8080/").unwrap()
    }
}

impl RequestBuilder {
    /// Create a new request builder with the given method and url
    ///
    /// An error will be returned if the url fails to parse
    pub fn new<U: IntoUrl>(method: Method, url: U) -> Result<RequestBuilder, ParseError> {
        let mut h = Headers::new();
        h.set(headers::UserAgent("anneal".into()));

        Ok(RequestBuilder {
            body: None,
            headers: h,
            method,
            url: url.into_url()?,
            client_address: "127.0.0.1:3000".parse().unwrap(),
            chain: Vec::new(),
        })
    }

    /// Shorthand for `RequestBuilder::new(Method::Get, url)`
    pub fn get<U: IntoUrl>(url: U) -> Result<RequestBuilder, ParseError> {
        Self::new(Method::Get, url)
    }

    /// Shorthand for `RequestBuilder::new(Method::Post, url)`
    pub fn post<U: IntoUrl>(url: U) -> Result<RequestBuilder, ParseError> {
        Self::new(Method::Post, url)
    }

    /// Shorthand for `RequestBuilder::new(Method::Options, url)`
    pub fn options<U: IntoUrl>(url: U) -> Result<RequestBuilder, ParseError> {
        Self::new(Method::Options, url)
    }

    /// Shorthand for `RequestBuilder::new(Method::Put, url)`
    pub fn put<U: IntoUrl>(url: U) -> Result<RequestBuilder, ParseError> {
        Self::new(Method::Put, url)
    }

    /// Shorthand for `RequestBuilder::new(Method::Delete, url)`
    pub fn delete<U: IntoUrl>(url: U) -> Result<RequestBuilder, ParseError> {
        Self::new(Method::Delete, url)
    }

    /// Shorthand for `RequestBuilder::new(Method::Head, url)`
    pub fn head<U: IntoUrl>(url: U) -> Result<RequestBuilder, ParseError> {
        Self::new(Method::Head, url)
    }

    /// Shorthand for `RequestBuilder::new(Method::Trace, url)`
    pub fn trace<U: IntoUrl>(url: U) -> Result<RequestBuilder, ParseError> {
        Self::new(Method::Trace, url)
    }

    /// Shorthand for `RequestBuilder::new(Method::Connect, url)`
    pub fn connect<U: IntoUrl>(url: U) -> Result<RequestBuilder, ParseError> {
        Self::new(Method::Connect, url)
    }

    /// Shorthand for `RequestBuilder::new(Method::Patch, url)`
    pub fn patch<U: IntoUrl>(url: U) -> Result<RequestBuilder, ParseError> {
        Self::new(Method::Patch, url)
    }

    /// Builds a POST request to `http://127.0.0.1:8080/` 
    pub fn default_post() -> Self {
        Self::new(Method::Post, "http://127.0.0.1:8080/").unwrap()
    }

    /// Set an individual header
    pub fn set_header<H: Header + HeaderFormat>(&mut self, header: H) -> &mut Self {
        self.headers.set(header);
        self
    }

    /// Replace the headers with a new `Headers` struct
    pub fn set_headers(&mut self, headers: Headers) -> &mut Self {
        self.headers = headers;
        self
    }

    /// Change the destination url of this request
    pub fn set_url<U: IntoUrl>(&mut self, url: U) -> Result<&mut Self, ParseError> {
        self.url = url.into_url()?;
        Ok(self)
    }

    /// Change this request's method
    pub fn set_method(&mut self, method: Method) -> &mut Self {
        self.method = method;
        self 
    }

    /// Set the body of the request to the provided vec
    pub fn set_bytes(&mut self, body: Vec<u8>) -> &mut Self {
        self.body = Some(body);
        self
    }

    /// Set the body of the request to the provided string
    pub fn set_string(&mut self, body: &str) -> &mut Self {
        self.body = Some(body.as_bytes().to_vec());
        self
    }

    /// Add `BeforeMiddleware` to be run before the main handler
    ///
    /// This adds middleware after all that is currently on the chain.
    /// If the middleware in this chain fails while building a request the request
    /// will `panic`.
    pub fn add_middleware<B: BeforeMiddleware + 'static>(&mut self, middleware: B) -> &mut Self {
        self.chain.push(Box::new(middleware));
        self
    }

    /// Set the middleware chain to be run before the main handler
    pub fn set_chain(&mut self, chain: Vec<Box<dyn BeforeMiddleware>>) -> &mut Self {
        self.chain = chain;
        self
    }

    #[cfg(feature = "cookies")]
    /// Set the `Cookie` header of the request
    pub fn set_cookies(&mut self, cookies: &cookie::CookieJar) -> &mut Self {
        let cookies : Vec<String> = cookies.iter()
            .map(|c| c.to_string())
            .collect();

        if cookies.len() != 0 { self.headers.set::<headers::Cookie>(headers::Cookie(cookies)); }

        self
    }

    #[cfg(feature = "json")]
    /// Set the main body of the request to contain serialized json
    ///
    /// This also sets the `Content-Type` header to `application/json`
    pub fn set_json<T: serde::Serialize>(&mut self, json: &T) -> &mut Self {
        self.body = Some(serde_json::to_vec(json).unwrap());
        self.headers.set::<headers::ContentType>(headers::ContentType::json());
        self
    }

    #[cfg(feature = "jsonapi")]
    fn jsonapi_mime() -> iron::mime::Mime {
        use iron::mime;
        mime::Mime(
            mime::TopLevel::Application,
            mime::SubLevel::Ext(String::from("vnd.api+json")),
            Vec::new())
    }

    #[cfg(feature = "jsonapi")]
    /// Set the body of the request to a serialized `Document`
    ///
    /// This also sets the `Content-Type` to `application/vnd.api+json`
    pub fn set_document(&mut self, doc: &japi::Document) -> &mut Self {
        self.body = Some(serde_json::to_vec(&doc).unwrap());
        self.headers.set::<headers::ContentType>(headers::ContentType(Self::jsonapi_mime()));

        self
    }

    #[cfg(feature = "jsonapi")]
    /// Set the body of the request to a a JSON:API Document with a single
    /// primary data member specified by `obj`
    ///
    /// This also sets the `Content-Type` to `application/vnd.api+json`
    pub fn set_primary_data(&mut self, obj: japi::GenericObject) -> &mut Self {
        let document = japi::Document {
            data: japi::OptionalVec::One(Some(obj)),
            ..Default::default()
        };
        self.body = Some(serde_json::to_vec(&document).unwrap());
        self.headers.set::<headers::ContentType>(headers::ContentType(Self::jsonapi_mime()));

        self
    }

    /// Generate a request and hand it off to some handler function
    /// 
    /// This will panic if any of the middleware in the before chain fails
    /// 
    /// The return value of the handler function will be return value of
    /// this function
    pub fn request<T, H: FnOnce(Request) -> T>(&self, handler: H) -> T {
        let tc = TransferConnector::new("127.0.0.1:3000".parse().unwrap());

        let client = Client::with_connector(tc.clone());
        let rb = client.request(self.method.clone(), self.url.clone())
            .headers(self.headers.clone());
        let rb = if let Some(b) = &self.body {
            rb.body(Body::BufBody(&b[..], b.len()))
        } else { rb };
        // this will cause the client to fill the transfer connector's buffer with
        // the request data
        // it will also error because the ClientStream returns and error to it
        // but we don't care about that
        rb.send(); 

        let proto = match tc.scheme.lock().expect("proto scheme lock")
                .as_ref().expect("proto scheme not set").as_str() {
            "http" => Protocol::http(),
            "https" => Protocol::https(),
            s => panic!("Unknown Scheme: {}", s),
        };

        let mut serv_stream = tc.server_stream();
        let mut buff_read = BufReader::new(&mut serv_stream as &mut NetworkStream);
        let http_request = HttpRequest::new(&mut buff_read, tc.client_address)
            .expect("build http request");
        let mut r = Request::from_http(
            http_request, 
            tc.server_address.lock().expect("server address lock").clone()
                .expect("server address not set"), 
            &proto).expect("build request");

        for middleware in &self.chain { middleware.before(&mut r).unwrap(); }

        handler(r)
    }

    /// Generate a request and hand it off to a handler function, 
    /// mapping the response into a `ResponseExamine` for easier checking
    pub fn request_response<H: FnOnce(Request) -> IronResult<Response>>(&self, handler: H) 
    -> IronResult<ResponseExamine> {
        self.request(handler).map(|r| ResponseExamine::new(r))
    }
}

#[cfg(test)]
mod test {
    use super::*;
    use hyper::version::HttpVersion;
    use std::io::Read;

    #[test]
    fn base() {
        RequestBuilder::new(Method::Get, "http://127.0.0.1:8080/").unwrap().request(|req| {
            let mut headers = Headers::new();
            headers.set(headers::Host{hostname: "127.0.0.1".into(), port: Some(8080)});
            headers.set(headers::UserAgent("anneal".into()));
            assert_eq!(req.headers, headers);
            assert_eq!(req.method,  Method::Get);
            assert_eq!(req.url, "http://127.0.0.1:8080/".parse().unwrap());
            assert_eq!(req.local_addr, "127.0.0.1:8080".parse().unwrap());
            assert_eq!(req.remote_addr, "127.0.0.1:3000".parse().unwrap());
            assert_eq!(req.body.bytes().count(), 0);
            assert_eq!(req.version, HttpVersion::Http11);
        });
    }

    #[test]
    fn full() {
        RequestBuilder::new(Method::Post, "https://127.0.0.1:8080/").unwrap()
            .set_header(headers::ContentType::json())
            .set_string("this is a body".into())
            .request(|mut req| {
                let mut headers = Headers::new();
                headers.set(headers::ContentLength(14));
                headers.set(headers::UserAgent("anneal".into()));
                headers.set(headers::Host{hostname: "127.0.0.1".into(), port: Some(8080)});
                headers.set(headers::ContentType::json());
                assert_eq!(req.headers, headers);
                assert_eq!(req.method,  Method::Post);
                assert_eq!(req.url, "https://127.0.0.1:8080/".parse().unwrap());
                assert_eq!(req.local_addr, "127.0.0.1:8080".parse().unwrap());
                assert_eq!(req.remote_addr, "127.0.0.1:3000".parse().unwrap());
                assert_eq!(req.version, HttpVersion::Http11);

                let mut s = String::new();
                req.body.read_to_string(&mut s).unwrap();
                assert_eq!(s, "this is a body");
            })
    }

    #[test]
    fn constructors() {
        fn assert_kind(rb: RequestBuilder, method: Method) {
            rb.request(|req| {
                assert_eq!(req.url, "http://127.0.0.1:8080/".parse().unwrap());
                assert_eq!(req.method, method);
            });
        }

        assert_kind(RequestBuilder::default(), Method::Get);
        assert_kind(RequestBuilder::default_post(), Method::Post);
        assert_kind(RequestBuilder::options("http://127.0.0.1:8080/").unwrap(), Method::Options);
        assert_kind(RequestBuilder::get("http://127.0.0.1:8080/").unwrap(), Method::Get);
        assert_kind(RequestBuilder::post("http://127.0.0.1:8080/").unwrap(), Method::Post);
        assert_kind(RequestBuilder::put("http://127.0.0.1:8080/").unwrap(), Method::Put);
        assert_kind(RequestBuilder::delete("http://127.0.0.1:8080/").unwrap(), Method::Delete);
        assert_kind(RequestBuilder::head("http://127.0.0.1:8080/").unwrap(), Method::Head);
        assert_kind(RequestBuilder::trace("http://127.0.0.1:8080/").unwrap(), Method::Trace);
        assert_kind(RequestBuilder::connect("http://127.0.0.1:8080/").unwrap(), Method::Connect);
        assert_kind(RequestBuilder::patch("http://127.0.0.1:8080/").unwrap(), Method::Patch);
    }

    #[test]
    fn middleware() {
        pub struct TestMiddleware(u8);
        impl iron::typemap::Key for TestMiddleware { type Value = Vec<u8>; }
        impl BeforeMiddleware for TestMiddleware {
            fn before(&self, req: &mut Request) -> IronResult<()> {
                if let Some(mut tm) = req.extensions.get_mut::<TestMiddleware>() {
                    tm.push(self.0);
                } else { req.extensions.insert::<TestMiddleware>(vec![self.0]); }
                Ok(())
            }
        }

        RequestBuilder::default()
            .add_middleware(TestMiddleware(0))
            .set_chain(vec![Box::new(TestMiddleware(1)), Box::new(TestMiddleware(2))])
            .add_middleware(TestMiddleware(3))
            .request(|req| {
                assert_eq!(req.extensions.get::<TestMiddleware>().unwrap(), &vec![1,2,3]);
            });
    }

    #[cfg(feature = "cookies")]
    #[test]
    fn cookies() {
        use cookie::{CookieJar, Cookie};
        let mut jar = CookieJar::new();
        jar.add(Cookie::new("a", "b"));
        jar.add(Cookie::new("c", "d"));

        RequestBuilder::new(Method::Get, "https://127.0.0.1:8080/").unwrap()
            .set_cookies(&jar)
            .request(|req| {
                let cookies = req.headers.get::<headers::Cookie>().unwrap();
                assert_eq!(cookies.len(), 2);

                for cookie in cookies.iter() {
                    let c = Cookie::parse(cookie).unwrap();
                    assert_eq!(&c, jar.get(c.name()).unwrap());
                }

            })
    }

    #[cfg(feature = "json")]
    #[test]
    fn json() {
        RequestBuilder::new(Method::Post, "https://127.0.0.1:8080/").unwrap()
            .set_json(&serde_json::json!({"a": "b"}))
            .request(|mut req| {
                assert_eq!(req.headers.get::<headers::ContentType>().unwrap(),
                    &headers::ContentType::json());
                let mut s = String::new();
                req.body.read_to_string(&mut s).unwrap();
                assert_eq!(s, "{\"a\":\"b\"}");
            })
    }

    #[cfg(feature = "jsonapi")]
    #[test]
    fn jsonapi_document() {
        use japi::{
            Document,
            OptionalVec,
            Identifier,
        };
        RequestBuilder::new(Method::Post, "https://127.0.0.1:8080/").unwrap()
            .set_document(&Document {
                data: OptionalVec::One(Some(Identifier::new("a".into(), "b".into()).into())),
                ..Default::default()
            })
            .request(|mut req| {
                assert_eq!(req.headers.get::<headers::ContentType>().unwrap(), 
                           &headers::ContentType(RequestBuilder::jsonapi_mime()));
                let mut s = String::new();
                req.body.read_to_string(&mut s).unwrap();
                assert_eq!(s, "{\"data\":{\"id\":\"a\",\"type\":\"b\"}}");
            })
    }

    #[cfg(feature = "jsonapi")]
    #[test]
    fn jsonapi_object() {
        RequestBuilder::new(Method::Post, "https://127.0.0.1:8080/").unwrap()
            .set_primary_data(japi::Identifier::new("a".into(), "b".into()).into())
            .request(|mut req| {
                assert_eq!(req.headers.get::<headers::ContentType>().unwrap(), 
                           &headers::ContentType(RequestBuilder::jsonapi_mime()));
                let mut s = String::new();
                req.body.read_to_string(&mut s).unwrap();
                assert_eq!(s, "{\"data\":{\"id\":\"a\",\"type\":\"b\"}}");
            })
    }
}