Skip to content

Commit ab333e3

Browse files
committed
cancellable-future: Add test checking delayed cancellation
1 parent 80d4032 commit ab333e3

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed

gio/src/cancellable_future.rs

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -141,11 +141,26 @@ impl Display for Cancelled {
141141

142142
#[cfg(test)]
143143
mod tests {
144+
use std::future::Future;
144145
use std::time::Duration;
145146

146147
use super::{Cancellable, CancellableFuture, Cancelled};
147148
use crate::{prelude::*, spawn_blocking};
148149

150+
async fn cancel_after_timeout(duration: Duration, cancellable: Cancellable) {
151+
glib::timeout_future_with_priority(glib::Priority::default(), duration).await;
152+
cancellable.cancel();
153+
}
154+
155+
async fn cancel_after_sleep_in_thread(duration: Duration, cancellable: Cancellable) {
156+
spawn_blocking(move || {
157+
std::thread::sleep(duration);
158+
cancellable.cancel();
159+
})
160+
.await
161+
.unwrap()
162+
}
163+
149164
#[test]
150165
fn cancellable_future_ok() {
151166
let ctx = glib::MainContext::new();
@@ -183,4 +198,40 @@ mod tests {
183198

184199
ctx.block_on(future).unwrap();
185200
}
201+
202+
#[test]
203+
fn cancellable_future_delayed_cancel_local() {
204+
let ctx = glib::MainContext::new();
205+
let c = Cancellable::new();
206+
207+
let (r1, r2) = ctx
208+
.block_on(ctx.spawn_local({
209+
futures_util::future::join(
210+
CancellableFuture::new(std::future::pending::<()>(), c.clone()),
211+
cancel_after_timeout(Duration::from_millis(300), c.clone()),
212+
)
213+
}))
214+
.expect("futures must be executed");
215+
216+
assert!(matches!(r1, Err(Cancelled)));
217+
assert!(matches!(r2, ()));
218+
}
219+
220+
#[test]
221+
fn cancellable_future_delayed_cancel_from_other_thread() {
222+
let ctx = glib::MainContext::new();
223+
let c = Cancellable::new();
224+
225+
let (r1, r2) = ctx
226+
.block_on(ctx.spawn_local({
227+
futures_util::future::join(
228+
CancellableFuture::new(std::future::pending::<()>(), c.clone()),
229+
cancel_after_sleep_in_thread(Duration::from_millis(300), c.clone()),
230+
)
231+
}))
232+
.expect("futures must be executed");
233+
234+
assert!(matches!(r1, Err(Cancelled)));
235+
assert!(matches!(r2, ()));
236+
}
186237
}

0 commit comments

Comments
 (0)