Skip to content

Instantly share code, notes, and snippets.

@matthewjberger
Created February 17, 2023 02:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save matthewjberger/2f5e2ea8583cae68cb72fc7dac0cf5c1 to your computer and use it in GitHub Desktop.
Save matthewjberger/2f5e2ea8583cae68cb72fc7dac0cf5c1 to your computer and use it in GitHub Desktop.
Shepmaster's rust test timeout solution
use std::{sync::mpsc, thread, time::Duration};
#[test]
fn oops() {
panic_after(Duration::from_millis(100), || {
thread::sleep(Duration::from_millis(200));
})
}
fn panic_after<T, F>(d: Duration, f: F) -> T
where
T: Send + 'static,
F: FnOnce() -> T,
F: Send + 'static,
{
let (done_tx, done_rx) = mpsc::channel();
let handle = thread::spawn(move || {
let val = f();
done_tx.send(()).expect("Unable to send completion signal");
val
});
match done_rx.recv_timeout(d) {
Ok(_) => handle.join().expect("Thread panicked"),
Err(_) => panic!("Thread took too long"),
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment