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
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
//! Integration testing tools for Actix Web applications.
//!
//! The main integration testing tool is [`TestServer`]. It spawns a real HTTP server on an
//! unused port and provides methods that use a real HTTP client. Therefore, it is much closer to
//! real-world cases than using `init_service`, which skips HTTP encoding and decoding.
//!
//! # Examples
//! ```
//! use actix_web::{get, web, test, App, HttpResponse, Error, Responder};
//!
//! #[get("/")]
//! async fn my_handler() -> Result<impl Responder, Error> {
//!     Ok(HttpResponse::Ok())
//! }
//!
//! #[actix_rt::test]
//! async fn test_example() {
//!     let srv = actix_test::start(||
//!         App::new().service(my_handler)
//!     );
//!
//!     let req = srv.get("/");
//!     let res = req.send().await.unwrap();
//!
//!     assert!(res.status().is_success());
//! }
//! ```

#![deny(rust_2018_idioms, nonstandard_style)]
#![warn(future_incompatible)]
#![doc(html_logo_url = "https://actix.rs/img/logo.png")]
#![doc(html_favicon_url = "https://actix.rs/favicon.ico")]
#![cfg_attr(docsrs, feature(doc_auto_cfg))]

#[cfg(feature = "openssl")]
extern crate tls_openssl as openssl;

use std::{fmt, net, thread, time::Duration};

use actix_codec::{AsyncRead, AsyncWrite, Framed};
pub use actix_http::{body::to_bytes, test::TestBuffer};
use actix_http::{header::HeaderMap, ws, HttpService, Method, Request, Response};
pub use actix_http_test::unused_addr;
use actix_service::{map_config, IntoServiceFactory, ServiceFactory, ServiceFactoryExt as _};
pub use actix_web::test::{
    call_and_read_body, call_and_read_body_json, call_service, init_service, ok_service, read_body,
    read_body_json, status_service, TestRequest,
};
use actix_web::{
    body::MessageBody,
    dev::{AppConfig, Server, ServerHandle, Service},
    rt::{self, System},
    web, Error,
};
pub use awc::{error::PayloadError, Client, ClientRequest, ClientResponse, Connector};
use futures_core::Stream;
use tokio::sync::mpsc;

/// Start default [`TestServer`].
///
/// # Examples
/// ```
/// use actix_web::{get, web, test, App, HttpResponse, Error, Responder};
///
/// #[get("/")]
/// async fn my_handler() -> Result<impl Responder, Error> {
///     Ok(HttpResponse::Ok())
/// }
///
/// #[actix_web::test]
/// async fn test_example() {
///     let srv = actix_test::start(||
///         App::new().service(my_handler)
///     );
///
///     let req = srv.get("/");
///     let res = req.send().await.unwrap();
///
///     assert!(res.status().is_success());
/// }
/// ```
pub fn start<F, I, S, B>(factory: F) -> TestServer
where
    F: Fn() -> I + Send + Clone + 'static,
    I: IntoServiceFactory<S, Request>,
    S: ServiceFactory<Request, Config = AppConfig> + 'static,
    S::Error: Into<Error> + 'static,
    S::InitError: fmt::Debug,
    S::Response: Into<Response<B>> + 'static,
    <S::Service as Service<Request>>::Future: 'static,
    B: MessageBody + 'static,
{
    start_with(TestServerConfig::default(), factory)
}

