Created
February 17, 2023 02:00
-
-
Save matthewjberger/2f5e2ea8583cae68cb72fc7dac0cf5c1 to your computer and use it in GitHub Desktop.
Shepmaster's rust test timeout solution
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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