ntex 3.7.2

Framework for composable network services
Documentation
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
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
//! Various helpers for ntex applications to use during testing.
use std::{fmt, net, net::SocketAddr, rc::Rc, sync::mpsc, thread, time};

#[cfg(feature = "cookie")]
use coo_kie::Cookie;
use serde::{Serialize, de::DeserializeOwned};
use uuid::Uuid;

use crate::client::{Client, ClientRequest, ClientResponse, Connector};
use crate::http::body::MessageBody;
use crate::http::error::{HttpError, PayloadError, ResponseError};
use crate::http::header::{CONTENT_TYPE, HeaderName, HeaderValue};
use crate::http::test::TestRequest as HttpTestRequest;
use crate::http::{
    HttpService, HttpServiceConfig, Method, Payload, Request, StatusCode, Uri, Version,
};
#[cfg(feature = "ws")]
use crate::io::Sealed;
use crate::router::{Path, ResourceDef};
use crate::service::{IntoService, IntoServiceFactory, Pipeline};
use crate::time::{Millis, Seconds, sleep};
use crate::util::{Bytes, BytesMut, Extensions, Ready, Stream, stream_recv};
#[cfg(feature = "ws")]
use crate::ws::{WsClient, WsConnection, error::WsClientError};
use crate::{Service, ServiceFactory, SharedCfg, io::IoConfig, rt::System, server::Server};

use crate::web::error::{DefaultError, ErrorRenderer};
use crate::web::httprequest::HttpRequest;
use crate::web::rmap::ResourceMap;
use crate::web::{FromRequest, HttpResponse, Responder, WebRequest, WebResponse};
use crate::web::{config::WebAppConfig, service::AppState};

/// Create service that always responds with `HttpResponse::Ok()`
pub fn ok_service<Err: ErrorRenderer>()
-> impl Service<WebRequest<Err>, Response = WebResponse, Error = std::convert::Infallible> {
    default_service::<Err>(StatusCode::OK)
}

/// Create service that responds with response with specified status code
pub fn default_service<Err: ErrorRenderer>(
    status_code: StatusCode,
) -> impl Service<WebRequest<Err>, Response = WebResponse, Error = std::convert::Infallible>
{
    (move |req: WebRequest<Err>| {
        Ready::Ok(req.into_response(HttpResponse::build(status_code).finish()))
    })
    .into_service()
}

/// This method accepts application builder instance, and constructs
/// service.
///
/// ```rust
/// use ntex::service::Service;
/// use ntex::http::StatusCode;
/// use ntex::web::{self, test, App, HttpResponse};
///
/// #[ntex::test]
/// async fn test_init_service() {
///     let mut app = test::init_service(
///         App::new()
///             .service(web::resource("/test").to(|| async { HttpResponse::Ok() }))
///     ).await;
///
///     // Create request object
///     let req = test::TestRequest::with_uri("/test").to_request();
///
///     // Execute application
///     let resp = app.call(req).await.unwrap();
///     assert_eq!(resp.status(), StatusCode::OK);
/// }
/// ```
pub async fn init_service<R, S, E>(
    app: R,
) -> Pipeline<impl Service<Request, Response = WebResponse, Error = E>>
where
    R: IntoServiceFactory<S, Request, SharedCfg>,
    S: ServiceFactory<Request, SharedCfg, Response = WebResponse, Error = E>,
    S::InitError: fmt::Debug,
{
    let srv = app.into_factory();
    srv.pipeline(
        SharedCfg::new("WEB")
            .add(IoConfig::new())
            .add(WebAppConfig::new())
            .into(),
    )
    .await
    .unwrap()
}

/// Calls service and waits for response future completion.
///
/// ```rust
/// use ntex::http::StatusCode;
/// use ntex::web::{self, test, App, HttpResponse};
///
/// #[ntex::test]
/// async fn test_response() {
///     let mut app = test::init_service(
///         App::new()
///             .service(web::resource("/test").to(|| async {
///                 HttpResponse::Ok()
///             }))
///     ).await;
///
///     // Create request object
///     let req = test::TestRequest::with_uri("/test").to_request();
///
///     // Call application
///     let resp = test::call_service(&mut app, req).await;
///     assert_eq!(resp.status(), StatusCode::OK);
/// }
/// ```
pub async fn call_service<S, R, E>(app: &Pipeline<S>, req: R) -> S::Response
where
    S: Service<R, Response = WebResponse, Error = E>,
    E: std::fmt::Debug,
{
    app.call(req).await.unwrap()
}

