Crate tokitsuge

Crate tokitsuge 

Source
Expand description

§Tokitsuge

A unit test friendly utility that provides the function to get current time.

§Feature flags

  • freeze provides functions to freeze the current time for unit testing.

§Usage

Just replace SystemTime::now with Clock::now.

use std::time::SystemTime;
use tokitsuge::Clock;

fn some_time_depended_function() -> SystemTime {
    Clock::now()
}

This code itself just calls SystemTime::now to get the system time (so there is no additional overhead in production). Running the tests with the freeze feature enabled in Cargo.toml will change the behavior.

use std::time::SystemTime;
use tokitsuge::Clock;

fn some_time_depended_function() -> SystemTime {
    Clock::now()
}

#[cfg(test)]
mod tests {
    use std::thread::sleep;
    use std::time::Duration;
    use super::*;

    #[test]
    fn test_some_time_depended_function() {
        // Real system time.
        let t1 = some_time_depended_function();

        {
            let frozen_clock = Clock::freeze();

            // Fixed time.
            let ft1 = some_time_depended_function();
            assert_eq!(ft1, frozen_clock.fixed_time());

            // This function will always return the same time until `frozen_clock` is dropped.
            sleep(Duration::from_millis(1));
            let ft2 = some_time_depended_function();
            assert_eq!(ft1, ft2);

            // Instead of sleep, FrozenClock#advance and FrozenClock#unwind can be used.
            frozen_clock.advance(Duration::from_millis(1));
            let ft3 = some_time_depended_function();
            assert_eq!(ft2 < ft3);
        }

        // Time flows again.
        let t2 = some_time_depended_function();
        assert!(t1 < t2);
    }
}

§Note

This utility IS NOT suitable for testing multithreaded operations.

The test code and the code under test must run in the same thread, as this utility uses thread-local variables to prevent freeze effects from spreading to other tests.

§License

Licensed under either of Apache License, Version 2.0 or MIT license at your option.

Structs§

Clock
Utility to get the current time.