//! 真实计时器的完成、输入错误和取消析构,不用 sleep 阻塞执行线程。 use dever_runtime::task; #[path = "task/boundary.rs"] mod boundary; #[path = "task/combinations.rs"] mod combinations; #[path = "task/ordered.rs"] mod ordered; #[path = "task/scope.rs"] mod scope; #[path = "task/worker.rs"] mod worker; use std::{ cell::Cell, future::{Future, poll_fn}, pin::pin, task::Poll, time::{Duration, Instant}, }; #[test] fn timer_completes_and_rejects_invalid_duration() { task::execute(false, async { assert_eq!( task::sleep(-1).await.unwrap_err(), "sleep duration must be nonnegative" ); let start = Instant::now(); task::sleep(5).await.unwrap(); assert!(start.elapsed() >= Duration::from_millis(5)); task::sleep(0).await.unwrap(); }) .unwrap(); } #[test] fn dropping_pending_timer_releases_its_owned_scope_without_running_later_steps() { struct Released<'a>(&'a Cell); impl Drop for Released<'_> { fn drop(&mut self) { self.0.set(true); } } let released = Cell::new(false); let completed = Cell::new(false); task::execute(false, async { { let mut pending = pin!(async { let _owned = Released(&released); task::sleep(60_000).await.unwrap(); completed.set(true); }); poll_fn(|context| { assert!(pending.as_mut().poll(context).is_pending()); Poll::Ready(()) }) .await; } assert!(released.get()); assert!(!completed.get()); task::sleep(1).await.unwrap(); assert!(!completed.get()); }) .unwrap(); }