1#![deny(rust_2018_idioms, warnings)]
3#![allow(clippy::type_complexity)]
4
5use std::sync::mpsc;
6use std::{net, thread};
7
8use actori_rt::{net::TcpStream, System};
9use actori_server::{Server, ServerBuilder, ServiceFactory};
10use net2::TcpBuilder;
11
12#[cfg(not(test))] pub use actori_macros::test;
14
15pub struct TestServer;
39
40pub struct TestServerRuntime {
42 addr: net::SocketAddr,
43 host: String,
44 port: u16,
45 system: System,
46}
47
48impl TestServer {
49 pub fn start<F>(mut factory: F) -> TestServerRuntime
51 where
52 F: FnMut(ServerBuilder) -> ServerBuilder + Send + 'static,
53 {
54 let (tx, rx) = mpsc::channel();
55
56 thread::spawn(move || {
58 let sys = System::new("actori-test-server");
59 factory(Server::build())
60 .workers(1)
61 .disable_signals()
62 .start();
63
64 tx.send(System::current()).unwrap();
65 sys.run()
66 });
67 let system = rx.recv().unwrap();
68
69 TestServerRuntime {
70 system,
71 addr: "127.0.0.1:0".parse().unwrap(),
72 host: "127.0.0.1".to_string(),
73 port: 0,
74 }
75 }
76
77 pub fn with<F: ServiceFactory<TcpStream>>(factory: F) -> TestServerRuntime {
79 let (tx, rx) = mpsc::channel();
80
81 thread::spawn(move || {
83 let sys = System::new("actori-test-server");
84 let tcp = net::TcpListener::bind("127.0.0.1:0").unwrap();
85 let local_addr = tcp.local_addr().unwrap();
86
87 Server::build()
88 .listen("test", tcp, factory)?
89 .workers(1)
90 .disable_signals()
91 .start();
92
93 tx.send((System::current(), local_addr)).unwrap();
94 sys.run()
95 });
96
97 let (system, addr) = rx.recv().unwrap();
98
99 let host = format!("{}", addr.ip());
100 let port = addr.port();
101
102 TestServerRuntime {
103 system,
104 addr,
105 host,
106 port,
107 }
108 }
109
110 pub fn unused_addr() -> net::SocketAddr {
112 let addr: net::SocketAddr = "127.0.0.1:0".parse().unwrap();
113 let socket = TcpBuilder::new_v4().unwrap();
114 socket.bind(&addr).unwrap();
115 socket.reuse_address(true).unwrap();
116 let tcp = socket.to_tcp_listener().unwrap();
117 tcp.local_addr().unwrap()
118 }
119}
120
121impl TestServerRuntime {
122 pub fn host(&self) -> &str {
124 &self.host
125 }
126
127 pub fn port(&self) -> u16 {
129 self.port
130 }
131
132 pub fn addr(&self) -> net::SocketAddr {
134 self.addr
135 }
136
137 fn stop(&mut self) {
139 self.system.stop();
140 }
141
142 pub fn connect(&self) -> std::io::Result<TcpStream> {
144 TcpStream::from_std(net::TcpStream::connect(self.addr)?)
145 }
146}
147
148impl Drop for TestServerRuntime {
149 fn drop(&mut self) {
150 self.stop()
151 }
152}