Skip to content

Instantly share code, notes, and snippets.

@la10736
Created March 26, 2022 17:06
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 la10736/6a3652c12d065d0201e36b3fc97f1caf to your computer and use it in GitHub Desktop.
Save la10736/6a3652c12d065d0201e36b3fc97f1caf to your computer and use it in GitHub Desktop.
POC timeout tests async agnostic
use std::time::Duration;
pub async fn delayed_sum(a: u32, b: u32, delay: Duration) -> u32 {
async_std::task::sleep(delay).await;
a + b
}
pub fn delayed_threaded_sum(a: u32, b: u32, delay: Duration) -> u32 {
std::thread::sleep(delay);
a + b
}
#[cfg(test)]
mod tests {
use super::*;
mod async_version {
use super::*;
use futures_timer::Delay;
use std::time::Duration;
use futures::{
future::FutureExt, // for `.fuse()`
select,
};
async fn test(delay: Duration) {
let result = delayed_sum(2, 2, delay).await;
assert_eq!(result, 4);
}
mod use_async_std_runtime {
use super::*;
#[async_std::test]
#[should_panic]
async fn should_fail() {
select! {
() = async {
Delay::new(Duration::from_millis(40)).await;
}.fuse() => panic!("Timeout {:?} expired", Duration::from_millis(40)),
out = test(Duration::from_millis(50)).fuse() => out,
}
}
#[async_std::test]
async fn should_pass() {
select! {
() = async {
Delay::new(Duration::from_millis(60)).await;
}.fuse() => panic!("Timeout {:?} expired", Duration::from_millis(60)),
out = test(Duration::from_millis(50)).fuse() => out,
}
}
}
mod use_tokio_runtime {
use super::*;
#[tokio::test]
#[should_panic]
async fn should_fail() {
select! {
() = async {
Delay::new(Duration::from_millis(40)).await;
}.fuse() => panic!("Timeout {:?} expired", Duration::from_millis(40)),
out = test(Duration::from_millis(50)).fuse() => out,
}
}
#[tokio::test]
async fn should_pass() {
select! {
() = async {
Delay::new(Duration::from_millis(60)).await;
}.fuse() => panic!("Timeout {:?} expired", Duration::from_millis(60)),
out = test(Duration::from_millis(50)).fuse() => out,
}
}
}
}
mod thread_version {
use std::sync::mpsc;
use super::*;
fn test(delay: Duration) {
let result = delayed_threaded_sum(2, 2, delay);
assert_eq!(result, 4);
}
pub fn execute_with_timeout<T: 'static + Send, F: Fn() -> T + Send + 'static>(
code: F,
timeout: Duration,
) -> Option<T> {
let (sender, receiver) = mpsc::channel();
std::thread::spawn(move || sender.send(code()));
receiver.recv_timeout(timeout).ok()
}
#[test]
fn should_pass() {
execute_with_timeout(
|| test(Duration::from_millis(50)),
Duration::from_millis(60),
)
.unwrap_or_else(|| panic!("Timeout {:?} Expired", Duration::from_millis(60)))
}
#[test]
#[should_panic]
fn should_fail() {
execute_with_timeout(
|| test(Duration::from_millis(50)),
Duration::from_millis(40),
)
.unwrap_or_else(|| panic!("Timeout {:?} Expired", Duration::from_millis(40)))
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment