1use 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
59pub 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
65pub 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
74pub 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
111pub 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
149pub 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
180pub 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
222pub 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
257pub 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
269pub 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
315pub 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
324pub async fn respond_to<T: Responder>(slf: T, req: &HttpRequest) -> HttpResponse {
326 T::respond_to(slf, &(), req).await
327}
328
329#[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 pub fn with_uri(path: &str) -> TestRequest {
390 TestRequest::default().uri(path)
391 }
392
393 #[must_use]
394 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 pub fn get() -> TestRequest {
407 TestRequest::default().method(Method::GET)
408 }
409
410 #[must_use]
411 pub fn post() -> TestRequest {
413 TestRequest::default().method(Method::POST)
414 }
415
416 #[must_use]
417 pub fn put() -> TestRequest {
419 TestRequest::default().method(Method::PUT)
420 }
421
422 #[must_use]
423 pub fn patch() -> TestRequest {
425 TestRequest::default().method(Method::PATCH)
426 }
427
428 #[must_use]
429 pub fn delete() -> TestRequest {
431 TestRequest::default().method(Method::DELETE)
432 }
433}
434
435impl<St> TestRequest<St> {
436 #[must_use]
437 pub fn version(mut self, ver: Version) -> Self {
439 self.req.version(ver);
440 self
441 }
442
443 #[must_use]
444 pub fn method(mut self, meth: Method) -> Self {
446 self.req.method(meth);
447 self
448 }
449
450 #[must_use]
451 pub fn uri(mut self, path: &str) -> Self {
453 self.req.uri(path);
454 self
455 }
456
457 #[must_use]
458 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 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 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 pub fn peer_addr(mut self, addr: SocketAddr) -> Self {
500 self.peer_addr = Some(addr);
501 self
502 }
503
504 #[must_use]
505 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 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 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 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 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 pub(crate) fn rmap(mut self, rmap: ResourceMap) -> Self {
577 self.rmap = rmap;
578 self
579 }
580
581 #[must_use]
582 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 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 pub fn to_srv_response(self, res: HttpResponse) -> WebResponse {
612 self.to_srv_request().into_response(res)
613 }
614
615 #[must_use]
616 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 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
640pub 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
678pub 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 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
738struct 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 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)]
940pub 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]
987pub fn config() -> TestServerConfig {
989 TestServerConfig::new()
990}
991
992impl TestServerConfig {
993 #[must_use]
994 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 pub fn h1(mut self) -> Self {
1010 self.tp = HttpVer::Http1;
1011 self
1012 }
1013
1014 #[must_use]
1015 pub fn h2(mut self) -> Self {
1017 self.tp = HttpVer::Http2;
1018 self
1019 }
1020
1021 #[must_use]
1022 #[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 #[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 pub fn client_timeout(mut self, val: Seconds) -> Self {
1040 self.client_timeout = val;
1041 self
1042 }
1043
1044 #[must_use]
1045 pub fn port(mut self, port: u16) -> Self {
1047 self.port = port;
1048 self
1049 }
1050
1051 #[must_use]
1052 pub fn listener(mut self, listener: net::TcpListener) -> Self {
1056 self.listener = Some(listener);
1057 self
1058 }
1059
1060 #[must_use]
1061 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 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)]
1076pub 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 pub fn addr(&self) -> net::SocketAddr {
1091 self.addr
1092 }
1093
1094 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 pub fn get<S: AsRef<str>>(&self, path: S) -> ClientRequest {
1107 self.client.get(self.url(path.as_ref()).as_str())
1108 }
1109
1110 pub fn post<S: AsRef<str>>(&self, path: S) -> ClientRequest {
1112 self.client.post(self.url(path.as_ref()).as_str())
1113 }
1114
1115 pub fn head<S: AsRef<str>>(&self, path: S) -> ClientRequest {
1117 self.client.head(self.url(path.as_ref()).as_str())
1118 }
1119
1120 pub fn put<S: AsRef<str>>(&self, path: S) -> ClientRequest {
1122 self.client.put(self.url(path.as_ref()).as_str())
1123 }
1124
1125 pub fn patch<S: AsRef<str>>(&self, path: S) -> ClientRequest {
1127 self.client.patch(self.url(path.as_ref()).as_str())
1128 }
1129
1130 pub fn delete<S: AsRef<str>>(&self, path: S) -> ClientRequest {
1132 self.client.delete(self.url(path.as_ref()).as_str())
1133 }
1134
1135 pub fn options<S: AsRef<str>>(&self, path: S) -> ClientRequest {
1137 self.client.options(self.url(path.as_ref()).as_str())
1138 }
1139
1140 pub fn query<S: AsRef<str>>(&self, path: S) -> ClientRequest {
1142 self.client.query(self.url(path.as_ref()).as_str())
1143 }
1144
1145 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 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 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 pub async fn ws(&self) -> Result<WsConnection<Sealed>, Error<WsClientError>> {
1197 self.ws_at("/").await
1198 }
1199
1200 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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[crate::rt_test]
1567 async fn test_server_listener_ignores_port() {
1568 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 #[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 #[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 #[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 #[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}