amont_runtime/clock.rs
1//! The one test-only knob on amont's own waits.
2//!
3//! Some behaviour exists only after a wait: a quiet run names its log once a
4//! check has run for five seconds, `amont land` re-reads the remote after a
5//! pause, a tree gate gets `amont.treeLintSlack` after the commit's checks.
6//! A test of that behaviour has to outlast the wait, and at full length those
7//! tests were most of the integration suite's time.
8//!
9//! In a `test-hooks` build (every `cargo test` build of the binary, and no
10//! `cargo build`) `AMONT_TEST_CLOCK_SCALE`, a factor in (0, 1], shortens
11//! each wait that goes through [`scaled`]; `.cargo/config.toml` pins it for
12//! the tests, and the fixtures scale their own sleeps by the same factor. In
13//! a shipped binary [`scaled`] is the identity and reads nothing. The budgets
14//! that kill a check (`amont.timeout`, `amont.idleTimeout`) are not scaled:
15//! `tests/timing.rs` proves them on the real clock.
16
17use std::time::Duration;
18
19/// `d`, shortened by the test clock scale where one applies.
20pub fn scaled(d: Duration) -> Duration {
21 #[cfg(feature = "test-hooks")]
22 if let Some(f) = factor() {
23 return d.mul_f64(f);
24 }
25 d
26}
27
28#[cfg(feature = "test-hooks")]
29fn factor() -> Option<f64> {
30 static FACTOR: std::sync::OnceLock<Option<f64>> = std::sync::OnceLock::new();
31 *FACTOR.get_or_init(|| {
32 std::env::var("AMONT_TEST_CLOCK_SCALE")
33 .ok()
34 .and_then(|v| v.parse::<f64>().ok())
35 .filter(|f| *f > 0.0 && *f <= 1.0)
36 })
37}
38
39#[cfg(test)]
40mod tests {
41 use super::*;
42
43 /// The pin in `.cargo/config.toml` reaches the tests, and halves nothing
44 /// it should not: a factor, never an offset.
45 #[test]
46 fn the_scale_is_a_factor() {
47 let d = Duration::from_secs(10);
48 #[cfg(feature = "test-hooks")]
49 assert!(scaled(d) <= d);
50 #[cfg(not(feature = "test-hooks"))]
51 assert_eq!(scaled(d), d);
52 assert_eq!(scaled(Duration::ZERO), Duration::ZERO);
53 }
54}