/// Start test server with custom configuration
///
/// Check [`TestServerConfig`] docs for configuration options.
///
/// # Examples
/// ```
/// use actix_web::{get, web, test, App, HttpResponse, Error, Responder};
///
/// #[get("/")]
/// async fn my_handler() -> Result<impl Responder, Error> {
///     Ok(HttpResponse::Ok())
/// }
///
/// #[actix_web::test]
/// async fn test_example() {
///     let srv = actix_test::start_with(actix_test::config().h1(), ||
///         App::new().service(my_handler)
///     );
///
///     let req = srv.get("/");
///     let res = req.send().await.unwrap();
///
///     assert!(res.status().is_success());
/// }
/// ```
pub fn start_with<F, I, S, B>(cfg: TestServerConfig, factory: F) -> TestServer
where
    F: Fn() -> I + Send + Clone + 'static,
    I: IntoServiceFactory<S, Request>,
    S: ServiceFactory<Request, Config = AppConfig> + 'static,
    S::Error: Into<Error> + 'static,
    S::InitError: fmt::Debug,
    S::Response: Into<Response<B>> + 'static,
    <S::Service as Service<Request>>::Future: 'static,
    B: MessageBody + 'static,
{
    // for sending handles and server info back from the spawned thread
    let (started_tx, started_rx) = std::sync::mpsc::channel();

    // for signaling the shutdown of spawned server and system
    let (thread_stop_tx, thread_stop_rx) = mpsc::channel(1);

    let tls = match cfg.stream {
        StreamType::Tcp => false,
        #[cfg(feature = "openssl")]
        StreamType::Openssl(_) => true,
        #[cfg(feature = "rustls-0_20")]
        StreamType::Rustls020(_) => true,
        #[cfg(feature = "rustls-0_21")]
        StreamType::Rustls021(_) => true,
        #[cfg(feature = "rustls-0_22")]
        StreamType::Rustls022(_) => true,
        #[cfg(feature = "rustls-0_23")]
        StreamType::Rustls023(_) => true,
    };

    // run server in separate orphaned thread
    thread::spawn(move || {
        rt::System::new().block_on(async move {
            let tcp = net::TcpListener::bind(("127.0.0.1", cfg.port)).unwrap();
            let local_addr = tcp.local_addr().unwrap();
            let factory = factory.clone();
            let srv_cfg = cfg.clone();
            let timeout = cfg.client_request_timeout;

            let builder = Server::build()
                .workers(cfg.workers)
                .disable_signals()
                .system_exit();

            let srv = match srv_cfg.stream {
                StreamType::Tcp => match srv_cfg.tp {
                    HttpVer::Http1 => builder.listen("test", tcp, move || {
                        let app_cfg =
                            AppConfig::__priv_test_new(false, local_addr.to_string(), local_addr);

                        let fac = factory()
                            .into_factory()
                            .map_err(|err| err.into().error_response());

                        HttpService::build()
                            .client_request_timeout(timeout)
                            .h1(map_config(fac, move |_| app_cfg.clone()))
                            .tcp()
                    }),
                    HttpVer::Http2 => builder.listen("test", tcp, move || {
                        let app_cfg =
                            AppConfig::__priv_test_new(false, local_addr.to_string(), local_addr);

                        let fac = factory()
                            .into_factory()
                            .map_err(|err| err.into().error_response());

                        HttpService::build()
                            .client_request_timeout(timeout)
                            .h2(map_config(fac, move |_| app_cfg.clone()))
                            .tcp()
                    }),
                    HttpVer::Both => builder.listen("test", tcp, move || {
                        let app_cfg =
                            AppConfig::__priv_test_new(false, local_addr.to_string(), local_addr);

                        let fac = factory()
                            .into_factory()
                            .map_err(|err| err.into().error_response());

                        HttpService::build()
                            .client_request_timeout(timeout)
                            .finish(map_config(fac, move |_| app_cfg.clone()))
                            .tcp()
                    }),
                },
                #[cfg(feature = "openssl")]
                StreamType::Openssl(acceptor) => match cfg.tp {
                    HttpVer::Http1 => builder.listen("test", tcp, move || {
                        let app_cfg =
                            AppConfig::__priv_test_new(false, local_addr.to_string(), local_addr);

                        let fac = factory()
                            .into_factory()
                            .map_err(|err| err.into().error_response());

                        HttpService::build()
                            .client_request_timeout(timeout)
                            .h1(map_config(fac, move |_| app_cfg.clone()))
                            .openssl(acceptor.clone())
                    }),
                    HttpVer::Http2 => builder.listen("test", tcp, move || {
                        let app_cfg =
                            AppConfig::__priv_test_new(false, local_addr.to_string(), local_addr);

                        let fac = factory()
                            .into_factory()
                            .map_err(|err| err.into().error_response());

                        HttpService::build()
                            .client_request_timeout(timeout)
                            .h2(map_config(fac, move |_| app_cfg.clone()))
                            .openssl(acceptor.clone())
                    }),
                    HttpVer::Both => builder.listen("test", tcp, move || {
                        let app_cfg =
                            AppConfig::__priv_test_new(false, local_addr.to_string(), local_addr);

                        let fac = factory()
                            .into_factory()
                            .map_err(|err| err.into().error_response());

                        HttpService::build()
                            .client_request_timeout(timeout)
                            .finish(map_config(fac, move |_| app_cfg.clone()))
                            .openssl(acceptor.clone())
                    }),
                },
                #[cfg(feature = "rustls-0_20")]
                StreamType::Rustls020(config) => match cfg.tp {
                    HttpVer::Http1 => builder.listen("test", tcp, move || {
                        let app_cfg =
                            AppConfig::__priv_test_new(false, local_addr.to_string(), local_addr);

                        let fac = factory()
                            .into_factory()
                            .map_err(|err| err.into().error_response());

                        HttpService::build()
                            .client_request_timeout(timeout)
                            .h1(map_config(fac, move |_| app_cfg.clone()))
                            .rustls(config.clone())
                    }),
                    HttpVer::Http2 => builder.listen("test", tcp, move || {
                        let app_cfg =
                            AppConfig::__priv_test_new(false, local_addr.to_string(), local_addr);

                        let fac = factory()
                            .into_factory()
                            .map_err(|err| err.into().error_response());

                        HttpService::build()
                            .client_request_timeout(timeout)
                            .h2(map_config(fac, move |_| app_cfg.clone()))
                            .rustls(config.clone())
                    }),
                    HttpVer::Both => builder.listen("test", tcp, move || {
                        let app_cfg =
                            AppConfig::__priv_test_new(false, local_addr.to_string(), local_addr);

                        let fac = factory()
                            .into_factory()
                            .map_err(|err| err.into().error_response());

                        HttpService::build()
                            .client_request_timeout(timeout)
                            .finish(map_config(fac, move |_| app_cfg.clone()))
                            .rustls(config.clone())
                    }),
                },
                #[cfg(feature = "rustls-0_21")]
                StreamType::Rustls021(config) => match cfg.tp {
                    HttpVer::Http1 => builder.listen("test", tcp, move || {
                        let app_cfg =
                            AppConfig::__priv_test_new(false, local_addr.to_string(), local_addr);

                        let fac = factory()
                            .into_factory()
                            .map_err(|err| err.into().error_response());

                        HttpService::build()
                            .client_request_timeout(timeout)
                            .h1(map_config(fac, move |_| app_cfg.clone()))
                            .rustls_021(config.clone())
                    }),
                    HttpVer::Http2 => builder.listen("test", tcp, move || {
                        let app_cfg =
                            AppConfig::__priv_test_new(false, local_addr.to_string(), local_addr);

                        let fac = factory()
                            .into_factory()
                            .map_err(|err| err.into().error_response());

                        HttpService::build()
                            .client_request_timeout(timeout)
                            .h2(map_config(fac, move |_| app_cfg.clone()))
                            .rustls_021(config.clone())
                    }),
                    HttpVer::Both => builder.listen("test", tcp, move || {
                        let app_cfg =
                            AppConfig::__priv_test_new(false, local_addr.to_string(), local_addr);

                        let fac = factory()
                            .into_factory()
                            .map_err(|err| err.into().error_response());

                        HttpService::build()
                            .client_request_timeout(timeout)
                            .finish(map_config(fac, move |_| app_cfg.clone()))
                            .rustls_021(config.clone())
                    }),
                },
                #[cfg(feature = "rustls-0_22")]
                StreamType::Rustls022(config) => match cfg.tp {
                    HttpVer::Http1 => builder.listen("test", tcp, move || {
                        let app_cfg =
                            AppConfig::__priv_test_new(false, local_addr.to_string(), local_addr);

                        let fac = factory()
                            .into_factory()
                            .map_err(|err| err.into().error_response());

                        HttpService::build()
                            .client_request_timeout(timeout)
                            .h1(map_config(fac, move |_| app_cfg.clone()))
                            .rustls_0_22(config.clone())
                    }),
                    HttpVer::Http2 => builder.listen("test", tcp, move || {
                        let app_cfg =
                            AppConfig::__priv_test_new(false, local_addr.to_string(), local_addr);

                        let fac = factory()
                            .into_factory()
                            .map_err(|err| err.into().error_response());

                        HttpService::build()
                            .client_request_timeout(timeout)
                            .h2(map_config(fac, move |_| app_cfg.clone()))
                            .rustls_0_22(config.clone())
                    }),
                    HttpVer::Both => builder.listen("test", tcp, move || {
                        let app_cfg =
                            AppConfig::__priv_test_new(false, local_addr.to_string(), local_addr);

                        let fac = factory()
                            .into_factory()
                            .map_err(|err| err.into().error_response());

                        HttpService::build()
                            .client_request_timeout(timeout)
                            .finish(map_config(fac, move |_| app_cfg.clone()))
                            .rustls_0_22(config.clone())
                    }),
                },
                #[cfg(feature = "rustls-0_23")]
                StreamType::Rustls023(config) => match cfg.tp {
                    HttpVer::Http1 => builder.listen("test", tcp, move || {
                        let app_cfg =
                            AppConfig::__priv_test_new(false, local_addr.to_string(), local_addr);

                        let fac = factory()
                            .into_factory()
                            .map_err(|err| err.into().error_response());

                        HttpService::build()
                            .client_request_timeout(timeout)
                            .h1(map_config(fac, move |_| app_cfg.clone()))
                            .rustls_0_23(config.clone())
                    }),
                    HttpVer::Http2 => builder.listen("test", tcp, move || {
                        let app_cfg =
                            AppConfig::__priv_test_new(false, local_addr.to_string(), local_addr);

                        let fac = factory()
                            .into_factory()
                            .map_err(|err| err.into().error_response());

                        HttpService::build()
                            .client_request_timeout(timeout)
                            .h2(map_config(fac, move |_| app_cfg.clone()))
                            .rustls_0_23(config.clone())
                    }),
                    HttpVer::Both => builder.listen("test", tcp, move || {
                        let app_cfg =
                            AppConfig::__priv_test_new(false, local_addr.to_string(), local_addr);

                        let fac = factory()
                            .into_factory()
                            .map_err(|err| err.into().error_response());

                        HttpService::build()
                            .client_request_timeout(timeout)
                            .finish(map_config(fac, move |_| app_cfg.clone()))
                            .rustls_0_23(config.clone())
                    }),
                },
            }
            .expect("test server could not be created");

            let srv = srv.run();
            started_tx
                .send((System::current(), srv.handle(), local_addr))
                .unwrap();

            // drive server loop
            srv.await.unwrap();

            // notify TestServer that server and system have shut down
            // all thread managed resources should be dropped at this point
        });

        #[allow(clippy::let_underscore_future)]
        let _ = thread_stop_tx.send(());
    });

    let (system, server, addr) = started_rx.recv().unwrap();

    let client = {
        let connector = {
            #[cfg(feature = "openssl")]
            {
                use openssl::ssl::{SslConnector, SslMethod, SslVerifyMode};

                let mut builder = SslConnector::builder(SslMethod::tls()).unwrap();
                builder.set_verify(SslVerifyMode::NONE);
                let _ = builder
                    .set_alpn_protos(b"\x02h2\x08http/1.1")
                    .map_err(|err| log::error!("Can not set alpn protocol: {err:?}"));
                Connector::new()
                    .conn_lifetime(Duration::from_secs(0))
                    .timeout(Duration::from_millis(30000))
                    .openssl(builder.build())
            }
            #[cfg(not(feature = "openssl"))]
            {
                Connector::new()
                    .conn_lifetime(Duration::from_secs(0))
                    .timeout(Duration::from_millis(30000))
            }
        };

        Client::builder().connector(connector).finish()
    };

    TestServer {
        server,
        thread_stop_rx,
        client,
        system,
        addr,
        tls,
    }
}

