Crates.io | tokitsuge |
lib.rs | tokitsuge |
version | 0.1.0 |
source | src |
created_at | 2023-08-17 08:20:08.610474 |
updated_at | 2023-08-17 08:20:08.610474 |
description | A unit test friendly utility that provides the function to get the current time. |
homepage | https://gitlab.com/faultier/tokitsuge-rs |
repository | https://gitlab.com/faultier/tokitsuge-rs |
max_upload_size | |
id | 946795 |
size | 31,059 |
Tokitsuge is a unit test friendly utility that provides the function to get the current time.
Just replace SystemTime::now
with Clock::now
.
use tokitsuge::Clock;
fn some_time_depended_function() {
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.
[dependencies]
tokitsuge = "0.1.0"
[dev-dependencies]
tokitsuge = { version = "0.1.0", features = ["freeze"] }
use tokitsuge::Clock;
fn some_time_depended_function() {
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);
}
}
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.
Licensed under either of Apache License, Version 2.0 or MIT license at your option.