rustasync / runtime

Empowering everyone to build asynchronous software
https://docs.rs/runtime
Apache License 2.0
862 stars 28 forks source link

Deterministic delay testing #108

Closed kstrafe closed 4 years ago

kstrafe commented 5 years ago

Runtime doesn't appear to have a special case for test scheduling. What is wanted here is the ability to run a Delay...await on the top level and let the system advance by some time in a deterministic manner - That's to say, mocking out the clock.

    #[runtime::test(runtime_tokio::Tokio)]
    async fn test() {
        let value = Arc::new(Mutex::new(1i32));
        let v2 = value.clone();

        runtime::spawn(async move {
            Delay::new(Duration::from_millis(1000)).await;
            println!["Hi!"];
            *v2.lock().unwrap() += 1;
        });

        // Simulate some work using non-awaits
        // Should not affect the scheduler in runtime::test
        std::thread::sleep(Duration::from_millis(4000));

        // This should be deterministic
        Delay::new(Duration::from_millis(999)).await;
        assert_eq![1, *value.lock().unwrap()];
        Delay::new(Duration::from_millis(2)).await;
        assert_eq![2, *value.lock().unwrap()];
    }