use RAII guard in tests

This commit is contained in:
Johann150 2021-02-25 17:30:12 +01:00
parent 1059f8b94a
commit 8b4692b08b
No known key found for this signature in database
GPG key ID: 9EE6577A2A06F8F1

View file

@ -16,7 +16,13 @@ fn addr(port: u16) -> SocketAddr {
.unwrap() .unwrap()
} }
fn get(args: &[&str], addr: SocketAddr, url: &str) -> Result<Page, anyhow::Error> { struct Server {
server: std::process::Child,
buf: u8,
}
impl Server {
pub fn new(args: &[&str]) -> Self {
// start the server // start the server
let mut server = Command::new(BINARY_PATH) let mut server = Command::new(BINARY_PATH)
.stderr(Stdio::piped()) .stderr(Stdio::piped())
@ -35,20 +41,24 @@ fn get(args: &[&str], addr: SocketAddr, url: &str) -> Result<Page, anyhow::Error
.read_exact(&mut buffer) .read_exact(&mut buffer)
.unwrap(); .unwrap();
// actually perform the request Self {
let page = tokio::runtime::Runtime::new() server,
.unwrap() buf: buffer[0],
.block_on(async { Page::fetch_from(&Url::parse(url).unwrap(), addr, None).await }); }
}
}
impl Drop for Server {
fn drop(&mut self) {
// try to stop the server again // try to stop the server again
match server.try_wait() { match self.server.try_wait() {
Err(e) => panic!("cannot access orchestrated program: {:?}", e), Err(e) => panic!("cannot access orchestrated program: {:?}", e),
// everything fine, still running as expected, kill it now // everything fine, still running as expected, kill it now
Ok(None) => server.kill().unwrap(), Ok(None) => self.server.kill().unwrap(),
Ok(Some(_)) => { Ok(Some(_)) => {
// forward stderr so we have a chance to understand the problem // forward stderr so we have a chance to understand the problem
let buffer = std::iter::once(Ok(buffer[0])) let buffer = std::iter::once(Ok(self.buf))
.chain(server.stderr.take().unwrap().bytes()) .chain(self.server.stderr.take().unwrap().bytes())
.collect::<Result<Vec<u8>, _>>() .collect::<Result<Vec<u8>, _>>()
.unwrap(); .unwrap();
@ -57,6 +67,16 @@ fn get(args: &[&str], addr: SocketAddr, url: &str) -> Result<Page, anyhow::Error
panic!("program had crashed"); panic!("program had crashed");
} }
} }
}
}
fn get(args: &[&str], addr: SocketAddr, url: &str) -> Result<Page, anyhow::Error> {
let _server = Server::new(args);
// actually perform the request
let page = tokio::runtime::Runtime::new()
.unwrap()
.block_on(async { Page::fetch_from(&Url::parse(url).unwrap(), addr, None).await });
page page
} }