/// Helper function that returns a response body of a `TestRequest`
///
/// ```rust
/// use ntex::{http::header, util::Bytes};
/// use ntex::web::{self, test, App, HttpResponse};
///
/// #[ntex::test]
/// async fn test_index() {
///     let mut app = test::init_service(
///         App::new().service(
///             web::resource("/index.html")
///                 .route(web::post().to(|| async {
///                     HttpResponse::Ok().body("welcome!")
///                 })))
///     ).await;
///
///     let req = test::TestRequest::post()
///         .uri("/index.html")
///         .header(header::CONTENT_TYPE, "application/json")
///         .to_request();
///
///     let result = test::read_response(&mut app, req).await;
///     assert_eq!(result, Bytes::from_static(b"welcome!"));
/// }
/// ```
pub async fn read_response<S>(app: &Pipeline<S>, req: Request) -> Bytes
where
    S: Service<Request, Response = WebResponse>,
{
    let mut resp = app
        .call(req)
        .await
        .unwrap_or_else(|_| panic!("read_response failed at application call"));

    let mut body = resp.take_body();
    let mut bytes = BytesMut::new();
    while let Some(item) = stream_recv(&mut body).await {
        bytes.extend_from_slice(&item.unwrap());
    }
    bytes.freeze()
}

/// Helper function that returns a response body of a `WebResponse`
///
/// ```rust
/// use ntex::{util::Bytes, http::header};
/// use ntex::web::{self, test, App, HttpResponse};
///
/// #[ntex::test]
/// async fn test_index() {
///     let mut app = test::init_service(
///         App::new().service(
///             web::resource("/index.html")
///                 .route(web::post().to(|| async {
///                     HttpResponse::Ok().body("welcome!")
///                 })))
///     ).await;
///
///     let req = test::TestRequest::post()
///         .uri("/index.html")
///         .header(header::CONTENT_TYPE, "application/json")
///         .to_request();
///
///     let resp = test::call_service(&mut app, req).await;
///     let result = test::read_body(resp);
///     assert_eq!(result, Bytes::from_static(b"welcome!"));
/// }
/// ```
pub async fn read_body(mut res: WebResponse) -> Bytes {
    let mut body = res.take_body();
    let mut bytes = BytesMut::new();
    while let Some(item) = stream_recv(&mut body).await {
        bytes.extend_from_slice(&item.unwrap());
    }
    bytes.freeze()
}

/// Reads response's body and combines it to a Bytes objects
pub async fn load_stream<S, E>(mut stream: S) -> Result<Bytes, E>
where
    S: Stream<Item = Result<Bytes, E>> + Unpin,
{
    let mut data = BytesMut::new();
    while let Some(item) = stream_recv(&mut stream).await {
        data.extend_from_slice(&item?);
    }
    Ok(data.freeze())
}

/// Helper function that returns a deserialized response body of a `TestRequest`
///
/// ```rust
/// use ntex::http::header;
/// use ntex::web::{self, test, App, HttpResponse};
/// use serde::{Serialize, Deserialize};
///
/// #[derive(Serialize, Deserialize)]
/// pub struct Person {
///     id: String,
///     name: String
/// }
///
/// #[ntex::test]
/// async fn test_add_person() {
///     let mut app = test::init_service(
///         App::new().service(
///             web::resource("/people")
///                 .route(web::post().to(|person: web::Json<Person>| async {
///                     HttpResponse::Ok()
///                         .json(person.into_inner())})
///                     ))
///     ).await;
///
///     let payload = r#"{"id":"12345","name":"User name"}"#.as_bytes();
///
///     let req = test::TestRequest::post()
///         .uri("/people")
///         .header(header::CONTENT_TYPE, "application/json")
///         .set_payload(payload)
///         .to_request();
///
///     let result: Person = test::read_response_json(&mut app, req).await;
/// }
/// ```
pub async fn read_response_json<S, T>(app: &Pipeline<S>, req: Request) -> T
where
    S: Service<Request, Response = WebResponse>,
    T: DeserializeOwned,
{
    let body = read_response::<S>(app, req).await;

    serde_json::from_slice(&body).unwrap_or_else(|e| {
        panic!("read_response_json failed during deserialization, {e:?}")
    })
}

/// Helper method for extractors testing
pub async fn from_request<T: FromRequest<DefaultError>>(
    req: &HttpRequest,
    payload: &mut Payload,
) -> Result<T, T::Error> {
    T::from_request(req, payload).await
}

/// Helper method for responders testing
pub async fn respond_to<T: Responder<DefaultError>>(
    slf: T,
    req: &HttpRequest,
) -> HttpResponse {
    T::respond_to(slf, req).await
}

