Skip to content

Commit

Permalink
Add cancel_on_shutdown test
Browse files Browse the repository at this point in the history
  • Loading branch information
Finomnis committed Oct 18, 2023
1 parent ecc1695 commit d654c2f
Show file tree
Hide file tree
Showing 2 changed files with 77 additions and 37 deletions.
77 changes: 77 additions & 0 deletions tests/cancel_on_shutdown.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
use tokio::time::{sleep, Duration};
use tokio_graceful_shutdown::{
errors::CancelledByShutdown, FutureExt, SubsystemBuilder, SubsystemHandle, Toplevel,
};
use tracing_test::traced_test;

use std::error::Error;

/// Wrapper function to simplify lambdas
type BoxedError = Box<dyn Error + Sync + Send>;
type BoxedResult = Result<(), BoxedError>;

#[tokio::test]
#[traced_test]
async fn cancel_on_shutdown_propagates_result() {
let subsystem1 = |subsys: SubsystemHandle| async move {
let compute_value = async {
sleep(Duration::from_millis(10)).await;
42
};

let value = compute_value.cancel_on_shutdown(&subsys).await;

assert_eq!(value.ok(), Some(42));

BoxedResult::Ok(())
};

let subsystem2 = |subsys: SubsystemHandle| async move {
async fn compute_value() -> i32 {
sleep(Duration::from_millis(10)).await;
42
}

let value = compute_value().cancel_on_shutdown(&subsys).await;

assert_eq!(value.ok(), Some(42));

BoxedResult::Ok(())
};

let result = Toplevel::<BoxedError>::new(move |s| async move {
s.start(SubsystemBuilder::new("subsys1", subsystem1));
s.start(SubsystemBuilder::new("subsys2", subsystem2));
})
.handle_shutdown_requests(Duration::from_millis(200))
.await;

assert!(result.is_ok());
}

#[tokio::test]
#[traced_test]
async fn cancel_on_shutdown_cancels_on_shutdown() {
let subsystem = |subsys: SubsystemHandle| async move {
async fn compute_value(subsys: &SubsystemHandle) -> i32 {
sleep(Duration::from_millis(100)).await;
subsys.request_shutdown();
sleep(Duration::from_millis(100)).await;
42
}

let value = compute_value(&subsys).cancel_on_shutdown(&subsys).await;

assert!(matches!(value, Err(CancelledByShutdown)));

BoxedResult::Ok(())
};

let result = Toplevel::<BoxedError>::new(move |s| async move {
s.start(SubsystemBuilder::new("subsys", subsystem));
})
.handle_shutdown_requests(Duration::from_millis(200))
.await;

assert!(result.is_ok());
}
37 changes: 0 additions & 37 deletions tests/rewrite_tests.rs

This file was deleted.

0 comments on commit d654c2f

Please sign in to comment.