mirror of
https://github.com/tokio-rs/tokio.git
synced 2026-09-03 00:00:05 +02:00
time: make test-util paused time fully deterministic (#3492)
The time driver stores an Instant internally used as a "base" for future time calculations. Since this is generated as the Runtime is being constructed, it previously always happened before the user had a chance to pause time. The fractional-millisecond variations in the timing around the runtime construction and time pause cause tests running entirely in paused time to be very slightly deterministic, with the time driver advancing time by 1 millisecond more or less depending on how the sub-millisecond components of the `Instant`s involved compared. To avoid this, there is now a new option on `runtime::Builder` which will create a `Runtime` with time "instantly" paused. This, along with a small change to have the time driver use the provided clock as the source for its start time allow totally deterministic tests with paused time.
This commit is contained in:
@@ -1,6 +1,9 @@
|
||||
#![warn(rust_2018_idioms)]
|
||||
#![cfg(feature = "full")]
|
||||
|
||||
use rand::SeedableRng;
|
||||
use rand::{rngs::StdRng, Rng};
|
||||
use tokio::time::{self, Duration, Instant};
|
||||
use tokio_test::assert_err;
|
||||
|
||||
#[tokio::test]
|
||||
@@ -31,3 +34,26 @@ async fn pause_time_in_spawn_threads() {
|
||||
|
||||
assert_err!(t.await);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn paused_time_is_deterministic() {
|
||||
let run_1 = paused_time_stress_run();
|
||||
let run_2 = paused_time_stress_run();
|
||||
|
||||
assert_eq!(run_1, run_2);
|
||||
}
|
||||
|
||||
#[tokio::main(flavor = "current_thread", start_paused = true)]
|
||||
async fn paused_time_stress_run() -> Vec<Duration> {
|
||||
let mut rng = StdRng::seed_from_u64(1);
|
||||
|
||||
let mut times = vec![];
|
||||
let start = Instant::now();
|
||||
for _ in 0..10_000 {
|
||||
let sleep = rng.gen_range(Duration::from_secs(0)..Duration::from_secs(1));
|
||||
time::sleep(sleep).await;
|
||||
times.push(start.elapsed());
|
||||
}
|
||||
|
||||
times
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user