/// Test `Request` builder.
///
/// For unit testing, ntex provides a request builder type and a simple handler runner. `TestRequest` implements a builder-like pattern.
/// You can generate various types of request via `TestRequest`'s methods:
///  * `TestRequest::to_request` creates `ntex::http::Request` instance.
///  * `TestRequest::to_srv_request` creates `WebRequest` instance, which is used for testing middlewares and chain adapters.
///  * `TestRequest::to_srv_response` creates `WebResponse` instance.
///  * `TestRequest::to_http_request` creates `HttpRequest` instance, which is used for testing handlers.
///
/// ```rust
/// use ntex::http::{header, StatusCode, HttpMessage};
/// use ntex::web::{self, test, HttpRequest, HttpResponse};
///
/// async fn index(req: HttpRequest) -> HttpResponse {
///     if let Some(hdr) = req.headers().get(header::CONTENT_TYPE) {
///         HttpResponse::Ok().into()
///     } else {
///         HttpResponse::BadRequest().into()
///     }
/// }
///
/// #[ntex::test]
/// async fn test_index() {
///     let req = test::TestRequest::with_header("content-type", "text/plain")
///         .to_http_request();
///
///     let resp = index(req).await.unwrap();
///     assert_eq!(resp.status(), StatusCode::OK);
///
///     let req = test::TestRequest::default().to_http_request();
///     let resp = index(req).await.unwrap();
///     assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
/// }
/// ```
#[derive(Debug)]
pub struct TestRequest {
    req: HttpTestRequest,
    rmap: ResourceMap,
    config: SharedCfg,
    path: Path<Uri>,
    peer_addr: Option<SocketAddr>,
    app_state: Extensions,
}

impl Default for TestRequest {
    fn default() -> TestRequest {
        TestRequest {
            req: HttpTestRequest::default(),
            rmap: ResourceMap::new(ResourceDef::new("")),
            config: SharedCfg::default(),
            path: Path::new(Uri::default()),
            peer_addr: None,
            app_state: Extensions::new(),
        }
    }
}

#[allow(clippy::wrong_self_convention)]
impl TestRequest {
    #[must_use]
    /// Create `TestRequest` and set request uri.
    pub fn with_uri(path: &str) -> TestRequest {
        TestRequest::default().uri(path)
    }

    #[must_use]
    /// Create `TestRequest` and set header.
    pub fn with_header<K, V>(key: K, value: V) -> TestRequest
    where
        HeaderName: TryFrom<K>,
        HeaderValue: TryFrom<V>,
        <HeaderName as TryFrom<K>>::Error: Into<HttpError>,
    {
        TestRequest::default().header(key, value)
    }

    #[must_use]
    /// Create `TestRequest` and set method to `Method::GET`.
    pub fn get() -> TestRequest {
        TestRequest::default().method(Method::GET)
    }

    #[must_use]
    /// Create `TestRequest` and set method to `Method::POST`.
    pub fn post() -> TestRequest {
        TestRequest::default().method(Method::POST)
    }

    #[must_use]
    /// Create `TestRequest` and set method to `Method::PUT`.
    pub fn put() -> TestRequest {
        TestRequest::default().method(Method::PUT)
    }

    #[must_use]
    /// Create `TestRequest` and set method to `Method::PATCH`.
    pub fn patch() -> TestRequest {
        TestRequest::default().method(Method::PATCH)
    }

    #[must_use]
    /// Create `TestRequest` and set method to `Method::DELETE`.
    pub fn delete() -> TestRequest {
        TestRequest::default().method(Method::DELETE)
    }

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

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

    #[must_use]
    /// Set HTTP Uri of this request.
    pub fn uri(mut self, path: &str) -> Self {
        self.req.uri(path);
        self
    }

    #[must_use]
    /// Set a header.
    pub fn header<K, V>(mut self, key: K, value: V) -> Self
    where
        HeaderName: TryFrom<K>,
        HeaderValue: TryFrom<V>,
        <HeaderName as TryFrom<K>>::Error: Into<HttpError>,
    {
        self.req.header(key, value);
        self
    }

    #[must_use]
    #[cfg(feature = "cookie")]
    /// Set cookie for this request.
    pub fn cookie<C>(mut self, cookie: C) -> Self
    where
        C: Into<Cookie<'static>>,
    {
        self.req.cookie(cookie);
        self
    }

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

    #[must_use]
    /// Set peer addr.
    pub fn peer_addr(mut self, addr: SocketAddr) -> Self {
        self.peer_addr = Some(addr);
        self
    }

    #[must_use]
    /// Set request payload.
    pub fn set_payload<B: Into<Bytes>>(mut self, data: B) -> Self {
        self.req.set_payload(data);
        self
    }

