actori_testing/
lib.rs

1//! Various helpers for Actori applications to use during testing.
2#![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))] // Work around for rust-lang/rust#62127
13pub use actori_macros::test;
14
15/// The `TestServer` type.
16///
17/// `TestServer` is very simple test server that simplify process of writing
18/// integration tests for actori-net applications.
19///
20/// # Examples
21///
22/// ```rust
23/// use actori_service::fn_service;
24/// use actori_testing::TestServer;
25///
26/// #[actori_rt::main]
27/// async fn main() {
28///     let srv = TestServer::with(|| fn_service(
29///         |sock| async move {
30///             println!("New connection: {:?}", sock);
31///             Ok::<_, ()>(())
32///         }
33///     ));
34///
35///     println!("SOCKET: {:?}", srv.connect());
36/// }
37/// ```
38pub struct TestServer;
39
40/// Test server runstime
41pub struct TestServerRuntime {
42    addr: net::SocketAddr,
43    host: String,
44    port: u16,
45    system: System,
46}
47
48impl TestServer {
49    /// Start new server with server builder
50    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        // run server in separate thread
57        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    /// Start new test server with application factory
78    pub fn with<F: ServiceFactory<TcpStream>>(factory: F) -> TestServerRuntime {
79        let (tx, rx) = mpsc::channel();
80
81        // run server in separate thread
82        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    /// Get firat available unused local address
111    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    /// Test server host
123    pub fn host(&self) -> &str {
124        &self.host
125    }
126
127    /// Test server port
128    pub fn port(&self) -> u16 {
129        self.port
130    }
131
132    /// Get test server address
133    pub fn addr(&self) -> net::SocketAddr {
134        self.addr
135    }
136
137    /// Stop http server
138    fn stop(&mut self) {
139        self.system.stop();
140    }
141
142    /// Connect to server, return tokio TcpStream
143    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}