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
664
665
666
667
668
669
670
671
672
673
674
//! Various helpers for Actix applications to use during testing.
use std::rc::Rc;
use std::str::FromStr;
use std::sync::mpsc;
use std::{net, thread};

use actix_inner::{Actor, Addr, System};

use cookie::Cookie;
use futures::Future;
use http::header::HeaderName;
use http::{HeaderMap, HttpTryFrom, Method, Uri, Version};
use net2::TcpBuilder;
use tokio::runtime::current_thread::Runtime;

#[cfg(feature = "alpn")]
use openssl::ssl::SslAcceptorBuilder;

use application::{App, HttpApplication};
use body::Binary;
use client::{ClientConnector, ClientRequest, ClientRequestBuilder};
use error::Error;
use handler::{AsyncResultItem, Handler, Responder};
use header::{Header, IntoHeaderValue};
use httprequest::HttpRequest;
use httpresponse::HttpResponse;
use middleware::Middleware;
use param::Params;
use payload::Payload;
use resource::Resource;
use router::Router;
use server::message::{Request, RequestPool};
use server::{HttpServer, IntoHttpHandler, ServerSettings};
use uri::Url as InnerUrl;
use ws;

/// The `TestServer` type.
///
/// `TestServer` is very simple test server that simplify process of writing
/// integration tests cases for actix web applications.
///
/// # Examples
///
/// ```rust
/// # extern crate actix_web;
/// # use actix_web::*;
/// #
/// # fn my_handler(req: &HttpRequest) -> HttpResponse {
/// #     HttpResponse::Ok().into()
/// # }
/// #
/// # fn main() {
/// use actix_web::test::TestServer;
///
/// let mut srv = TestServer::new(|app| app.handler(my_handler));
///
/// let req = srv.get().finish().unwrap();
/// let response = srv.execute(req.send()).unwrap();
/// assert!(response.status().is_success());
/// # }
/// ```
pub struct TestServer {
    addr: net::SocketAddr,
    ssl: bool,
    conn: Addr<ClientConnector>,
    rt: Runtime,
}

impl TestServer {
    /// Start new test server
    ///
    /// This method accepts configuration method. You can add
    /// middlewares or set handlers for test application.
    pub fn new<F>(config: F) -> Self
    where
        F: Sync + Send + 'static + Fn(&mut TestApp<()>),
    {
        TestServerBuilder::new(|| ()).start(config)
    }

    /// Create test server builder
    pub fn build() -> TestServerBuilder<()> {
        TestServerBuilder::new(|| ())
    }

    /// Create test server builder with specific state factory
    ///
    /// This method can be used for constructing application state.
    /// Also it can be used for external dependency initialization,
    /// like creating sync actors for diesel integration.
    pub fn build_with_state<F, S>(state: F) -> TestServerBuilder<S>
    where
        F: Fn() -> S + Sync + Send + 'static,
        S: 'static,
    {
        TestServerBuilder::new(state)
    }

    /// Start new test server with application factory
    pub fn with_factory<F, U, H>(factory: F) -> Self
    where
        F: Fn() -> U + Sync + Send + 'static,
        U: IntoIterator<Item = H> + 'static,
        H: IntoHttpHandler + 'static,
    {
        let (tx, rx) = mpsc::channel();

        // run server in separate thread
        thread::spawn(move || {
            let sys = System::new("actix-test-server");
            let tcp = net::TcpListener::bind("127.0.0.1:0").unwrap();
            let local_addr = tcp.local_addr().unwrap();

            HttpServer::new(factory)
                .disable_signals()
                .listen(tcp)
                .start();

            tx.send((System::current(), local_addr, TestServer::get_conn()))
                .unwrap();
            sys.run();
        });

        let (system, addr, conn) = rx.recv().unwrap();
        System::set_current(system);
        TestServer {
            addr,
            conn,
            ssl: false,
            rt: Runtime::new().unwrap(),
        }
    }

    fn get_conn() -> Addr<ClientConnector> {
        #[cfg(feature = "alpn")]
        {
            use openssl::ssl::{SslConnector, SslMethod, SslVerifyMode};

            let mut builder = SslConnector::builder(SslMethod::tls()).unwrap();
            builder.set_verify(SslVerifyMode::NONE);
            ClientConnector::with_connector(builder.build()).start()
        }
        #[cfg(not(feature = "alpn"))]
        {
            ClientConnector::default().start()
        }
    }

    /// Get firat available unused address
    pub fn unused_addr() -> net::SocketAddr {
        let addr: net::SocketAddr = "127.0.0.1:0".parse().unwrap();
        let socket = TcpBuilder::new_v4().unwrap();
        socket.bind(&addr).unwrap();
        socket.reuse_address(true).unwrap();
        let tcp = socket.to_tcp_listener().unwrap();
        tcp.local_addr().unwrap()
    }