    #[must_use]
    /// Serialize `data` to a URL encoded form and set it as the request payload.
    ///
    /// The `Content-Type` header is set to `application/x-www-form-urlencoded`.
    pub fn set_form<T: Serialize>(mut self, data: &T) -> Self {
        let bytes = serde_urlencoded::to_string(data)
            .expect("Failed to serialize test data as a urlencoded form");
        self.req.set_payload(bytes);
        self.req
            .header(CONTENT_TYPE, "application/x-www-form-urlencoded");
        self
    }

    #[must_use]
    /// Serialize `data` to JSON and set it as the request payload.
    ///
    /// The `Content-Type` header is set to `application/json`.
    pub fn set_json<T: Serialize>(mut self, data: &T) -> Self {
        let bytes =
            serde_json::to_string(data).expect("Failed to serialize test data to json");
        self.req.set_payload(bytes);
        self.req.header(CONTENT_TYPE, "application/json");
        self
    }

    #[must_use]
    /// Set application data.
    ///
    /// This is equivalent of `App::data()` method for testing purpose.
    pub fn state<T: 'static>(mut self, data: T) -> Self {
        self.app_state.insert(data);
        self
    }

    #[must_use]
    #[cfg(test)]
    /// Set request config
    pub(crate) fn rmap(mut self, rmap: ResourceMap) -> Self {
        self.rmap = rmap;
        self
    }

    #[must_use]
    /// Complete request creation and generate `Request` instance.
    pub fn to_request(mut self) -> Request {
        self.req.finish()
    }

    #[must_use]
    /// Complete request creation and generate `WebRequest` instance.
    pub fn to_srv_request(mut self) -> WebRequest<DefaultError> {
        let (head, payload) = self.req.finish().into_parts();
        *self.path.get_mut() = head.uri.clone();
        let app_state = AppState::new(self.app_state, None, self.config.get());

        WebRequest::new(HttpRequest::new(
            self.path,
            head,
            payload,
            Rc::new(self.rmap),
            app_state,
        ))
    }

    #[must_use]
    /// Complete request creation and generate `WebResponse` instance.
    pub fn to_srv_response(self, res: HttpResponse) -> WebResponse {
        self.to_srv_request().into_response(res)
    }

    #[must_use]
    /// Complete request creation and generate `HttpRequest` instance.
    pub fn to_http_request(mut self) -> HttpRequest {
        let (head, payload) = self.req.finish().into_parts();
        *self.path.get_mut() = head.uri.clone();
        let app_state = AppState::new(self.app_state, None, self.config.get());

        HttpRequest::new(self.path, head, payload, Rc::new(self.rmap), app_state)
    }

    #[must_use]
    /// Complete request creation and generate `HttpRequest` and `Payload` instances.
    pub fn to_http_parts(mut self) -> (HttpRequest, Payload) {
        let (head, payload) = self.req.finish().into_parts();
        *self.path.get_mut() = head.uri.clone();
        let app_state = AppState::new(self.app_state, None, self.config.get());

        let req = HttpRequest::new(
            self.path,
            head,
            Payload::None,
            Rc::new(self.rmap),
            app_state,
        );

        (req, payload)
    }
}

/// Start test server with default configuration
///
/// Test server is very simple server that simplify process of writing
/// integration tests cases for ntex web applications.
///
/// # Examples
///
/// ```rust
/// use ntex::web::{self, test, App, HttpResponse};
///
/// async fn my_handler() -> Result<HttpResponse, std::io::Error> {
///     Ok(HttpResponse::Ok().into())
/// }
///
/// #[ntex::test]
/// async fn test_example() {
///     let mut srv = test::server(
///         || App::new().service(
///                 web::resource("/").to(my_handler))
///     );
///
///     let req = srv.get("/");
///     let response = req.send().await.unwrap();
///     assert!(response.status().is_success());
/// }
/// ```
pub async fn server<F, I, S, B>(factory: F) -> TestServer
where
    F: AsyncFn() -> I + Send + Clone + 'static,
    I: IntoServiceFactory<S, Request, SharedCfg>,
    S: ServiceFactory<Request, SharedCfg> + 'static,
    S::Error: ResponseError,
    S::InitError: fmt::Debug,
    S::Response: Into<HttpResponse<B>>,
    B: MessageBody + 'static,
{
    server_with(TestServerConfig::default(), factory).await
}