#[derive(Debug, Clone)]
enum HttpVer {
    Http1,
    Http2,
    Both,
}

#[derive(Clone)]
enum StreamType {
    Tcp,
    #[cfg(feature = "openssl")]
    Openssl(openssl::ssl::SslAcceptor),
    #[cfg(feature = "rustls-0_20")]
    Rustls020(tls_rustls_0_20::ServerConfig),
    #[cfg(feature = "rustls-0_21")]
    Rustls021(tls_rustls_0_21::ServerConfig),
    #[cfg(feature = "rustls-0_22")]
    Rustls022(tls_rustls_0_22::ServerConfig),
    #[cfg(feature = "rustls-0_23")]
    Rustls023(tls_rustls_0_23::ServerConfig),
}

/// Create default test server config.
pub fn config() -> TestServerConfig {
    TestServerConfig::default()
}

#[derive(Clone)]
pub struct TestServerConfig {
    tp: HttpVer,
    stream: StreamType,
    client_request_timeout: Duration,
    port: u16,
    workers: usize,
}

impl Default for TestServerConfig {
    fn default() -> Self {
        TestServerConfig::new()
    }
}

impl TestServerConfig {
    /// Constructs default server configuration.
    pub(crate) fn new() -> TestServerConfig {
        TestServerConfig {
            tp: HttpVer::Both,
            stream: StreamType::Tcp,
            client_request_timeout: Duration::from_secs(5),
            port: 0,
            workers: 1,
        }
    }

    /// Accepts HTTP/1.1 only.
    pub fn h1(mut self) -> Self {
        self.tp = HttpVer::Http1;
        self
    }

    /// Accepts HTTP/2 only.
    pub fn h2(mut self) -> Self {
        self.tp = HttpVer::Http2;
        self
    }

    /// Accepts secure connections via OpenSSL.
    #[cfg(feature = "openssl")]
    pub fn openssl(mut self, acceptor: openssl::ssl::SslAcceptor) -> Self {
        self.stream = StreamType::Openssl(acceptor);
        self
    }

    #[doc(hidden)]
    #[deprecated(note = "Renamed to `rustls_0_20()`.")]
    #[cfg(feature = "rustls-0_20")]
    pub fn rustls(mut self, config: tls_rustls_0_20::ServerConfig) -> Self {
        self.stream = StreamType::Rustls020(config);
        self
    }

    /// Accepts secure connections via Rustls v0.20.
    #[cfg(feature = "rustls-0_20")]
    pub fn rustls_0_20(mut self, config: tls_rustls_0_20::ServerConfig) -> Self {
        self.stream = StreamType::Rustls020(config);
        self
    }

    #[doc(hidden)]
    #[deprecated(note = "Renamed to `rustls_0_21()`.")]
    #[cfg(feature = "rustls-0_21")]
    pub fn rustls_021(mut self, config: tls_rustls_0_21::ServerConfig) -> Self {
        self.stream = StreamType::Rustls021(config);
        self
    }