    /// Construct test server url
    pub fn addr(&self) -> net::SocketAddr {
        self.addr
    }

    /// Construct test server url
    pub fn url(&self, uri: &str) -> String {
        if uri.starts_with('/') {
            format!(
                "{}://{}{}",
                if self.ssl { "https" } else { "http" },
                self.addr,
                uri
            )
        } else {
            format!(
                "{}://{}/{}",
                if self.ssl { "https" } else { "http" },
                self.addr,
                uri
            )
        }
    }

    /// Stop http server
    fn stop(&mut self) {
        System::current().stop();
    }

    /// Execute future on current core
    pub fn execute<F, I, E>(&mut self, fut: F) -> Result<I, E>
    where
        F: Future<Item = I, Error = E>,
    {
        self.rt.block_on(fut)
    }

    /// Connect to websocket server
    pub fn ws(
        &mut self,
    ) -> Result<(ws::ClientReader, ws::ClientWriter), ws::ClientError> {
        let url = self.url("/");
        self.rt
            .block_on(ws::Client::with_connector(url, self.conn.clone()).connect())
    }

    /// Create `GET` request
    pub fn get(&self) -> ClientRequestBuilder {
        ClientRequest::get(self.url("/").as_str())
    }

    /// Create `POST` request
    pub fn post(&self) -> ClientRequestBuilder {
        ClientRequest::post(self.url("/").as_str())
    }

    /// Create `HEAD` request
    pub fn head(&self) -> ClientRequestBuilder {
        ClientRequest::head(self.url("/").as_str())
    }

    /// Connect to test http server
    pub fn client(&self, meth: Method, path: &str) -> ClientRequestBuilder {
        ClientRequest::build()
            .method(meth)
            .uri(self.url(path).as_str())
            .with_connector(self.conn.clone())
            .take()
    }
}

impl Drop for TestServer {
    fn drop(&mut self) {
        self.stop()
    }
}

/// An `TestServer` builder
///
/// This type can be used to construct an instance of `TestServer` through a
/// builder-like pattern.
pub struct TestServerBuilder<S> {
    state: Box<Fn() -> S + Sync + Send + 'static>,
    #[cfg(feature = "alpn")]
    ssl: Option<SslAcceptorBuilder>,
}

impl<S: 'static> TestServerBuilder<S> {
    /// Create a new test server
    pub fn new<F>(state: F) -> TestServerBuilder<S>
    where
        F: Fn() -> S + Sync + Send + 'static,
    {
        TestServerBuilder {
            state: Box::new(state),
            #[cfg(feature = "alpn")]
            ssl: None,
        }
    }

    #[cfg(feature = "alpn")]
    /// Create ssl server
    pub fn ssl(mut self, ssl: SslAcceptorBuilder) -> Self {
        self.ssl = Some(ssl);
        self
    }

    #[allow(unused_mut)]
    /// Configure test application and run test server
    pub fn start<F>(mut self, config: F) -> TestServer
    where
        F: Sync + Send + 'static + Fn(&mut TestApp<S>),
    {
        let (tx, rx) = mpsc::channel();

        #[cfg(feature = "alpn")]
        let ssl = self.ssl.is_some();
        #[cfg(not(feature = "alpn"))]
        let ssl = false;

        // run server in separate thread
        thread::spawn(move || {
            let tcp = net::TcpListener::bind("127.0.0.1:0").unwrap();
            let local_addr = tcp.local_addr().unwrap();

            let sys = System::new("actix-test-server");
            let state = self.state;
            let srv = HttpServer::new(move || {
                let mut app = TestApp::new(state());
                config(&mut app);
                vec![app]
            }).workers(1)
                .disable_signals();

            tx.send((System::current(), local_addr, TestServer::get_conn()))
                .unwrap();

            #[cfg(feature = "alpn")]
            {
                let ssl = self.ssl.take();
                if let Some(ssl) = ssl {
                    srv.listen_ssl(tcp, ssl).unwrap().start();
                } else {
                    srv.listen(tcp).start();
                }
            }
            #[cfg(not(feature = "alpn"))]
            {
                srv.listen(tcp).start();
            }
            sys.run();
        });

        let (system, addr, conn) = rx.recv().unwrap();
        System::set_current(system);
        TestServer {
            addr,
            ssl,
            conn,
            rt: Runtime::new().unwrap(),
        }
    }
}

/// Test application helper for testing request handlers.
pub struct TestApp<S = ()> {
    app: Option<App<S>>,
}

impl<S: 'static> TestApp<S> {
    fn new(state: S) -> TestApp<S> {
        let app = App::with_state(state);
        TestApp { app: Some(app) }
    }

    /// Register handler for "/"
    pub fn handler<F, R>(&mut self, handler: F)
    where
        F: Fn(&HttpRequest<S>) -> R + 'static,
        R: Responder + 'static,
    {
        self.app = Some(self.app.take().unwrap().resource("/", |r| r.f(handler)));
    }

    /// Register middleware
    pub fn middleware<T>(&mut self, mw: T) -> &mut TestApp<S>
    where
        T: Middleware<S> + 'static,
    {
        self.app = Some(self.app.take().unwrap().middleware(mw));
        self
    }

    /// Register resource. This method is similar
    /// to `App::resource()` method.
    pub fn resource<F, R>(&mut self, path: &str, f: F) -> &mut TestApp<S>
    where
        F: FnOnce(&mut Resource<S>) -> R + 'static,
    {
        self.app = Some(self.app.take().unwrap().resource(path, f));
        self
    }
}

impl<S: 'static> IntoHttpHandler for TestApp<S> {
    type Handler = HttpApplication<S>;

    fn into_handler(mut self) -> HttpApplication<S> {
        self.app.take().unwrap().into_handler()
    }
}

#[doc(hidden)]
impl<S: 'static> Iterator for TestApp<S> {
    type Item = HttpApplication<S>;

    fn next(&mut self) -> Option<Self::Item> {
        if let Some(mut app) = self.app.take() {
            Some(app.finish())
        } else {
            None
        }
    }
}

/// Test `HttpRequest` builder
///
/// ```rust
/// # extern crate http;
/// # extern crate actix_web;
/// # use http::{header, StatusCode};
/// # use actix_web::*;
/// use actix_web::test::TestRequest;
///
/// fn index(req: &HttpRequest) -> HttpResponse {
///     if let Some(hdr) = req.headers().get(header::CONTENT_TYPE) {
///         HttpResponse::Ok().into()
///     } else {
///         HttpResponse::BadRequest().into()
///     }
/// }
///
/// fn main() {
///     let resp = TestRequest::with_header("content-type", "text/plain")
///         .run(&index)
///         .unwrap();
///     assert_eq!(resp.status(), StatusCode::OK);
///
///     let resp = TestRequest::default().run(&index).unwrap();
///     assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
/// }
/// ```
pub struct TestRequest<S> {
    state: S,
    version: Version,
    method: Method,
    uri: Uri,
    headers: HeaderMap,
    params: Params,
    cookies: Option<Vec<Cookie<'static>>>,
    payload: Option<Payload>,
    prefix: u16,
}

impl Default for TestRequest<()> {
    fn default() -> TestRequest<()> {
        TestRequest {
            state: (),
            method: Method::GET,
            uri: Uri::from_str("/").unwrap(),
            version: Version::HTTP_11,
            headers: HeaderMap::new(),
            params: Params::new(),
            cookies: None,
            payload: None,
            prefix: 0,
        }
    }
}

impl TestRequest<()> {
    /// Create TestRequest and set request uri
    pub fn with_uri(path: &str) -> TestRequest<()> {
        TestRequest::default().uri(path)
    }

    /// Create TestRequest and set header
    pub fn with_hdr<H: Header>(hdr: H) -> TestRequest<()> {
        TestRequest::default().set(hdr)
    }

    /// Create TestRequest and set header
    pub fn with_header<K, V>(key: K, value: V) -> TestRequest<()>
    where
        HeaderName: HttpTryFrom<K>,
        V: IntoHeaderValue,
    {
        TestRequest::default().header(key, value)
    }
}

impl<S: 'static> TestRequest<S> {
    /// Start HttpRequest build process with application state
    pub fn with_state(state: S) -> TestRequest<S> {
        TestRequest {
            state,
            method: Method::GET,
            uri: Uri::from_str("/").unwrap(),
            version: Version::HTTP_11,
            headers: HeaderMap::new(),
            params: Params::new(),
            cookies: None,
            payload: None,
            prefix: 0,
        }
    }

    /// Set HTTP version of this request
    pub fn version(mut self, ver: Version) -> Self {
        self.version = ver;
        self
    }

    /// Set HTTP method of this request
    pub fn method(mut self, meth: Method) -> Self {
        self.method = meth;
        self
    }

    /// Set HTTP Uri of this request
    pub fn uri(mut self, path: &str) -> Self {
        self.uri = Uri::from_str(path).unwrap();
        self
    }

    /// Set a header
    pub fn set<H: Header>(mut self, hdr: H) -> Self {
        if let Ok(value) = hdr.try_into() {
            self.headers.append(H::name(), value);
            return self;
        }
        panic!("Can not set header");
    }

    /// Set a header
    pub fn header<K, V>(mut self, key: K, value: V) -> Self
    where
        HeaderName: HttpTryFrom<K>,
        V: IntoHeaderValue,
    {
        if let Ok(key) = HeaderName::try_from(key) {
            if let Ok(value) = value.try_into() {
                self.headers.append(key, value);
                return self;
            }
        }
        panic!("Can not create header");
    }

    /// Set request path pattern parameter
    pub fn param(mut self, name: &'static str, value: &'static str) -> Self {
        self.params.add_static(name, value);
        self
    }

    /// Set request payload
    pub fn set_payload<B: Into<Binary>>(mut self, data: B) -> Self {
        let mut data = data.into();
        let mut payload = Payload::empty();
        payload.unread_data(data.take());
        self.payload = Some(payload);
        self
    }

    /// Set request's prefix
    pub fn prefix(mut self, prefix: u16) -> Self {
        self.prefix = prefix;
        self
    }

    /// Complete request creation and generate `HttpRequest` instance
    pub fn finish(self) -> HttpRequest<S> {
        let TestRequest {
            state,
            method,
            uri,
            version,
            headers,
            mut params,
            cookies,
            payload,
            prefix,
        } = self;
        let router = Router::<()>::new();

        let pool = RequestPool::pool(ServerSettings::default());
        let mut req = RequestPool::get(pool);
        {
            let inner = req.inner_mut();
            inner.method = method;
            inner.url = InnerUrl::new(uri);
            inner.version = version;
            inner.headers = headers;
            *inner.payload.borrow_mut() = payload;
        }
        params.set_url(req.url().clone());
        let mut info = router.route_info_params(0, params);
        info.set_prefix(prefix);

        let mut req = HttpRequest::new(req, Rc::new(state), info);
        req.set_cookies(cookies);
        req
    }

    #[cfg(test)]
    /// Complete request creation and generate `HttpRequest` instance
    pub(crate) fn finish_with_router(self, router: Router<S>) -> HttpRequest<S> {
        let TestRequest {
            state,
            method,
            uri,
            version,
            headers,
            mut params,
            cookies,
            payload,
            prefix,
        } = self;

        let pool = RequestPool::pool(ServerSettings::default());
        let mut req = RequestPool::get(pool);
        {
            let inner = req.inner_mut();
            inner.method = method;
            inner.url = InnerUrl::new(uri);
            inner.version = version;
            inner.headers = headers;
            *inner.payload.borrow_mut() = payload;
        }
        params.set_url(req.url().clone());
        let mut info = router.route_info_params(0, params);
        info.set_prefix(prefix);
        let mut req = HttpRequest::new(req, Rc::new(state), info);
        req.set_cookies(cookies);
        req
    }

    /// Complete request creation and generate server `Request` instance
    pub fn request(self) -> Request {
        let TestRequest {
            method,
            uri,
            version,
            headers,
            payload,
            ..
        } = self;

        let pool = RequestPool::pool(ServerSettings::default());
        let mut req = RequestPool::get(pool);
        {
            let inner = req.inner_mut();
            inner.method = method;
            inner.url = InnerUrl::new(uri);
            inner.version = version;
            inner.headers = headers;
            *inner.payload.borrow_mut() = payload;
        }
        req
    }

    /// This method generates `HttpRequest` instance and runs handler
    /// with generated request.
    ///
    /// This method panics is handler returns actor or async result.
    pub fn run<H: Handler<S>>(self, h: &H) -> Result<HttpResponse, Error> {
        let req = self.finish();
        let resp = h.handle(&req);

        match resp.respond_to(&req) {
            Ok(resp) => match resp.into().into() {
                AsyncResultItem::Ok(resp) => Ok(resp),
                AsyncResultItem::Err(err) => Err(err),
                AsyncResultItem::Future(_) => panic!("Async handler is not supported."),
            },
            Err(err) => Err(err.into()),
        }
    }

    /// This method generates `HttpRequest` instance and runs handler
    /// with generated request.
    ///
    /// This method panics is handler returns actor.
    pub fn run_async<H, R, F, E>(self, h: H) -> Result<HttpResponse, E>
    where
        H: Fn(HttpRequest<S>) -> F + 'static,
        F: Future<Item = R, Error = E> + 'static,
        R: Responder<Error = E> + 'static,
        E: Into<Error> + 'static,
    {
        let req = self.finish();
        let fut = h(req.clone());

        let mut core = Runtime::new().unwrap();
        match core.block_on(fut) {
            Ok(r) => match r.respond_to(&req) {
                Ok(reply) => match reply.into().into() {
                    AsyncResultItem::Ok(resp) => Ok(resp),
                    _ => panic!("Nested async replies are not supported"),
                },
                Err(e) => Err(e),
            },
            Err(err) => Err(err),
        }
    }
}