/// Start test server with custom configuration
///
/// Test server could be configured in different ways, for details check
/// `TestServerConfig` docs.
///
/// # Examples
///
/// ```rust
/// use ntex::web::{self, test, App, HttpResponse};
///
/// async fn my_handler() -> HttpResponse {
///     HttpResponse::Ok().into()
/// }
///
/// #[ntex::test]
/// async fn test_example() {
///     let mut srv = test::server_with(test::config().h1().port(4000), ||
///         App::new().service(web::resource("/").to(my_handler))
///     );
///
///     let req = srv.get("/");
///     let response = req.send().await.unwrap();
///     assert!(response.status().is_success());
/// }
/// ```
pub async fn server_with<F, I, S, B>(cfg: TestServerConfig, factory: F) -> TestServer
where
    F: AsyncFn() -> I + Send + Clone + 'static,
    I: IntoServiceFactory<S, Request, SharedCfg>,
    S: ServiceFactory<Request, SharedCfg> + 'static,
    S::Error: ResponseError,
    S::InitError: fmt::Debug,
    S::Response: Into<HttpResponse<B>>,
    B: MessageBody + 'static,
{
    let sys = System::current().config();
    let name = System::current().name().to_string();

    let id = Uuid::now_v7();
    let (tx, rx) = mpsc::channel();
    log::debug!("Starting {name:?} web server {id:?}");

    let ssl = match cfg.stream {
        StreamType::Tcp => false,
        #[cfg(feature = "openssl")]
        StreamType::Openssl(_) => true,
        #[cfg(feature = "rustls")]
        StreamType::Rustls(_) => true,
    };

    // run server in separate thread
    thread::spawn(move || {
        let sys = System::with_config(&name, sys);

        let factory = factory.clone();
        let ctimeout = cfg.client_timeout;
        let port = cfg.port;
        let tcp = cfg
            .listener
            .unwrap_or(net::TcpListener::bind(format!("127.0.0.1:{port}")).unwrap());
        let local_addr = tcp.local_addr().unwrap();

        sys.run(move || {
            let builder = crate::server::build().workers(1).disable_signals();
            let secure = match cfg.stream {
                StreamType::Tcp => false,
                #[cfg(feature = "openssl")]
                StreamType::Openssl(_) => true,
                #[cfg(feature = "rustls")]
                StreamType::Rustls(_) => true,
            };

            let srv = match cfg.stream {
                StreamType::Tcp => match cfg.tp {
                    HttpVer::Http1 => builder.listen("test", tcp, async move |_| {
                        HttpService::h1(factory().await)
                    }),
                    HttpVer::Http2 => builder.listen("test", tcp, async move |_| {
                        HttpService::h2(factory().await)
                    }),
                    HttpVer::Both => builder.listen("test", tcp, async move |_| {
                        HttpService::new(factory().await)
                    }),
                },
                #[cfg(feature = "openssl")]
                StreamType::Openssl(acceptor) => match cfg.tp {
                    HttpVer::Http1 => builder.listen("test", tcp, async move |_| {
                        HttpService::h1(factory().await).openssl(acceptor.clone())
                    }),
                    HttpVer::Http2 => builder.listen("test", tcp, async move |_| {
                        HttpService::h2(factory().await).openssl(acceptor.clone())
                    }),
                    HttpVer::Both => builder.listen("test", tcp, async move |_| {
                        HttpService::new(factory().await).openssl(acceptor.clone())
                    }),
                },
                #[cfg(feature = "rustls")]
                StreamType::Rustls(config) => match cfg.tp {
                    HttpVer::Http1 => builder.listen("test", tcp, async move |_| {
                        HttpService::h1(factory().await).rustls(config.clone())
                    }),
                    HttpVer::Http2 => builder.listen("test", tcp, async move |_| {
                        HttpService::h2(factory().await).rustls(config.clone())
                    }),
                    HttpVer::Both => builder.listen("test", tcp, async move |_| {
                        HttpService::new(factory().await).rustls(config.clone())
                    }),
                },
            }
            .unwrap()
            .config(
                "test",
                SharedCfg::new("WEB-SRV")
                    .add(IoConfig::new())
                    .add(HttpServiceConfig::new().set_headers_read_rate(
                        ctimeout,
                        Seconds::ZERO,
                        256,
                    ))
                    .add(WebAppConfig::with(
                        &name,
                        secure,
                        local_addr,
                        format!("{local_addr}"),
                    )),
            )
            .run();

            tx.send((System::current(), srv, local_addr)).unwrap();
            Ok(())
        })
    });
    let (system, server, addr) = rx.recv().unwrap();
    sleep(Millis(25)).await;

    let cfg: SharedCfg = SharedCfg::new("TEST-CLIENT")
        .add(IoConfig::new().set_connect_timeout(Millis(90_000)))
        .add(ntex_tls::TlsConfig::new().set_handshake_timeout(Seconds(5)))
        .add(
            ntex_h2::ServiceConfig::new()
                .set_max_header_list_size(256 * 1024)
                .set_max_header_continuation_frames(96),
        )
        .into();

    let client = {
        let connector = {
            #[cfg(feature = "openssl")]
            {
                use tls_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(|e| log::error!("Cannot set alpn protocol: {e:?}"));
                Connector::default()
                    .lifetime(Seconds::ZERO)
                    .openssl(builder.build())
            }
            #[cfg(not(feature = "openssl"))]
            {
                Connector::default().lifetime(Seconds::ZERO)
            }
        };

        Client::builder()
            .connector::<&str>(connector)
            .build(cfg.clone())
            .await
            .unwrap()
    };

    TestServer {
        id,
        cfg,
        addr,
        client,
        system,
        ssl,
        server,
    }
}

