From b85ef38187000f0d65325696a4ef535e0c93f0d8 Mon Sep 17 00:00:00 2001 From: Eric Huss Date: Wed, 6 Sep 2023 19:30:45 -0700 Subject: [PATCH] Add test helpers for waiting for an operation with a timeout. --- crates/cargo-test-support/src/lib.rs | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/crates/cargo-test-support/src/lib.rs b/crates/cargo-test-support/src/lib.rs index ffaee9ea5..ec74ce0b2 100644 --- a/crates/cargo-test-support/src/lib.rs +++ b/crates/cargo-test-support/src/lib.rs @@ -13,6 +13,7 @@ use std::path::{Path, PathBuf}; use std::process::{Command, Output}; use std::str; use std::sync::OnceLock; +use std::thread::JoinHandle; use std::time::{self, Duration}; use anyhow::{bail, Result}; @@ -1500,3 +1501,20 @@ where fn retry_fails() { retry(2, || None::<()>); } + +/// Helper that waits for a thread to finish, up to `n` tenths of a second. +pub fn thread_wait_timeout(n: u32, thread: JoinHandle) -> T { + retry(n, || thread.is_finished().then_some(())); + thread.join().unwrap() +} + +/// Helper that runs some function, and waits up to `n` tenths of a second for +/// it to finish. +pub fn threaded_timeout(n: u32, f: F) -> R +where + F: FnOnce() -> R + Send + 'static, + R: Send + 'static, +{ + let thread = std::thread::spawn(|| f()); + thread_wait_timeout(n, thread) +}