    /// Accepts secure connections via Rustls v0.21.
    #[cfg(feature = "rustls-0_21")]
    pub fn rustls_0_21(mut self, config: tls_rustls_0_21::ServerConfig) -> Self {
        self.stream = StreamType::Rustls021(config);
        self
    }

    /// Accepts secure connections via Rustls v0.22.
    #[cfg(feature = "rustls-0_22")]
    pub fn rustls_0_22(mut self, config: tls_rustls_0_22::ServerConfig) -> Self {
        self.stream = StreamType::Rustls022(config);
        self
    }

    /// Accepts secure connections via Rustls v0.23.
    #[cfg(feature = "rustls-0_23")]
    pub fn rustls_0_23(mut self, config: tls_rustls_0_23::ServerConfig) -> Self {
        self.stream = StreamType::Rustls023(config);
        self
    }

    /// Sets client timeout for first request.
    pub fn client_request_timeout(mut self, dur: Duration) -> Self {
        self.client_request_timeout = dur;
        self
    }

    /// Sets test server port.
    ///
    /// By default, a random free port is determined by the OS.
    pub fn port(mut self, port: u16) -> Self {
        self.port = port;
        self
    }

    /// Sets number of workers for the test server.
    ///
    /// By default, the server uses 1 worker
    pub fn workers(mut self, workers: usize) -> Self {
        self.workers = workers;
        self
    }
}