#[derive(Debug)]
/// Test server configuration
pub struct TestServerConfig {
    tp: HttpVer,
    stream: StreamType,
    client_timeout: Seconds,
    port: u16,
    listener: Option<net::TcpListener>,
}

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

#[derive(Clone)]
#[allow(clippy::large_enum_variant)]
enum StreamType {
    Tcp,
    #[cfg(feature = "openssl")]
    Openssl(tls_openssl::ssl::SslAcceptor),
    #[cfg(feature = "rustls")]
    Rustls(tls_rustls::ServerConfig),
}

impl fmt::Debug for StreamType {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            StreamType::Tcp => write!(f, "StreamType::Tcp"),
            #[cfg(feature = "openssl")]
            StreamType::Openssl(_) => write!(f, "StreamType::Openssl"),
            #[cfg(feature = "rustls")]
            StreamType::Rustls(_) => write!(f, "StreamType::Rustls"),
        }
    }
}

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

#[must_use]
/// Create default test server config
pub fn config() -> TestServerConfig {
    TestServerConfig::new()
}

impl TestServerConfig {
    #[must_use]
    /// Create default server configuration
    pub(crate) fn new() -> TestServerConfig {
        TestServerConfig {
            tp: HttpVer::Both,
            stream: StreamType::Tcp,
            client_timeout: Seconds(5),
            port: 0,
            listener: None,
        }
    }

    #[must_use]
    /// Start http/1.1 server only.
    pub fn h1(mut self) -> Self {
        self.tp = HttpVer::Http1;
        self
    }

    #[must_use]
    /// Start http/2 server only.
    pub fn h2(mut self) -> Self {
        self.tp = HttpVer::Http2;
        self
    }

    #[must_use]
    /// Start openssl server.
    #[cfg(feature = "openssl")]
    pub fn openssl(mut self, acceptor: tls_openssl::ssl::SslAcceptor) -> Self {
        self.stream = StreamType::Openssl(acceptor);
        self
    }

    #[must_use]
    /// Start rustls server.
    #[cfg(feature = "rustls")]
    pub fn rustls(mut self, config: tls_rustls::ServerConfig) -> Self {
        self.stream = StreamType::Rustls(config);
        self
    }

    #[must_use]
    /// Set server client timeout in seconds for first request.
    pub fn client_timeout(mut self, val: Seconds) -> Self {
        self.client_timeout = val;
        self
    }

    #[must_use]
    /// Set server port. By default, test server binds to a random port assigned by OS.
    pub fn port(mut self, port: u16) -> Self {
        self.port = port;
        self
    }

    #[must_use]
    pub fn listener(mut self, listener: net::TcpListener) -> Self {
        self.listener = Some(listener);
        self
    }
}

#[derive(Debug)]
/// Test server controller
pub struct TestServer {
    id: Uuid,
    cfg: SharedCfg,
    addr: net::SocketAddr,
    client: Client,
    system: crate::rt::System,
    ssl: bool,
    server: Server,
}

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.ssl { "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<S: AsRef<str>>(&self, path: S) -> ClientRequest {
        self.client.get(self.url(path.as_ref()).as_str())
    }

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

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

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

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

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

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

    /// Connect to test http server
    pub fn request<S: AsRef<str>>(&self, method: Method, path: S) -> ClientRequest {
        self.client.request(method, path.as_ref())
    }

    /// Load response's body
    pub async fn load_body(&self, response: ClientResponse) -> Result<Bytes, PayloadError> {
        response.body().limit(10_485_760).await
    }

    #[cfg(feature = "ws")]
    /// Connect to websocket server at a given path
    pub async fn ws_at(&self, path: &str) -> Result<WsConnection<Sealed>, WsClientError> {
        if self.ssl {
            #[cfg(feature = "openssl")]
            {
                use tls_openssl::ssl::{SslConnector, SslMethod, SslVerifyMode};

                let mut builder = SslConnector::builder(SslMethod::tls()).unwrap();
                builder.set_verify(SslVerifyMode::NONE);
                let _ = builder
                    .set_alpn_protos(b"\x08http/1.1")
                    .map_err(|e| log::error!("Cannot set alpn protocol: {e:?}"));

                WsClient::builder(self.url(path))
                    .address(self.addr)
                    .timeout(Seconds(60))
                    .openssl(builder.build())
                    .take()
                    .build(self.cfg.clone())
                    .await
                    .unwrap()
                    .connect()
                    .await
                    .map(WsConnection::seal)
            }
            #[cfg(not(feature = "openssl"))]
            {
                panic!("openssl feature is required")
            }
        } else {
            WsClient::builder(self.url(path))
                .address(self.addr)
                .timeout(Seconds(60))
                .build(self.cfg.clone())
                .await
                .unwrap()
                .connect()
                .await
                .map(WsConnection::seal)
        }
    }

    #[cfg(feature = "ws")]
    /// Connect to a websocket server
    pub async fn ws(&self) -> Result<WsConnection<Sealed>, WsClientError> {
        self.ws_at("/").await
    }

    /// Gracefully stop http server
    pub async fn stop(&self) {
        self.server.stop(true).await;
    }
}

