Skip to main content

ntex/web/
test.rs

1//! Various helpers for ntex applications to use during testing.
2use std::sync::{Arc, Mutex, mpsc};
3use std::{convert::Infallible, fmt, future::Future, io, net, net::SocketAddr};
4use std::{pin::Pin, rc::Rc, thread, time};
5
6#[cfg(feature = "cookie")]
7use coo_kie::Cookie;
8use serde::{Serialize, de::DeserializeOwned};
9use urly::Url;
10use uuid::Uuid;
11
12use crate::client::error::ClientPayloadError;
13use crate::client::{Client, ClientConfig, ClientRequest, ClientResponse};
14use crate::error::Error;
15use crate::http::error::{HttpError, ResponseError};
16use crate::http::header::{CONTENT_TYPE, HeaderName, HeaderValue};
17use crate::http::test::TestRequest as HttpTestRequest;
18use crate::http::{self, HttpService, Method, Payload, Request, Response, StatusCode, Version};
19#[cfg(feature = "ws")]
20use crate::io::Sealed;
21use crate::router::{Path, ResourceDef};
22use crate::service::boxed::{self, BoxServiceFactory};
23use crate::service::{IntoServiceFactory, Pipeline, fn_service};
24use crate::time::{Millis, Seconds};
25use crate::util::{Bytes, BytesMut, Stream, stream_recv};
26#[cfg(feature = "ws")]
27use crate::ws::{WsClient, WsClientConfig, WsConnection, error::WsClientError};
28use crate::{Service, ServiceFactory, SharedCfg, io::IoConfig, rt::System, server::Server};
29
30use crate::web::config::WebAppConfig;
31use crate::web::httprequest::HttpRequest;
32use crate::web::rmap::ResourceMap;
33use crate::web::{FromRequest, HttpResponse, Responder, State, WebRequest, WebResponse};
34
35fn set_peer_addr(head: &mut http::RequestHead, addr: Option<SocketAddr>) {
36    #[derive(Debug)]
37    struct TestIo {
38        io: crate::io::Io,
39        _peer: crate::io::testing::IoTest,
40    }
41
42    impl http::IoAccess for TestIo {
43        fn get(&self) -> Option<&crate::io::IoRef> {
44            Some(self.io.as_ref())
45        }
46
47        fn take(&self) -> Option<(crate::io::IoBoxed, http::h1::Codec)> {
48            None
49        }
50    }
51
52    if let Some(addr) = addr {
53        let (client, server) = crate::io::testing::IoTest::create();
54        let io = crate::io::Io::new(server.set_peer_addr(addr), SharedCfg::default());
55        head.io = http::CurrentIo::new(Rc::new(TestIo { io, _peer: client }));
56    }
57}
58
59/// Create service that always responds with `HttpResponse::Ok()`
60pub fn ok_service<St: State, In>()
61-> impl Service<St, WebRequest<In>, Res = WebResponse, Error = std::convert::Infallible> {
62    default_service::<St, In>(StatusCode::OK)
63}
64
65/// Create service that responds with response with specified status code
66pub fn default_service<St: State, In>(
67    status_code: StatusCode,
68) -> impl Service<St, WebRequest<In>, Res = WebResponse, Error = Infallible> {
69    fn_service(async move |req: WebRequest<In>| {
70        Ok::<_, Infallible>(req.into_response(HttpResponse::builder(status_code).build()))
71    })
72}
73
74/// This method accepts application builder instance, and constructs
75/// service.
76///
77/// Success does not mean every route can be built: registered services are
78/// created on their first request. A failing service factory shows up as a
79/// `500 Internal Server Error` response, so assert response statuses.
80///
81/// ```rust
82/// use ntex::service::Service;
83/// use ntex::http::StatusCode;
84/// use ntex::web::{self, test, App, HttpResponse};
85///
86/// #[ntex::test]
87/// async fn test_init_service() {
88///     let mut app = test::init_service(
89///         App::new()
90///             .service(web::resource("/test").to(async || { HttpResponse::Ok() }))
91///     ).await;
92///
93///     // Create request object
94///     let req = test::TestRequest::with_uri("/test").to_request();
95///
96///     // Execute application
97///     let resp = app.call(req).await.unwrap();
98///     assert_eq!(resp.status(), StatusCode::OK);
99/// }
100/// ```
101pub async fn init_service<R, S, E>(app: R) -> Pipeline<Request, Response, E>
102where
103    R: IntoServiceFactory<S, (), Request>,
104    S: ServiceFactory<(), Request, Res = Response, Error = E> + 'static,
105    S::InitError: fmt::Debug,
106{
107    let srv = app.into_factory().map_init_err(|e| log::error!("{e:?}"));
108    srv.pipeline(()).await.unwrap()
109}
110
111/// This method accepts application builder instance, and constructs
112/// service with specified state.
113///
114/// As with [`init_service`], service factories run on their first request, and
115/// a failing one shows up as a `500 Internal Server Error` response.
116///
117/// ```rust
118/// use ntex::service::Service;
119/// use ntex::http::StatusCode;
120/// use ntex::web::{self, test, App, HttpResponse};
121///
122/// #[ntex::test]
123/// async fn test_init_service() {
124///     let mut app = test::init_service_st(
125///         (),
126///         App::new()
127///             .service(web::resource("/test").to(async || { HttpResponse::Ok() }))
128///     ).await;
129///
130///     // Create request object
131///     let req = test::TestRequest::with_uri("/test").to_request();
132///
133///     // Execute application
134///     let resp = app.call(req).await.unwrap();
135///     assert_eq!(resp.status(), StatusCode::OK);
136/// }
137/// ```
138pub async fn init_service_st<St, R, S, E>(st: St, app: R) -> Pipeline<Request, Response, E>
139where
140    St: 'static,
141    R: IntoServiceFactory<S, St, Request>,
142    S: ServiceFactory<St, Request, Res = Response, Error = E> + 'static,
143    S::InitError: fmt::Debug,
144{
145    let srv = app.into_factory().map_init_err(|e| log::error!("{e:?}"));
146    srv.pipeline(st).await.unwrap()
147}
148
149/// Calls service and waits for response future completion.
150///
151/// ```rust
152/// use ntex::http::StatusCode;
153/// use ntex::web::{self, test, App, HttpResponse};
154///
155/// #[ntex::test]
156/// async fn test_response() {
157///     let mut app = test::init_service(
158///         App::new()
159///             .service(web::resource("/test").to(async || {
160///                 HttpResponse::Ok()
161///             }))
162///     ).await;
163///
164///     // Create request object
165///     let req = test::TestRequest::with_uri("/test").to_request();
166///
167///     // Call application
168///     let resp = test::call_service(&mut app, req).await;
169///     assert_eq!(resp.status(), StatusCode::OK);
170/// }
171/// ```
172pub async fn call_service<R, E>(app: &Pipeline<R, Response, E>, req: R) -> Response
173where
174    R: 'static,
175    E: fmt::Debug + 'static,
176{
177    app.call(req).await.unwrap()
178}
179
180/// Helper function that returns a response body of a `TestRequest`
181///
182/// ```rust
183/// use ntex::{http::header, util::Bytes};
184/// use ntex::web::{self, test, App, HttpResponse};
185///
186/// #[ntex::test]
187/// async fn test_index() {
188///     let mut app = test::init_service(
189///         App::new().service(
190///             web::resource("/index.html")
191///                 .route(web::post().to(async || {
192///                     HttpResponse::Ok().body("welcome!")
193///                 })))
194///     ).await;
195///
196///     let req = test::TestRequest::post()
197///         .uri("/index.html")
198///         .header(header::CONTENT_TYPE, "application/json")
199///         .to_request();
200///
201///     let result = test::read_response(&mut app, req).await;
202///     assert_eq!(result, Bytes::from_static(b"welcome!"));
203/// }
204/// ```
205pub async fn read_response<E>(app: &Pipeline<Request, Response, E>, req: Request) -> Bytes
206where
207    E: 'static,
208{
209    let mut resp = app
210        .call(req)
211        .await
212        .unwrap_or_else(|_| panic!("read_response failed at application call"));
213
214    let mut body = resp.take_body();
215    let mut bytes = BytesMut::new();
216    while let Some(item) = stream_recv(&mut body).await {
217        bytes.extend_from_slice(&item.unwrap());
218    }
219    bytes.freeze()
220}
221
222/// Helper function that returns a response body of a `WebResponse`
223///
224/// ```rust
225/// use ntex::{util::Bytes, http::header};
226/// use ntex::web::{self, test, App, HttpResponse};
227///
228/// #[ntex::test]
229/// async fn test_index() {
230///     let mut app = test::init_service(
231///         App::new().service(
232///             web::resource("/index.html")
233///                 .route(web::post().to(async || {
234///                     HttpResponse::Ok().body("welcome!")
235///                 })))
236///     ).await;
237///
238///     let req = test::TestRequest::post()
239///         .uri("/index.html")
240///         .header(header::CONTENT_TYPE, "application/json")
241///         .to_request();
242///
243///     let resp = test::call_service(&mut app, req).await;
244///     let result = test::read_body(resp).await;
245///     assert_eq!(result, Bytes::from_static(b"welcome!"));
246/// }
247/// ```
248pub async fn read_body(res: impl Into<Response>) -> Bytes {
249    let mut body = res.into().take_body();
250    let mut bytes = BytesMut::new();
251    while let Some(item) = stream_recv(&mut body).await {
252        bytes.extend_from_slice(&item.unwrap());
253    }
254    bytes.freeze()
255}
256
257/// Reads response's body and combines it to a Bytes objects
258pub async fn load_stream<S, E>(mut stream: S) -> Result<Bytes, E>
259where
260    S: Stream<Item = Result<Bytes, E>> + Unpin,
261{
262    let mut data = BytesMut::new();
263    while let Some(item) = stream_recv(&mut stream).await {
264        data.extend_from_slice(&item?);
265    }
266    Ok(data.freeze())
267}
268
269/// Helper function that returns a deserialized response body of a `TestRequest`
270///
271/// ```rust
272/// use ntex::http::header;
273/// use ntex::web::{self, test, App, HttpResponse};
274/// use serde::{Serialize, Deserialize};
275///
276/// #[derive(Serialize, Deserialize)]
277/// pub struct Person {
278///     id: String,
279///     name: String
280/// }
281///
282/// #[ntex::test]
283/// async fn test_add_person() {
284///     let mut app = test::init_service(
285///         App::new().service(
286///             web::resource("/people")
287///                 .route(web::post().to(async |person: web::types::Json<Person>| {
288///                     HttpResponse::Ok()
289///                         .json(&person.into_inner())})
290///                     ))
291///     ).await;
292///
293///     let payload = r#"{"id":"12345","name":"User name"}"#.as_bytes();
294///
295///     let req = test::TestRequest::post()
296///         .uri("/people")
297///         .header(header::CONTENT_TYPE, "application/json")
298///         .payload(payload)
299///         .to_request();
300///
301///     let result: Person = test::read_response_json(&mut app, req).await;
302/// }
303/// ```
304pub async fn read_response_json<T, E>(app: &Pipeline<Request, Response, E>, req: Request) -> T
305where
306    T: DeserializeOwned,
307    E: 'static,
308{
309    let body = read_response(app, req).await;
310
311    crate::http::json::from_slice(&body)
312        .unwrap_or_else(|e| panic!("read_response_json failed during deserialization, {e:?}"))
313}
314
315/// Helper method for extractors testing
316pub async fn from_request<St, T: FromRequest<St>>(
317    st: &St,
318    req: &HttpRequest,
319    payload: &mut Payload,
320) -> Result<T, T::Error> {
321    T::from_request(st, req, payload).await
322}
323
324/// Helper method for responders testing
325pub async fn respond_to<T: Responder>(slf: T, req: &HttpRequest) -> HttpResponse {
326    T::respond_to(slf, &(), req).await
327}
328
329/// Test `Request` builder.
330///
331/// For unit testing, ntex provides a request builder type and a simple handler runner. `TestRequest` implements a builder-like pattern.
332/// You can generate various types of request via `TestRequest`'s methods:
333///  * `TestRequest::to_request` creates `ntex::http::Request` instance.
334///  * `TestRequest::to_srv_request` creates `WebRequest` instance, which is used for testing middlewares and chain adapters.
335///  * `TestRequest::to_srv_response` creates `WebResponse` instance.
336///  * `TestRequest::to_http_request` creates `HttpRequest` instance, which is used for testing handlers.
337///
338/// ```rust
339/// use ntex::http::{header, StatusCode, HttpMessage};
340/// use ntex::web::{self, test, HttpRequest, HttpResponse};
341///
342/// async fn index(req: HttpRequest) -> HttpResponse {
343///     if req.headers().contains_key(header::CONTENT_TYPE) {
344///         HttpResponse::Ok().into()
345///     } else {
346///         HttpResponse::BadRequest().into()
347///     }
348/// }
349///
350/// #[ntex::test]
351/// async fn test_index() {
352///     let req = test::TestRequest::with_header("content-type", "text/plain")
353///         .to_http_request();
354///
355///     let resp = index(req).await;
356///     assert_eq!(resp.status(), StatusCode::OK);
357///
358///     let req = test::TestRequest::default().to_http_request();
359///     let resp = index(req).await;
360///     assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
361/// }
362/// ```
363#[derive(Debug)]
364pub struct TestRequest<St = ()> {
365    req: HttpTestRequest,
366    rmap: ResourceMap,
367    path: Path<Url>,
368    peer_addr: Option<SocketAddr>,
369    state: St,
370    config: WebAppConfig,
371}
372
373impl Default for TestRequest {
374    fn default() -> TestRequest {
375        TestRequest {
376            req: HttpTestRequest::default(),
377            rmap: ResourceMap::new(ResourceDef::new("")),
378            path: Path::new(Url::new()),
379            peer_addr: None,
380            state: (),
381            config: WebAppConfig::new(),
382        }
383    }
384}
385
386impl TestRequest {
387    #[must_use]
388    /// Create `TestRequest` and set request uri.
389    pub fn with_uri(path: &str) -> TestRequest {
390        TestRequest::default().uri(path)
391    }
392
393    #[must_use]
394    /// Create `TestRequest` and set header.
395    pub fn with_header<K, V>(key: K, value: V) -> TestRequest
396    where
397        HeaderName: TryFrom<K>,
398        HeaderValue: TryFrom<V>,
399        <HeaderName as TryFrom<K>>::Error: Into<HttpError>,
400    {
401        TestRequest::default().header(key, value)
402    }
403
404    #[must_use]
405    /// Create `TestRequest` and set method to `Method::GET`.
406    pub fn get() -> TestRequest {
407        TestRequest::default().method(Method::GET)
408    }
409
410    #[must_use]
411    /// Create `TestRequest` and set method to `Method::POST`.
412    pub fn post() -> TestRequest {
413        TestRequest::default().method(Method::POST)
414    }
415
416    #[must_use]
417    /// Create `TestRequest` and set method to `Method::PUT`.
418    pub fn put() -> TestRequest {
419        TestRequest::default().method(Method::PUT)
420    }
421
422    #[must_use]
423    /// Create `TestRequest` and set method to `Method::PATCH`.
424    pub fn patch() -> TestRequest {
425        TestRequest::default().method(Method::PATCH)
426    }
427
428    #[must_use]
429    /// Create `TestRequest` and set method to `Method::DELETE`.
430    pub fn delete() -> TestRequest {
431        TestRequest::default().method(Method::DELETE)
432    }
433}
434
435impl<St> TestRequest<St> {
436    #[must_use]
437    /// Set HTTP version of this request.
438    pub fn version(mut self, ver: Version) -> Self {
439        self.req.version(ver);
440        self
441    }
442
443    #[must_use]
444    /// Set HTTP method of this request.
445    pub fn method(mut self, meth: Method) -> Self {
446        self.req.method(meth);
447        self
448    }
449
450    #[must_use]
451    /// Set the HTTP request-target without validation or normalization, as received by the server.
452    pub fn uri(mut self, path: &str) -> Self {
453        self.req.uri(path);
454        self
455    }
456
457    #[must_use]
458    /// Set a header.
459    pub fn header<K, V>(mut self, key: K, value: V) -> Self
460    where
461        HeaderName: TryFrom<K>,
462        HeaderValue: TryFrom<V>,
463        <HeaderName as TryFrom<K>>::Error: Into<HttpError>,
464    {
465        self.req.header(key, value);
466        self
467    }
468
469    #[must_use]
470    #[cfg(feature = "cookie")]
471    /// Set cookie for this request.
472    pub fn cookie<C>(mut self, cookie: C) -> Self
473    where
474        C: Into<Cookie<'static>>,
475    {
476        self.req.cookie(cookie);
477        self
478    }
479
480    #[must_use]
481    /// Set request path pattern parameter.
482    ///
483    /// Applies to [`to_srv_request`](Self::to_srv_request),
484    /// [`to_http_request`](Self::to_http_request), and
485    /// [`to_http_parts`](Self::to_http_parts). It is ignored by
486    /// [`to_request`](Self::to_request), because the application router sets
487    /// path parameters for routed requests.
488    pub fn param(mut self, name: &'static str, value: &'static str) -> Self {
489        self.path.add_static(name, value);
490        self
491    }
492
493    #[must_use]
494    /// Set peer addr.
495    ///
496    /// The address is returned by `peer_addr()` of every generated request,
497    /// including one built with [`to_request`](Self::to_request).
498    /// Requests with a peer address must be created inside the ntex runtime.
499    pub fn peer_addr(mut self, addr: SocketAddr) -> Self {
500        self.peer_addr = Some(addr);
501        self
502    }
503
504    #[must_use]
505    /// Set request payload.
506    pub fn payload<B: Into<Bytes>>(mut self, data: B) -> Self {
507        self.req.set_payload(data);
508        self
509    }
510
511    #[must_use]
512    /// Serialize `data` to a URL encoded form and set it as the request payload.
513    ///
514    /// The `Content-Type` header is set to `application/x-www-form-urlencoded`.
515    pub fn form<T: Serialize>(mut self, data: &T) -> Self {
516        let bytes = serde_urlencoded::to_string(data)
517            .expect("Failed to serialize test data as a urlencoded form");
518        self.req.set_payload(bytes);
519        self.req
520            .header(CONTENT_TYPE, "application/x-www-form-urlencoded");
521        self
522    }
523
524    #[must_use]
525    /// Serialize `data` to JSON and set it as the request payload.
526    ///
527    /// The `Content-Type` header is set to `application/json`.
528    pub fn json<T: Serialize>(mut self, data: &T) -> Self {
529        let bytes =
530            crate::http::json::to_bytes(data).expect("Failed to serialize test data to json");
531        self.req.set_payload(bytes);
532        self.req.header(CONTENT_TYPE, "application/json");
533        self
534    }
535
536    #[must_use]
537    /// Set request state.
538    ///
539    /// It is ignored by [`to_request`](Self::to_request), because the
540    /// application supplies the state for routed requests.
541    pub fn state<NewSt: 'static>(self, state: NewSt) -> TestRequest<NewSt> {
542        TestRequest {
543            state,
544            req: self.req,
545            rmap: self.rmap,
546            path: self.path,
547            peer_addr: self.peer_addr,
548            config: self.config,
549        }
550    }
551
552    #[must_use]
553    /// Store a typed configuration value.
554    ///
555    /// This is equivalent of [`WebAppConfig::set_value()`] method for testing
556    /// purpose. The value is available via `HttpRequest::app_value()`.
557    ///
558    /// It is ignored by [`to_request`](Self::to_request), because the
559    /// application configuration applies to routed requests; set the value with
560    /// `App::with_config()` instead.
561    pub fn app_value<T: Send + Sync + 'static>(mut self, data: T) -> Self {
562        self.config = self.config.set_value(data);
563        self
564    }
565
566    #[must_use]
567    #[doc(hidden)]
568    #[deprecated(since = "4.7.0", note = "use `TestRequest::app_value()` instead")]
569    pub fn app_state<T: Send + Sync + 'static>(self, data: T) -> Self {
570        self.app_value(data)
571    }
572
573    #[must_use]
574    #[cfg(test)]
575    /// Set request config
576    pub(crate) fn rmap(mut self, rmap: ResourceMap) -> Self {
577        self.rmap = rmap;
578        self
579    }
580
581    #[must_use]
582    /// Complete request creation and generate `Request` instance.
583    ///
584    /// The request is meant to be passed through an application service, for
585    /// example with [`call_service`]. It keeps the method, URI, version,
586    /// headers, cookies, payload, and peer address. Path parameters, state, and
587    /// application values are supplied by the application instead.
588    pub fn to_request(mut self) -> Request {
589        let mut req = self.req.build();
590        set_peer_addr(req.head_mut(), self.peer_addr);
591        req
592    }
593
594    #[must_use]
595    /// Complete request creation and generate `WebRequest` instance.
596    pub fn to_srv_request(mut self) -> WebRequest<St> {
597        let (mut head, payload) = self.req.build().into_parts();
598        set_peer_addr(&mut head, self.peer_addr);
599        *self.path.get_mut() = head.uri.clone();
600        let cfg = SharedCfg::new("TEST").add(self.config).build();
601
602        WebRequest::new(
603            HttpRequest::new(self.path, head, Rc::new(self.rmap), cfg.get()),
604            payload,
605            self.state,
606        )
607    }
608
609    #[must_use]
610    /// Complete request creation and generate `WebResponse` instance.
611    pub fn to_srv_response(self, res: HttpResponse) -> WebResponse {
612        self.to_srv_request().into_response(res)
613    }
614
615    #[must_use]
616    /// Complete request creation and generate `HttpRequest` instance.
617    pub fn to_http_request(mut self) -> HttpRequest {
618        let (mut head, _) = self.req.build().into_parts();
619        set_peer_addr(&mut head, self.peer_addr);
620        *self.path.get_mut() = head.uri.clone();
621        let cfg = SharedCfg::new("TEST").add(self.config).build();
622
623        HttpRequest::new(self.path, head, Rc::new(self.rmap), cfg.get())
624    }
625
626    #[must_use]
627    /// Complete request creation and generate `HttpRequest` and `Payload` instances.
628    pub fn to_http_parts(mut self) -> (HttpRequest, Payload, St) {
629        let (mut head, payload) = self.req.build().into_parts();
630        set_peer_addr(&mut head, self.peer_addr);
631        *self.path.get_mut() = head.uri.clone();
632        let cfg = SharedCfg::new("TEST").add(self.config).build();
633
634        let req = HttpRequest::new(self.path, head, Rc::new(self.rmap), cfg.get());
635
636        (req, payload, self.state)
637    }
638}
639
640/// Start test server with default configuration
641///
642/// Test server is very simple server that simplify process of writing
643/// integration tests cases for ntex web applications.
644///
645/// # Examples
646///
647/// ```rust
648/// use ntex::web::{self, test, App, HttpResponse};
649///
650/// async fn my_handler() -> Result<HttpResponse, std::io::Error> {
651///     Ok(HttpResponse::Ok().into())
652/// }
653///
654/// #[ntex::test]
655/// async fn test_example() {
656///     let srv = test::server(
657///         async |_| App::new().service(
658///                 web::resource("/").to(my_handler))
659///     );
660///
661///     let req = srv.get("/");
662///     let response = req.send().await.unwrap();
663///     assert!(response.status().is_success());
664/// }
665/// ```
666pub fn server<F, I, Sf>(factory: F) -> TestServer
667where
668    F: AsyncFn(&()) -> I + Send + Clone + 'static,
669    I: IntoServiceFactory<Sf, (), Request>,
670    Sf: ServiceFactory<(), Request> + 'static,
671    Sf::Res: Into<Response>,
672    Sf::Error: ResponseError,
673    Sf::InitError: fmt::Debug,
674{
675    server_with(TestServerConfig::default(), factory)
676}
677
678/// Start test server with custom configuration
679///
680/// Test server could be configured in different ways, for details check
681/// `TestServerConfig` docs.
682///
683/// # Examples
684///
685/// ```rust
686/// use ntex::web::{self, test, App, HttpResponse};
687///
688/// async fn my_handler() -> HttpResponse {
689///     HttpResponse::Ok().into()
690/// }
691///
692/// #[ntex::test]
693/// async fn test_example() {
694///     let srv = test::server_with(test::config().h1(), async |_|
695///         App::new().service(web::resource("/").to(my_handler))
696///     );
697///
698///     let req = srv.get("/");
699///     let response = req.send().await.unwrap();
700///     assert!(response.status().is_success());
701/// }
702/// ```
703pub fn server_with<F, I, Sf>(cfg: TestServerConfig, factory: F) -> TestServer
704where
705    F: AsyncFn(&()) -> I + Send + Clone + 'static,
706    I: IntoServiceFactory<Sf, (), Request>,
707    Sf: ServiceFactory<(), Request> + 'static,
708    Sf::Res: Into<Response>,
709    Sf::Error: ResponseError + 'static,
710    Sf::InitError: fmt::Debug,
711{
712    // Type-erase the application factory, so the HTTP server stacks below
713    // are compiled once instead of once per test application.
714    let factory = Mutex::new(factory);
715    let factory: AppFactory = Arc::new(move || {
716        let factory = factory.lock().unwrap().clone();
717        Box::pin(async move {
718            boxed::factory(
719                factory(&())
720                    .await
721                    .into_factory()
722                    .map(Into::into)
723                    .map_err(AppError::new)
724                    .map_init_err(|e| io::Error::other(format!("{e:?}"))),
725            )
726        })
727    });
728    start_server(cfg, factory)
729}
730
731type AppFactory = Arc<
732    dyn Fn() -> Pin<
733            Box<dyn Future<Output = BoxServiceFactory<(), Request, Response, AppError, io::Error>>>,
734        > + Send
735        + Sync,
736>;
737
738/// Type-erased application error
739struct AppError(Box<dyn ResponseError>);
740
741impl AppError {
742    fn new<E: ResponseError + 'static>(err: E) -> Self {
743        AppError(Box::new(err))
744    }
745}
746
747impl fmt::Debug for AppError {
748    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
749        fmt::Debug::fmt(&self.0, f)
750    }
751}
752
753impl fmt::Display for AppError {
754    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
755        fmt::Display::fmt(&self.0, f)
756    }
757}
758
759impl std::error::Error for AppError {
760    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
761        self.0.source()
762    }
763}
764
765impl ResponseError for AppError {
766    fn error_response(&self) -> Response {
767        self.0.error_response()
768    }
769}
770
771fn start_server(cfg: TestServerConfig, factory: AppFactory) -> TestServer {
772    let sys = System::current().config();
773    let name = System::current().name().to_string();
774
775    let id = Uuid::now_v7();
776    let (tx, rx) = mpsc::channel();
777    log::debug!("Starting {name:?} web server {id:?}");
778
779    let ssl = match cfg.stream {
780        StreamType::Tcp => false,
781        #[cfg(feature = "openssl")]
782        StreamType::Openssl(_) => true,
783        #[cfg(feature = "rustls")]
784        StreamType::Rustls(_) => true,
785    };
786
787    // run server in separate thread
788    thread::spawn(move || {
789        let sys = System::with_config(&name, sys);
790        let factory = async move |&(): &()| factory().await;
791
792        let ctimeout = cfg.client_timeout;
793        let port = cfg.port;
794        let tcp = cfg
795            .listener
796            .unwrap_or_else(|| net::TcpListener::bind(format!("127.0.0.1:{port}")).unwrap());
797        let local_addr = tcp.local_addr().unwrap();
798
799        sys.run(move || {
800            let builder = crate::server::build().workers(1).disable_signals();
801            let secure = match cfg.stream {
802                StreamType::Tcp => false,
803                #[cfg(feature = "openssl")]
804                StreamType::Openssl(_) => true,
805                #[cfg(feature = "rustls")]
806                StreamType::Rustls(_) => true,
807            };
808            let c = cfg.srv_cfg.clone().unwrap_or_else(|| {
809                SharedCfg::new("WEB-SRV")
810                    .add(IoConfig::new())
811                    .add(http::HttpServiceConfig::new().set_headers_read_rate(
812                        ctimeout,
813                        Seconds::ZERO,
814                        256,
815                    ))
816                    .add(WebAppConfig::with(
817                        &name,
818                        secure,
819                        local_addr,
820                        format!("{local_addr}"),
821                    ))
822                    .into()
823            });
824
825            let srv = match cfg.stream {
826                StreamType::Tcp => match cfg.tp {
827                    HttpVer::Http1 => builder.listen("test", tcp, c, async move |st| {
828                        HttpService::h1(factory(st).await)
829                    }),
830                    HttpVer::Http2 => builder.listen("test", tcp, c, async move |st| {
831                        HttpService::h2(factory(st).await)
832                    }),
833                    HttpVer::Both => builder.listen("test", tcp, c, async move |st| {
834                        HttpService::new(factory(st).await)
835                    }),
836                },
837                #[cfg(feature = "openssl")]
838                StreamType::Openssl(acceptor) => match cfg.tp {
839                    HttpVer::Http1 => builder.listen("test", tcp, c, async move |st| {
840                        http::openssl(acceptor.clone(), HttpService::h1(factory(st).await))
841                    }),
842                    HttpVer::Http2 => builder.listen("test", tcp, c, async move |st| {
843                        http::openssl(acceptor.clone(), HttpService::h2(factory(st).await))
844                    }),
845                    HttpVer::Both => builder.listen("test", tcp, c, async move |st| {
846                        http::openssl(acceptor.clone(), HttpService::new(factory(st).await))
847                    }),
848                },
849                #[cfg(feature = "rustls")]
850                StreamType::Rustls(config) => match cfg.tp {
851                    HttpVer::Http1 => builder.listen("test", tcp, c, async move |st| {
852                        http::rustls(
853                            config.clone(),
854                            http::ALPN_PROTO_H1,
855                            HttpService::h1(factory(st).await),
856                        )
857                    }),
858                    HttpVer::Http2 => builder.listen("test", tcp, c, async move |st| {
859                        http::rustls(
860                            config.clone(),
861                            http::ALPN_PROTO_H2,
862                            HttpService::h2(factory(st).await),
863                        )
864                    }),
865                    HttpVer::Both => builder.listen("test", tcp, c, async move |st| {
866                        http::rustls(
867                            config.clone(),
868                            http::ALPN_PROTOS,
869                            HttpService::new(factory(st).await),
870                        )
871                    }),
872                },
873            }
874            .unwrap()
875            .run();
876
877            tx.send((System::current(), srv, local_addr)).unwrap();
878            Ok(())
879        })
880    });
881    let (system, server, addr) = rx.recv().unwrap();
882    thread::sleep(Millis(25).into());
883
884    let cfg = cfg.client_cfg.clone().unwrap_or_else(|| {
885        let cfg = SharedCfg::new("TEST-CLIENT")
886            .add(IoConfig::new().set_connect_timeout(Millis(90_000)))
887            .add(ntex_tls::TlsConfig::new().set_handshake_timeout(Seconds(5)))
888            .add(
889                ntex_h2::ServiceConfig::new()
890                    .set_max_header_list_size(256 * 1024)
891                    .set_max_header_continuation_frames(96),
892            )
893            .add(
894                ClientConfig::new()
895                    .set_response_timeout(Seconds(30))
896                    .set_response_payload_timeout(Seconds(30)),
897            );
898        #[cfg(feature = "ws")]
899        let cfg = cfg.add(
900            WsClientConfig::new()
901                .set_address(addr)
902                .set_handshake_timeout(Seconds(60)),
903        );
904        cfg.build()
905    });
906
907    let client = {
908        #[cfg(feature = "openssl")]
909        {
910            use tls_openssl::ssl::{SslConnector, SslMethod, SslVerifyMode};
911
912            let mut builder = SslConnector::builder(SslMethod::tls()).unwrap();
913            builder.set_verify(SslVerifyMode::NONE);
914            let _ = builder
915                .set_alpn_protos(b"\x02h2\x08http/1.1")
916                .map_err(|e| log::error!("Cannot set alpn protocol: {e:?}"));
917            Client::builder()
918                .openssl(builder.build())
919                .build(cfg.clone())
920        }
921        #[cfg(not(feature = "openssl"))]
922        {
923            Client::builder().build(cfg.clone())
924        }
925    };
926
927    TestServer {
928        id,
929        #[cfg(feature = "ws")]
930        cfg,
931        addr,
932        client,
933        system,
934        ssl,
935        server,
936    }
937}
938
939#[derive(Debug)]
940/// Test server configuration
941pub struct TestServerConfig {
942    tp: HttpVer,
943    stream: StreamType,
944    client_timeout: Seconds,
945    port: u16,
946    listener: Option<net::TcpListener>,
947    srv_cfg: Option<SharedCfg>,
948    client_cfg: Option<SharedCfg>,
949}
950
951#[derive(Clone, Debug)]
952enum HttpVer {
953    Http1,
954    Http2,
955    Both,
956}
957
958#[derive(Clone)]
959#[allow(clippy::large_enum_variant)]
960enum StreamType {
961    Tcp,
962    #[cfg(feature = "openssl")]
963    Openssl(tls_openssl::ssl::SslAcceptor),
964    #[cfg(feature = "rustls")]
965    Rustls(tls_rustls::ServerConfig),
966}
967
968impl fmt::Debug for StreamType {
969    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
970        match self {
971            StreamType::Tcp => write!(f, "StreamType::Tcp"),
972            #[cfg(feature = "openssl")]
973            StreamType::Openssl(_) => write!(f, "StreamType::Openssl"),
974            #[cfg(feature = "rustls")]
975            StreamType::Rustls(_) => write!(f, "StreamType::Rustls"),
976        }
977    }
978}
979
980impl Default for TestServerConfig {
981    fn default() -> Self {
982        TestServerConfig::new()
983    }
984}
985
986#[must_use]
987/// Create default test server config
988pub fn config() -> TestServerConfig {
989    TestServerConfig::new()
990}
991
992impl TestServerConfig {
993    #[must_use]
994    /// Create default server configuration
995    pub(crate) fn new() -> TestServerConfig {
996        TestServerConfig {
997            tp: HttpVer::Both,
998            stream: StreamType::Tcp,
999            client_timeout: Seconds(5),
1000            port: 0,
1001            listener: None,
1002            srv_cfg: None,
1003            client_cfg: None,
1004        }
1005    }
1006
1007    #[must_use]
1008    /// Start http/1.1 server only.
1009    pub fn h1(mut self) -> Self {
1010        self.tp = HttpVer::Http1;
1011        self
1012    }
1013
1014    #[must_use]
1015    /// Start http/2 server only.
1016    pub fn h2(mut self) -> Self {
1017        self.tp = HttpVer::Http2;
1018        self
1019    }
1020
1021    #[must_use]
1022    /// Start openssl server.
1023    #[cfg(feature = "openssl")]
1024    pub fn openssl(mut self, acceptor: tls_openssl::ssl::SslAcceptor) -> Self {
1025        self.stream = StreamType::Openssl(acceptor);
1026        self
1027    }
1028
1029    #[must_use]
1030    /// Start rustls server.
1031    #[cfg(feature = "rustls")]
1032    pub fn rustls(mut self, config: tls_rustls::ServerConfig) -> Self {
1033        self.stream = StreamType::Rustls(config);
1034        self
1035    }
1036
1037    #[must_use]
1038    /// Set server client timeout in seconds for first request.
1039    pub fn client_timeout(mut self, val: Seconds) -> Self {
1040        self.client_timeout = val;
1041        self
1042    }
1043
1044    #[must_use]
1045    /// Set server port. By default, test server binds to a random port assigned by OS.
1046    pub fn port(mut self, port: u16) -> Self {
1047        self.port = port;
1048        self
1049    }
1050
1051    #[must_use]
1052    /// Use an already bound TCP listener for the test server.
1053    ///
1054    /// When set, the configured port is ignored.
1055    pub fn listener(mut self, listener: net::TcpListener) -> Self {
1056        self.listener = Some(listener);
1057        self
1058    }
1059
1060    #[must_use]
1061    /// Use custom `SharedCfg` for test server.
1062    pub fn server_cfg(mut self, cfg: impl Into<SharedCfg>) -> Self {
1063        self.srv_cfg = Some(cfg.into());
1064        self
1065    }
1066
1067    #[must_use]
1068    /// Use custom `SharedCfg` for client.
1069    pub fn client_cfg(mut self, cfg: impl Into<SharedCfg>) -> Self {
1070        self.client_cfg = Some(cfg.into());
1071        self
1072    }
1073}
1074
1075#[derive(Debug)]
1076/// Test server controller
1077pub struct TestServer {
1078    id: Uuid,
1079    #[cfg(feature = "ws")]
1080    cfg: SharedCfg,
1081    addr: net::SocketAddr,
1082    client: Client,
1083    system: crate::rt::System,
1084    ssl: bool,
1085    server: Server,
1086}
1087
1088impl TestServer {
1089    /// Returns the test server's socket address.
1090    pub fn addr(&self) -> net::SocketAddr {
1091        self.addr
1092    }
1093
1094    /// Construct test server url
1095    pub fn url(&self, uri: &str) -> String {
1096        let scheme = if self.ssl { "https" } else { "http" };
1097
1098        if uri.starts_with('/') {
1099            format!("{}://localhost:{}{}", scheme, self.addr.port(), uri)
1100        } else {
1101            format!("{}://localhost:{}/{}", scheme, self.addr.port(), uri)
1102        }
1103    }
1104
1105    /// Create `GET` request
1106    pub fn get<S: AsRef<str>>(&self, path: S) -> ClientRequest {
1107        self.client.get(self.url(path.as_ref()).as_str())
1108    }
1109
1110    /// Create `POST` request
1111    pub fn post<S: AsRef<str>>(&self, path: S) -> ClientRequest {
1112        self.client.post(self.url(path.as_ref()).as_str())
1113    }
1114
1115    /// Create `HEAD` request
1116    pub fn head<S: AsRef<str>>(&self, path: S) -> ClientRequest {
1117        self.client.head(self.url(path.as_ref()).as_str())
1118    }
1119
1120    /// Create `PUT` request
1121    pub fn put<S: AsRef<str>>(&self, path: S) -> ClientRequest {
1122        self.client.put(self.url(path.as_ref()).as_str())
1123    }
1124
1125    /// Create `PATCH` request
1126    pub fn patch<S: AsRef<str>>(&self, path: S) -> ClientRequest {
1127        self.client.patch(self.url(path.as_ref()).as_str())
1128    }
1129
1130    /// Create `DELETE` request
1131    pub fn delete<S: AsRef<str>>(&self, path: S) -> ClientRequest {
1132        self.client.delete(self.url(path.as_ref()).as_str())
1133    }
1134
1135    /// Create `OPTIONS` request
1136    pub fn options<S: AsRef<str>>(&self, path: S) -> ClientRequest {
1137        self.client.options(self.url(path.as_ref()).as_str())
1138    }
1139
1140    /// Create `QUERY` request
1141    pub fn query<S: AsRef<str>>(&self, path: S) -> ClientRequest {
1142        self.client.query(self.url(path.as_ref()).as_str())
1143    }
1144
1145    /// Create client request with the specified method
1146    ///
1147    /// A relative `path` is resolved against the test server url, an absolute
1148    /// url (containing `://`) is used as is.
1149    pub fn request<S: AsRef<str>>(&self, method: Method, path: S) -> ClientRequest {
1150        let path = path.as_ref();
1151        if path.contains("://") {
1152            self.client.request(method, path)
1153        } else {
1154            self.client.request(method, self.url(path).as_str())
1155        }
1156    }
1157
1158    /// Load response's body
1159    pub async fn load_body(
1160        &self,
1161        response: ClientResponse,
1162    ) -> Result<Bytes, Error<ClientPayloadError>> {
1163        response.body().limit(10_485_760).await
1164    }
1165
1166    #[cfg(feature = "ws")]
1167    /// Connect to websocket server at a given path
1168    pub async fn ws_at(&self, path: &str) -> Result<WsConnection<Sealed>, Error<WsClientError>> {
1169        #[cfg(feature = "openssl")]
1170        if self.ssl {
1171            use tls_openssl::ssl::{SslConnector, SslMethod, SslVerifyMode};
1172
1173            let mut builder = SslConnector::builder(SslMethod::tls()).unwrap();
1174            builder.set_verify(SslVerifyMode::NONE);
1175            let _ = builder
1176                .set_alpn_protos(b"\x08http/1.1")
1177                .map_err(|e| log::error!("Cannot set alpn protocol: {e:?}"));
1178
1179            return WsClient::new(self.url(path), &self.cfg)
1180                .openssl(builder.build())
1181                .connect()
1182                .await
1183                .map(WsConnection::seal);
1184        }
1185        #[cfg(not(feature = "openssl"))]
1186        assert!(!self.ssl, "openssl feature is required");
1187
1188        WsClient::new(self.url(path), &self.cfg)
1189            .connect()
1190            .await
1191            .map(WsConnection::seal)
1192    }
1193
1194    #[cfg(feature = "ws")]
1195    /// Connect to a websocket server
1196    pub async fn ws(&self) -> Result<WsConnection<Sealed>, Error<WsClientError>> {
1197        self.ws_at("/").await
1198    }
1199
1200    /// Gracefully stop http server
1201    pub async fn stop(&self) {
1202        self.server.stop(true).await;
1203    }
1204}
1205
1206impl Drop for TestServer {
1207    fn drop(&mut self) {
1208        log::debug!("Stopping test web server {:?}", self.id);
1209        drop(self.server.stop(false));
1210        thread::sleep(time::Duration::from_millis(75));
1211        self.system.stop();
1212        thread::sleep(time::Duration::from_millis(25));
1213    }
1214}
1215
1216#[cfg(test)]
1217mod tests {
1218    use serde::{Deserialize, Serialize};
1219
1220    use super::*;
1221    use crate::http::{HttpMessage, header};
1222    use crate::web::{self, App};
1223
1224    /// STATEMENT: `TestRequest` carries configured HTTP metadata, application state, and an empty default payload.
1225    ///
1226    /// HOW:
1227    /// - Set headers, HTTP version, route parameters, application state, and peer address and assert each.
1228    /// - Check TCP stream debug text and assert a request without payload loads as empty bytes.
1229    #[crate::rt_test]
1230    async fn test_basics() {
1231        let req = TestRequest::with_header(header::CONTENT_TYPE, "application/json")
1232            .version(Version::HTTP_2)
1233            .header(header::DATE, "some date")
1234            .param("test", "123")
1235            .app_value(20u64)
1236            .peer_addr("127.0.0.1:8081".parse().unwrap())
1237            .to_http_request();
1238        assert!(req.headers().contains_key(header::CONTENT_TYPE));
1239        assert!(req.headers().contains_key(header::DATE));
1240        assert_eq!(req.peer_addr(), Some("127.0.0.1:8081".parse().unwrap()));
1241        assert_eq!(&req.match_info()["test"], "123");
1242        assert_eq!(req.version(), Version::HTTP_2);
1243        let data = req.app_value::<u64>().unwrap();
1244        assert_eq!(*data, 20);
1245        assert_eq!(format!("{:?}", StreamType::Tcp), "StreamType::Tcp");
1246
1247        let (_, pl, ()) = TestRequest::with_header(header::CONTENT_TYPE, "application/json")
1248            .to_srv_request()
1249            .into_parts();
1250        let res = load_stream(pl).await.unwrap();
1251        assert_eq!(res, &b""[..]);
1252    }
1253
1254    /// STATEMENT: `to_request` keeps the peer address for a routed request, while the router,
1255    /// not `param`, supplies path parameters.
1256    ///
1257    /// HOW:
1258    /// - Route `/{name}` to a handler that returns the peer address and `name` match.
1259    /// - Call it via `call_service` with `peer_addr` and a conflicting `param`, and assert the
1260    ///   body shows the address and the routed segment.
1261    /// - Call it without `peer_addr` and assert the handler sees `None`.
1262    #[crate::rt_test]
1263    async fn test_to_request_peer_addr() {
1264        let app = init_service(App::new().route(
1265            "/{name}",
1266            web::get().to(async |req: HttpRequest| {
1267                HttpResponse::Ok().body(format!(
1268                    "{:?} {}",
1269                    req.peer_addr(),
1270                    &req.match_info()["name"]
1271                ))
1272            }),
1273        ))
1274        .await;
1275
1276        let req = TestRequest::with_uri("/routed")
1277            .peer_addr("127.0.0.1:8081".parse().unwrap())
1278            .param("name", "ignored")
1279            .to_request();
1280        let resp = call_service(&app, req).await;
1281        assert_eq!(resp.status(), StatusCode::OK);
1282        assert_eq!(read_body(resp).await, &b"Some(127.0.0.1:8081) routed"[..]);
1283
1284        let resp = call_service(&app, TestRequest::with_uri("/plain").to_request()).await;
1285        assert_eq!(read_body(resp).await, &b"None plain"[..]);
1286    }
1287
1288    /// STATEMENT: Request-builder method helpers dispatch to their corresponding application routes.
1289    ///
1290    /// HOW:
1291    /// - Register distinct PUT, PATCH, and DELETE response bodies.
1292    /// - Build each request with its method helper and assert `read_response` returns the matching bytes.
1293    #[crate::rt_test]
1294    async fn test_request_methods() {
1295        let app = init_service(
1296            App::new().service(
1297                web::resource("/index.html")
1298                    .route(web::put().to(async || HttpResponse::Ok().body("put!")))
1299                    .route(web::patch().to(async || HttpResponse::Ok().body("patch!")))
1300                    .route(web::delete().to(async || HttpResponse::Ok().body("delete!"))),
1301            ),
1302        )
1303        .await;
1304
1305        let put_req = TestRequest::put()
1306            .uri("/index.html")
1307            .header(header::CONTENT_TYPE, "application/json")
1308            .to_request();
1309
1310        let result = read_response(&app, put_req).await;
1311        assert_eq!(result, Bytes::from_static(b"put!"));
1312
1313        let patch_req = TestRequest::patch()
1314            .uri("/index.html")
1315            .header(header::CONTENT_TYPE, "application/json")
1316            .to_request();
1317
1318        let result = read_response(&app, patch_req).await;
1319        assert_eq!(result, Bytes::from_static(b"patch!"));
1320
1321        let delete_req = TestRequest::delete().uri("/index.html").to_request();
1322        let result = read_response(&app, delete_req).await;
1323        assert_eq!(result, Bytes::from_static(b"delete!"));
1324    }
1325
1326    /// STATEMENT: `read_response` collects the body returned by an initialized application service.
1327    ///
1328    /// HOW:
1329    /// - Register a POST handler returning `welcome!` and build a POST request to its path.
1330    /// - Read the response and assert the exact body bytes.
1331    #[crate::rt_test]
1332    async fn test_response() {
1333        let app = init_service(
1334            App::new().service(
1335                web::resource("/index.html")
1336                    .route(web::post().to(async || HttpResponse::Ok().body("welcome!"))),
1337            ),
1338        )
1339        .await;
1340
1341        let req = TestRequest::post()
1342            .uri("/index.html")
1343            .header(header::CONTENT_TYPE, "application/json")
1344            .to_request();
1345
1346        let result = read_response(&app, req).await;
1347        assert_eq!(result, Bytes::from_static(b"welcome!"));
1348    }
1349
1350    #[derive(Serialize, Deserialize)]
1351    struct Person {
1352        id: String,
1353        name: String,
1354    }
1355
1356    /// STATEMENT: `read_response_json` deserializes a service's JSON response into a typed value.
1357    ///
1358    /// HOW:
1359    /// - POST raw JSON to a handler that extracts and echoes a `Person` as JSON.
1360    /// - Deserialize the response with `read_response_json` and assert the person's ID.
1361    #[crate::rt_test]
1362    async fn test_response_json() {
1363        let app = init_service(
1364            App::new().service(web::resource("/people").route(web::post().to(
1365                async |person: web::types::Json<Person>| {
1366                    HttpResponse::Ok().json(&person.into_inner())
1367                },
1368            ))),
1369        )
1370        .await;
1371
1372        let payload = r#"{"id":"12345","name":"User name"}"#.as_bytes();
1373
1374        let req = TestRequest::post()
1375            .uri("/people")
1376            .header(header::CONTENT_TYPE, "application/json")
1377            .payload(payload)
1378            .to_request();
1379
1380        let result: Person = read_response_json(&app, req).await;
1381        assert_eq!(&result.id, "12345");
1382    }
1383
1384    /// STATEMENT: Form request construction sets the media type and round-trips serialized fields.
1385    ///
1386    /// HOW:
1387    /// - Build a POST using `TestRequest::form` and assert its URL-encoded content type.
1388    /// - Send it to a form-extracting JSON responder and assert both decoded response fields.
1389    #[crate::rt_test]
1390    async fn test_request_response_form() {
1391        let app = init_service(
1392            App::new().service(web::resource("/people").route(web::post().to(
1393                async |person: web::types::Form<Person>| {
1394                    HttpResponse::Ok().json(&person.into_inner())
1395                },
1396            ))),
1397        )
1398        .await;
1399
1400        let payload = Person {
1401            id: "12345".to_string(),
1402            name: "User name".to_string(),
1403        };
1404
1405        let req = TestRequest::post()
1406            .uri("/people")
1407            .form(&payload)
1408            .to_request();
1409
1410        assert_eq!(req.content_type(), "application/x-www-form-urlencoded");
1411
1412        let result: Person = read_response_json(&app, req).await;
1413        assert_eq!(&result.id, "12345");
1414        assert_eq!(&result.name, "User name");
1415    }
1416
1417    /// STATEMENT: JSON request construction sets the media type and round-trips serialized fields.
1418    ///
1419    /// HOW:
1420    /// - Build a POST using `TestRequest::json` and assert `application/json`.
1421    /// - Echo the extracted person as JSON and assert both fields after response deserialization.
1422    #[crate::rt_test]
1423    async fn test_request_response_json() {
1424        let app = init_service(
1425            App::new().service(web::resource("/people").route(web::post().to(
1426                async |person: web::types::Json<Person>| {
1427                    HttpResponse::Ok().json(&person.into_inner())
1428                },
1429            ))),
1430        )
1431        .await;
1432
1433        let payload = Person {
1434            id: "12345".to_string(),
1435            name: "User name".to_string(),
1436        };
1437
1438        let req = TestRequest::post()
1439            .uri("/people")
1440            .json(&payload)
1441            .to_request();
1442
1443        assert_eq!(req.content_type(), "application/json");
1444
1445        let result: Person = read_response_json(&app, req).await;
1446        assert_eq!(&result.id, "12345");
1447        assert_eq!(&result.name, "User name");
1448    }
1449
1450    /// STATEMENT: An asynchronous handler can await successful work from `web::block`.
1451    ///
1452    /// HOW:
1453    /// - Register a handler that offloads obtaining a value and builds a response from its result.
1454    /// - POST to the handler and assert the response has a success status.
1455    #[crate::rt_test]
1456    async fn test_async_with_block() {
1457        async fn async_with_block() -> Result<HttpResponse, Infallible> {
1458            let res = web::block(move || Some(4usize).ok_or("wrong")).await;
1459
1460            #[allow(clippy::match_wild_err_arm)]
1461            match res {
1462                Ok(value) => Ok(HttpResponse::Ok()
1463                    .content_type("text/plain")
1464                    .body(format!("Async with block value: {value}"))),
1465                Err(_) => panic!("Unexpected"),
1466            }
1467        }
1468
1469        let app =
1470            init_service(App::new().service(web::resource("/index.html").to(async_with_block)))
1471                .await;
1472
1473        let req = TestRequest::post().uri("/index.html").to_request();
1474        let res = app.call(req).await.unwrap();
1475        assert!(res.status().is_success());
1476    }
1477
1478    /// STATEMENT: Test-server method helpers send their corresponding HTTP methods and load empty bodies.
1479    ///
1480    /// HOW:
1481    /// - Start a server with PUT, PATCH, DELETE, and OPTIONS routes and call each helper.
1482    /// - Assert all statuses are OK, then load another PUT response and assert its body is empty.
1483    #[crate::rt_test]
1484    async fn test_test_methods() {
1485        let srv = server(async |()| {
1486            App::new().service(
1487                web::resource("/").route((
1488                    web::route()
1489                        .method(Method::PUT)
1490                        .to(async || HttpResponse::Ok()),
1491                    web::route()
1492                        .method(Method::PATCH)
1493                        .to(async || HttpResponse::Ok()),
1494                    web::route()
1495                        .method(Method::DELETE)
1496                        .to(async || HttpResponse::Ok()),
1497                    web::route()
1498                        .method(Method::OPTIONS)
1499                        .to(async || HttpResponse::Ok()),
1500                )),
1501            )
1502        });
1503
1504        assert_eq!(srv.put("/").send().await.unwrap().status(), StatusCode::OK);
1505        assert_eq!(
1506            srv.patch("/").send().await.unwrap().status(),
1507            StatusCode::OK
1508        );
1509        assert_eq!(
1510            srv.delete("/").send().await.unwrap().status(),
1511            StatusCode::OK
1512        );
1513        assert_eq!(
1514            srv.options("/").send().await.unwrap().status(),
1515            StatusCode::OK
1516        );
1517
1518        let res = srv.put("").send().await.unwrap();
1519        assert_eq!(srv.load_body(res).await.unwrap(), Bytes::new());
1520    }
1521
1522    /// STATEMENT: `TestRequest::state` preserves state in decomposed and service-request forms.
1523    ///
1524    /// HOW:
1525    /// - Set numeric state and assert `to_http_parts` returns it.
1526    /// - Set `AppState<usize>` and assert the service request exposes the wrapped value.
1527    #[crate::rt_test]
1528    async fn test_request_state() {
1529        let (_, _, st) = TestRequest::default().state(10usize).to_http_parts();
1530        assert_eq!(st, 10);
1531
1532        let req = TestRequest::default()
1533            .state(web::AppState::new(5usize))
1534            .to_srv_request();
1535        assert_eq!(**req.st(), 5);
1536    }
1537
1538    /// STATEMENT: Test-server configuration applies HTTP/1 mode and accepts custom client configuration.
1539    ///
1540    /// HOW:
1541    /// - Configure HTTP/1, an ephemeral port, and a named client configuration; inspect TCP debug output.
1542    /// - Start the server, assert OK and HTTP/1.1 from a request, and stop it explicitly.
1543    #[crate::rt_test]
1544    async fn test_server_config() {
1545        let cfg = config()
1546            .h1()
1547            .port(0)
1548            .client_cfg(SharedCfg::new("CUSTOM-CLIENT"));
1549        let dbg = format!("{cfg:?}");
1550        assert!(dbg.contains("StreamType::Tcp"), "{dbg}");
1551
1552        let srv = server_with(cfg, async |()| {
1553            App::new().service(web::resource("/").to(async || HttpResponse::Ok()))
1554        });
1555        let res = srv.get("/").send().await.unwrap();
1556        assert_eq!(res.status(), StatusCode::OK);
1557        assert_eq!(res.version(), http::Version::HTTP_11);
1558        srv.stop().await;
1559    }
1560
1561    /// STATEMENT: A supplied test-server listener takes precedence over the configured port.
1562    ///
1563    /// HOW:
1564    /// - Bind an ephemeral listener and configure both that listener and its already-bound port.
1565    /// - Start the server, assert it uses the listener address, and verify an OK request succeeds.
1566    #[crate::rt_test]
1567    async fn test_server_listener_ignores_port() {
1568        // regression: the configured port was bound even if a listener is set
1569        let lst = net::TcpListener::bind("127.0.0.1:0").unwrap();
1570        let addr = lst.local_addr().unwrap();
1571
1572        let srv = server_with(config().port(addr.port()).listener(lst), async |()| {
1573            App::new().service(web::resource("/").to(async || HttpResponse::Ok()))
1574        });
1575        assert_eq!(srv.addr(), addr);
1576        let res = srv.get("/").send().await.unwrap();
1577        assert_eq!(res.status(), StatusCode::OK);
1578    }
1579
1580    #[cfg(feature = "openssl")]
1581    fn ssl_acceptor(h2: bool) -> tls_openssl::ssl::SslAcceptor {
1582        use tls_openssl::ssl::{SslAcceptor, SslFiletype, SslMethod};
1583
1584        let mut builder = SslAcceptor::mozilla_intermediate(SslMethod::tls()).unwrap();
1585        builder
1586            .set_private_key_file("./tests/key.pem", SslFiletype::PEM)
1587            .unwrap();
1588        builder
1589            .set_certificate_chain_file("./tests/cert.pem")
1590            .unwrap();
1591        builder.set_alpn_select_callback(move |_, protos| {
1592            if h2 && protos.windows(3).any(|w| w == b"\x02h2") {
1593                Ok(b"h2")
1594            } else {
1595                Ok(b"http/1.1")
1596            }
1597        });
1598        builder.build()
1599    }
1600
1601    /// STATEMENT: OpenSSL test servers expose HTTPS URLs and negotiate the configured HTTP protocol.
1602    ///
1603    /// HOW:
1604    /// - Start HTTP/1-only, HTTP/2-only, and automatic servers with matching ALPN selections.
1605    /// - Assert OpenSSL debug identity, HTTPS URL scheme, OK status, and the expected response version.
1606    #[cfg(feature = "openssl")]
1607    #[crate::rt_test]
1608    async fn test_server_openssl() {
1609        for (cfg, h2, version) in [
1610            (config().h1(), false, http::Version::HTTP_11),
1611            (config().h2(), true, http::Version::HTTP_2),
1612            (config(), true, http::Version::HTTP_2),
1613            (config(), false, http::Version::HTTP_11),
1614        ] {
1615            let cfg = cfg.openssl(ssl_acceptor(h2));
1616            assert!(format!("{cfg:?}").contains("StreamType::Openssl"));
1617
1618            let srv = server_with(cfg, async |()| {
1619                App::new().service(web::resource("/").to(async || HttpResponse::Ok()))
1620            });
1621            assert!(srv.url("/").starts_with("https://"));
1622            let res = srv.get("/").send().await.unwrap();
1623            assert_eq!(res.status(), StatusCode::OK);
1624            assert_eq!(res.version(), version);
1625        }
1626    }
1627
1628    /// STATEMENT: The test-server WebSocket helper connects to an OpenSSL-backed upgrade handler.
1629    ///
1630    /// HOW:
1631    /// - Start a TLS HTTP/1 server whose root handler calls `web::ws::start`.
1632    /// - Await `srv.ws()` and assert the connection succeeds.
1633    #[cfg(all(feature = "openssl", feature = "ws"))]
1634    #[crate::rt_test]
1635    async fn test_server_openssl_ws() {
1636        let srv = server_with(config().h1().openssl(ssl_acceptor(false)), async |()| {
1637            App::new().service(
1638                web::resource("/").route(web::to(async |req: web::HttpRequest| {
1639                    let _ = web::ws::start(&req, None, async |_: web::ws::Frame| {
1640                        Ok::<_, io::Error>(None)
1641                    })
1642                    .await;
1643                })),
1644            )
1645        });
1646        assert!(srv.ws().await.is_ok());
1647    }
1648
1649    /// STATEMENT: Rustls test-server configuration identifies its TLS stream type in debug output.
1650    ///
1651    /// HOW:
1652    /// - Load the test certificate and private key and build a Rustls server configuration.
1653    /// - Apply it to the test-server configuration and assert `StreamType::Rustls` appears in debug text.
1654    #[cfg(feature = "rustls")]
1655    #[test]
1656    fn test_server_config_rustls_debug() {
1657        use std::{fs::File, io::BufReader};
1658
1659        let cert_file = &mut BufReader::new(File::open("tests/cert.pem").unwrap());
1660        let key_file = &mut BufReader::new(File::open("tests/key.pem").unwrap());
1661        let cert_chain = rustls_pemfile::certs(cert_file)
1662            .map(|r| r.unwrap())
1663            .collect();
1664        let key = rustls_pemfile::private_key(key_file).unwrap().unwrap();
1665        let cfg = tls_rustls::ServerConfig::builder()
1666            .with_no_client_auth()
1667            .with_single_cert(cert_chain, key)
1668            .unwrap();
1669        assert!(format!("{:?}", config().rustls(cfg)).contains("StreamType::Rustls"));
1670    }
1671
1672    /// STATEMENT: `TestRequest::cookie` produces a request with a parseable named cookie.
1673    ///
1674    /// HOW:
1675    /// - Add a cookie with domain, path, HTTP-only, and lifetime settings to a request.
1676    /// - Parse its cookies and assert exactly one cookie named `name` is present.
1677    #[cfg(feature = "cookie")]
1678    #[test]
1679    fn test_response_cookies() {
1680        let req = TestRequest::default()
1681            .cookie(
1682                coo_kie::Cookie::build(("name", "value"))
1683                    .domain("www.rust-lang.org")
1684                    .path("/test")
1685                    .http_only(true)
1686                    .max_age(::time::Duration::days(1)),
1687            )
1688            .to_http_request();
1689
1690        let cookies = req.cookies().unwrap();
1691        assert_eq!(cookies.len(), 1);
1692        assert_eq!(cookies[0].name(), "name");
1693    }
1694}