/// A basic HTTP server controller that simplifies the process of writing integration tests for
/// Actix Web applications.
///
/// See [`start`] for usage example.
pub struct TestServer {
    server: ServerHandle,
    thread_stop_rx: mpsc::Receiver<()>,
    client: awc::Client,
    system: rt::System,
    addr: net::SocketAddr,
    tls: bool,
}

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

    /// Construct test server url
    pub fn url(&self, uri: &str) -> String {
        let scheme = if self.tls { "https" } else { "http" };

        if uri.starts_with('/') {
            format!("{}://localhost:{}{}", scheme, self.addr.port(), uri)
        } else {
            format!("{}://localhost:{}/{}", scheme, self.addr.port(), uri)
        }
    }

    /// Create `GET` request.
    pub fn get(&self, path: impl AsRef<str>) -> ClientRequest {
        self.client.get(self.url(path.as_ref()).as_str())
    }

    /// Create `POST` request.
    pub fn post(&self, path: impl AsRef<str>) -> ClientRequest {
        self.client.post(self.url(path.as_ref()).as_str())
    }

    /// Create `HEAD` request.
    pub fn head(&self, path: impl AsRef<str>) -> ClientRequest {
        self.client.head(self.url(path.as_ref()).as_str())
    }

    /// Create `PUT` request.
    pub fn put(&self, path: impl AsRef<str>) -> ClientRequest {
        self.client.put(self.url(path.as_ref()).as_str())
    }

    /// Create `PATCH` request.
    pub fn patch(&self, path: impl AsRef<str>) -> ClientRequest {
        self.client.patch(self.url(path.as_ref()).as_str())
    }

    /// Create `DELETE` request.
    pub fn delete(&self, path: impl AsRef<str>) -> ClientRequest {
        self.client.delete(self.url(path.as_ref()).as_str())
    }

    /// Create `OPTIONS` request.
    pub fn options(&self, path: impl AsRef<str>) -> ClientRequest {
        self.client.options(self.url(path.as_ref()).as_str())
    }

    /// Connect request with given method and path.
    pub fn request(&self, method: Method, path: impl AsRef<str>) -> ClientRequest {
        self.client.request(method, path.as_ref())
    }

    pub async fn load_body<S>(
        &mut self,
        mut response: ClientResponse<S>,
    ) -> Result<web::Bytes, PayloadError>
    where
        S: Stream<Item = Result<web::Bytes, PayloadError>> + Unpin + 'static,
    {
        response.body().limit(10_485_760).await
    }

    /// Connect to WebSocket server at a given path.
    pub async fn ws_at(
        &mut self,
        path: &str,
    ) -> Result<Framed<impl AsyncRead + AsyncWrite, ws::Codec>, awc::error::WsClientError> {
        let url = self.url(path);
        let connect = self.client.ws(url).connect();
        connect.await.map(|(_, framed)| framed)
    }

    /// Connect to a WebSocket server.
    pub async fn ws(
        &mut self,
    ) -> Result<Framed<impl AsyncRead + AsyncWrite, ws::Codec>, awc::error::WsClientError> {
        self.ws_at("/").await
    }

    /// Get default HeaderMap of Client.
    ///
    /// Returns Some(&mut HeaderMap) when Client object is unique
    /// (No other clone of client exists at the same time).
    pub fn client_headers(&mut self) -> Option<&mut HeaderMap> {
        self.client.headers()
    }

    /// Stop HTTP server.
    ///
    /// Waits for spawned `Server` and `System` to shutdown (force) shutdown.
    pub async fn stop(mut self) {
        // signal server to stop
        self.server.stop(false).await;

        // also signal system to stop
        // though this is handled by `ServerBuilder::exit_system` too
        self.system.stop();

        // wait for thread to be stopped but don't care about result
        let _ = self.thread_stop_rx.recv().await;
    }
}

impl Drop for TestServer {
    fn drop(&mut self) {
        // calls in this Drop impl should be enough to shut down the server, system, and thread
        // without needing to await anything

        // signal server to stop
        #[allow(clippy::let_underscore_future)]
        let _ = self.server.stop(true);

        // signal system to stop
        self.system.stop();
    }
}