impl Drop for TestServer {
    fn drop(&mut self) {
        log::debug!("Stopping test web server {:?}", self.id);
        drop(self.server.stop(false));
        thread::sleep(time::Duration::from_millis(75));
        self.system.stop();
        thread::sleep(time::Duration::from_millis(25));
    }
}

#[cfg(test)]
mod tests {
    use serde::{Deserialize, Serialize};
    use std::convert::Infallible;

    use super::*;
    use crate::http::{HttpMessage, header};
    use crate::web::{self, App};

    #[crate::rt_test]
    async fn test_basics() {
        let req = TestRequest::with_header(header::CONTENT_TYPE, "application/json")
            .version(Version::HTTP_2)
            .header(header::DATE, "some date")
            .param("test", "123")
            .state(20u64)
            .peer_addr("127.0.0.1:8081".parse().unwrap())
            .to_http_request();
        assert!(req.headers().contains_key(header::CONTENT_TYPE));
        assert!(req.headers().contains_key(header::DATE));
        assert_eq!(req.peer_addr(), None);
        assert_eq!(&req.match_info()["test"], "123");
        assert_eq!(req.version(), Version::HTTP_2);
        let data = req.app_state::<u64>().unwrap();
        assert_eq!(*data, 20);
        assert_eq!(format!("{:?}", StreamType::Tcp), "StreamType::Tcp");

        let mut req = TestRequest::with_header(header::CONTENT_TYPE, "application/json")
            .to_srv_request();
        let pl = req.take_payload();
        let res = load_stream(pl).await.unwrap();
        assert_eq!(res, &b""[..]);
    }

    #[crate::rt_test]
    async fn test_request_methods() {
        let app = init_service(
            App::new().service(
                web::resource("/index.html")
                    .route(web::put().to(|| async { HttpResponse::Ok().body("put!") }))
                    .route(web::patch().to(|| async { HttpResponse::Ok().body("patch!") }))
                    .route(
                        web::delete().to(|| async { HttpResponse::Ok().body("delete!") }),
                    ),
            ),
        )
        .await;

        let put_req = TestRequest::put()
            .uri("/index.html")
            .header(header::CONTENT_TYPE, "application/json")
            .to_request();

        let result = read_response(&app, put_req).await;
        assert_eq!(result, Bytes::from_static(b"put!"));

        let patch_req = TestRequest::patch()
            .uri("/index.html")
            .header(header::CONTENT_TYPE, "application/json")
            .to_request();

        let result = read_response(&app, patch_req).await;
        assert_eq!(result, Bytes::from_static(b"patch!"));

        let delete_req = TestRequest::delete().uri("/index.html").to_request();
        let result = read_response(&app, delete_req).await;
        assert_eq!(result, Bytes::from_static(b"delete!"));
    }

    #[crate::rt_test]
    async fn test_response() {
        let app =
            init_service(App::new().service(
                web::resource("/index.html").route(
                    web::post().to(|| async { HttpResponse::Ok().body("welcome!") }),
                ),
            ))
            .await;

        let req = TestRequest::post()
            .uri("/index.html")
            .header(header::CONTENT_TYPE, "application/json")
            .to_request();

        let result = read_response(&app, req).await;
        assert_eq!(result, Bytes::from_static(b"welcome!"));
    }

    #[derive(Serialize, Deserialize)]
    struct Person {
        id: String,
        name: String,
    }

    #[crate::rt_test]
    async fn test_response_json() {
        let app = init_service(App::new().service(web::resource("/people").route(
            web::post().to(|person: web::types::Json<Person>| async {
                HttpResponse::Ok().json(&person.into_inner())
            }),
        )))
        .await;

        let payload = r#"{"id":"12345","name":"User name"}"#.as_bytes();

        let req = TestRequest::post()
            .uri("/people")
            .header(header::CONTENT_TYPE, "application/json")
            .set_payload(payload)
            .to_request();

        let result: Person = read_response_json(&app, req).await;
        assert_eq!(&result.id, "12345");
    }

    #[crate::rt_test]
    async fn test_request_response_form() {
        let app = init_service(App::new().service(web::resource("/people").route(
            web::post().to(|person: web::types::Form<Person>| async {
                HttpResponse::Ok().json(&person.into_inner())
            }),
        )))
        .await;

        let payload = Person {
            id: "12345".to_string(),
            name: "User name".to_string(),
        };

        let req = TestRequest::post()
            .uri("/people")
            .set_form(&payload)
            .to_request();

        assert_eq!(req.content_type(), "application/x-www-form-urlencoded");

        let result: Person = read_response_json(&app, req).await;
        assert_eq!(&result.id, "12345");
        assert_eq!(&result.name, "User name");
    }

    #[crate::rt_test]
    async fn test_request_response_json() {
        let app = init_service(App::new().service(web::resource("/people").route(
            web::post().to(|person: web::types::Json<Person>| async {
                HttpResponse::Ok().json(&person.into_inner())
            }),
        )))
        .await;

        let payload = Person {
            id: "12345".to_string(),
            name: "User name".to_string(),
        };

        let req = TestRequest::post()
            .uri("/people")
            .set_json(&payload)
            .to_request();

        assert_eq!(req.content_type(), "application/json");

        let result: Person = read_response_json(&app, req).await;
        assert_eq!(&result.id, "12345");
        assert_eq!(&result.name, "User name");
    }

    #[crate::rt_test]
    async fn test_async_with_block() {
        async fn async_with_block() -> Result<HttpResponse, Infallible> {
            let res = web::block(move || Some(4usize).ok_or("wrong")).await;

            #[allow(clippy::match_wild_err_arm)]
            match res {
                Ok(value) => Ok(HttpResponse::Ok()
                    .content_type("text/plain")
                    .body(format!("Async with block value: {value}"))),
                Err(_) => panic!("Unexpected"),
            }
        }

        let app = init_service(
            App::new().service(web::resource("/index.html").to(async_with_block)),
        )
        .await;

        let req = TestRequest::post().uri("/index.html").to_request();
        let res = app.call(req).await.unwrap();
        assert!(res.status().is_success());
    }

    #[crate::rt_test]
    async fn test_server_state() {
        async fn handler(data: web::types::State<usize>) -> crate::http::ResponseBuilder {
            assert_eq!(*data, 10);
            HttpResponse::Ok()
        }

        let app = init_service(App::new().state(10usize).service(
            web::resource("/index.html").to(crate::web::dev::__assert_handler1(handler)),
        ))
        .await;

        let req = TestRequest::post().uri("/index.html").to_request();
        let res = app.call(req).await.unwrap();
        assert!(res.status().is_success());
    }

    #[crate::rt_test]
    async fn test_test_methods() {
        let srv = server(|| async {
            App::new().service(
                web::resource("/").route((
                    web::route()
                        .method(Method::PUT)
                        .to(|| async { HttpResponse::Ok() }),
                    web::route()
                        .method(Method::PATCH)
                        .to(|| async { HttpResponse::Ok() }),
                    web::route()
                        .method(Method::DELETE)
                        .to(|| async { HttpResponse::Ok() }),
                    web::route()
                        .method(Method::OPTIONS)
                        .to(|| async { HttpResponse::Ok() }),
                )),
            )
        })
        .await;

        assert_eq!(srv.put("/").send().await.unwrap().status(), StatusCode::OK);
        assert_eq!(
            srv.patch("/").send().await.unwrap().status(),
            StatusCode::OK
        );
        assert_eq!(
            srv.delete("/").send().await.unwrap().status(),
            StatusCode::OK
        );
        assert_eq!(
            srv.options("/").send().await.unwrap().status(),
            StatusCode::OK
        );

        let res = srv.put("").send().await.unwrap();
        assert_eq!(srv.load_body(res).await.unwrap(), Bytes::new());
    }

    #[cfg(feature = "cookie")]
    #[test]
    fn test_response_cookies() {
        let req = TestRequest::default()
            .cookie(
                coo_kie::Cookie::build(("name", "value"))
                    .domain("www.rust-lang.org")
                    .path("/test")
                    .http_only(true)
                    .max_age(::time::Duration::days(1)),
            )
            .to_http_request();

        let cookies = req.cookies().unwrap();
        assert_eq!(cookies.len(), 1);
        assert_eq!(cookies[0].name(), "name");
    }
}