1#![allow(clippy::missing_panics_doc)]
3use std::{fmt, io, marker::PhantomData, net, thread, time};
4
5use ntex_io::{Io, IoConfig};
6use ntex_net::tcp_connect;
7use ntex_rt::System;
8use ntex_service::{IntoService, Service, cfg::SharedCfg};
9use socket2::{Domain, SockAddr, Socket, Type};
10use uuid::Uuid;
11
12use super::{NoConfig, Server, ServerAppConfig, ServerBuilder};
13
14pub struct TestServerBuilder<Cfg, F, Sf, I> {
16 id: Uuid,
17 cfg: Cfg,
18 factory: F,
19 config: SharedCfg,
20 client_config: SharedCfg,
21 _t: PhantomData<(Sf, I)>,
22}
23
24impl<Cfg, F, Sf, I> fmt::Debug for TestServerBuilder<Cfg, F, Sf, I> {
25 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
26 f.debug_struct("TestServerBuilder")
27 .field("id", &self.id)
28 .field("config", &self.config)
29 .field("client_config", &self.client_config)
30 .finish()
31 }
32}
33
34impl<F, S, I> TestServerBuilder<NoConfig, F, S, I>
35where
36 F: AsyncFn() -> I + Send + Clone + 'static,
37 I: IntoService<S, (), Io> + 'static,
38 S: Service<(), Io> + 'static,
39{
40 #[must_use]
41 pub fn new(factory: F) -> Self {
43 Self {
44 factory,
45 id: Uuid::now_v7(),
46 cfg: NoConfig,
47 config: SharedCfg::new("TEST-SERVER").into(),
48 client_config: SharedCfg::new("TEST-CLIENT").into(),
49 _t: PhantomData,
50 }
51 }
52}
53
54impl<Cfg, F, S, I> TestServerBuilder<Cfg, F, S, I>
55where
56 F: AsyncFn() -> I + Send + Clone + 'static,
57 I: IntoService<S, Cfg::State, Io> + 'static,
58 S: Service<Cfg::State, Io> + 'static,
59 Cfg: ServerAppConfig + 'static,
60{
61 #[must_use]
62 pub fn with(cfg: Cfg, factory: F) -> Self {
64 Self {
65 cfg,
66 factory,
67 id: Uuid::now_v7(),
68 config: SharedCfg::new("TEST-SERVER").into(),
69 client_config: SharedCfg::new("TEST-CLIENT").into(),
70 _t: PhantomData,
71 }
72 }
73
74 #[must_use]
75 pub fn config<T: Into<SharedCfg>>(mut self, cfg: T) -> Self {
77 self.config = cfg.into();
78 self
79 }
80
81 #[must_use]
82 pub fn client_config<T: Into<SharedCfg>>(mut self, cfg: T) -> Self {
84 self.client_config = cfg.into();
85 self
86 }
87
88 pub fn start(self) -> TestServer {
90 log::debug!("Starting test server {:?}", self.id);
91 let cfg = self.cfg;
92 let config = self.config;
93 let factory = self.factory;
94 let sys_cfg = System::current().config();
95 let name = System::current().name().to_string();
96
97 let (tx, rx) = oneshot::channel();
98 thread::spawn(move || {
100 let sys = System::with_config(&name, sys_cfg);
101 let tcp = net::TcpListener::bind("127.0.0.1:0").unwrap();
102 let local_addr = tcp.local_addr().unwrap();
103
104 sys.run(move || {
105 let server = ServerBuilder::new(cfg)
106 .listen("test", tcp, config, async move |_| factory().await)?
107 .workers(1)
108 .disable_signals()
109 .enable_affinity()
110 .run();
111
112 ntex_rt::spawn(async move {
113 tx.send((System::current(), local_addr, server))
114 .expect("Failed to send Server to TestServer");
115 });
116
117 Ok(())
118 })
119 });
120 let (system, addr, server) = rx.recv().unwrap();
121 thread::sleep(time::Duration::from_millis(25));
122
123 TestServer {
124 addr,
125 server,
126 system,
127 id: self.id,
128 cfg: self.client_config,
129 }
130 }
131}
132
133pub fn test_server<F, S>(factory: F) -> TestServer
163where
164 F: AsyncFn() -> S + Send + Clone + 'static,
165 S: Service<(), Io> + 'static,
166{
167 TestServerBuilder::new(factory).start()
168}
169
170pub fn build_test_server<Cfg, F>(cfg: Cfg, factory: F) -> TestServer
172where
173 Cfg: ServerAppConfig,
174 F: AsyncFnOnce(ServerBuilder<Cfg>) -> ServerBuilder<Cfg> + Send + 'static,
175{
176 let sys = System::current().config();
177 let name = System::current().name().to_string();
178
179 let id = Uuid::now_v7();
180 log::debug!("Starting {name:?} server {id:?}");
181
182 let (tx, rx) = oneshot::channel();
183
184 thread::spawn(move || {
186 let sys = System::with_config(&name, sys);
187
188 sys.block_on(async move {
189 let server = factory(ServerBuilder::new(cfg))
190 .await
191 .workers(1)
192 .disable_signals()
193 .run();
194 tx.send((System::current(), server.clone()))
195 .expect("Failed to send Server to TestServer");
196 let _ = server.await;
197 });
198 });
199 let (system, server) = rx.recv().unwrap();
200 thread::sleep(time::Duration::from_millis(25));
201
202 TestServer {
203 id,
204 system,
205 server,
206 addr: "127.0.0.1:0".parse().unwrap(),
207 cfg: SharedCfg::new("TEST-CLIENT").add(IoConfig::new()).into(),
208 }
209}
210
211#[derive(Clone, Debug)]
212pub struct TestServer {
214 id: Uuid,
215 addr: net::SocketAddr,
216 system: System,
217 server: Server,
218 cfg: SharedCfg,
219}
220
221impl TestServer {
222 pub fn addr(&self) -> net::SocketAddr {
224 self.addr
225 }
226
227 #[must_use]
228 pub fn set_addr(mut self, addr: net::SocketAddr) -> Self {
229 self.addr = addr;
230 self
231 }
232
233 pub fn config(&self) -> SharedCfg {
235 self.cfg.clone()
236 }
237
238 pub async fn connect(&self) -> io::Result<Io> {
240 tcp_connect(self.addr, self.cfg.clone()).await
241 }
242
243 pub fn stop(&self) {
245 drop(self.server.stop(true));
246 }
247
248 pub fn unused_addr() -> net::SocketAddr {
250 let addr: net::SocketAddr = "127.0.0.1:0".parse().unwrap();
251 let socket = Socket::new(Domain::IPV4, Type::STREAM, None).unwrap();
252 socket.set_reuse_address(true).unwrap();
253 socket.bind(&SockAddr::from(addr)).unwrap();
254 let tcp = net::TcpListener::from(socket);
255 tcp.local_addr().unwrap()
256 }
257
258 pub fn server(&self) -> Server {
260 self.server.clone()
261 }
262}
263
264impl Drop for TestServer {
265 fn drop(&mut self) {
266 log::debug!("Stopping test server {:?}", self.id);
267 drop(self.server.stop(false));
268 thread::sleep(time::Duration::from_millis(75));
269 self.system.stop();
270 thread::sleep(time::Duration::from_millis(25));
271 }
272}