TestServer would wait on spawn thread's join handle

This commit is contained in:
fakeshadow 2021-04-06 21:07:43 +08:00
parent ebd213d576
commit 58a860ceb1
1 changed files with 7 additions and 3 deletions

View File

@ -1,5 +1,5 @@
use std::sync::mpsc; use std::sync::mpsc;
use std::{net, thread}; use std::{io, net, thread};
use actix_rt::{net::TcpStream, System}; use actix_rt::{net::TcpStream, System};
@ -36,6 +36,7 @@ pub struct TestServerRuntime {
host: String, host: String,
port: u16, port: u16,
handle: ServerHandle, handle: ServerHandle,
join_handle: Option<thread::JoinHandle<io::Result<()>>>,
} }
impl TestServer { impl TestServer {
@ -47,7 +48,7 @@ impl TestServer {
let (tx, rx) = mpsc::channel(); let (tx, rx) = mpsc::channel();
// run server in separate thread // run server in separate thread
thread::spawn(move || { let join_handle = thread::spawn(move || {
System::new().block_on(async { System::new().block_on(async {
let server = factory(Server::build()).workers(1).disable_signals().run(); let server = factory(Server::build()).workers(1).disable_signals().run();
tx.send(server.handle()).unwrap(); tx.send(server.handle()).unwrap();
@ -62,6 +63,7 @@ impl TestServer {
host: "127.0.0.1".to_string(), host: "127.0.0.1".to_string(),
port: 0, port: 0,
handle, handle,
join_handle: Some(join_handle),
} }
} }
@ -70,7 +72,7 @@ impl TestServer {
let (tx, rx) = mpsc::channel(); let (tx, rx) = mpsc::channel();
// run server in separate thread // run server in separate thread
thread::spawn(move || { let join_handle = thread::spawn(move || {
let sys = System::new(); let sys = System::new();
let tcp = net::TcpListener::bind("127.0.0.1:0").unwrap(); let tcp = net::TcpListener::bind("127.0.0.1:0").unwrap();
let local_addr = tcp.local_addr().unwrap(); let local_addr = tcp.local_addr().unwrap();
@ -99,6 +101,7 @@ impl TestServer {
host, host,
port, port,
handle, handle,
join_handle: Some(join_handle),
} }
} }
@ -132,6 +135,7 @@ impl TestServerRuntime {
/// Stop http server /// Stop http server
fn stop(&mut self) { fn stop(&mut self) {
let _ = self.handle.stop(false); let _ = self.handle.stop(false);
self.join_handle.take().unwrap().join().unwrap().unwrap();
} }
/// Connect to server, return tokio TcpStream /// Connect to server, return tokio TcpStream