Fake Clock for Deterministic Tests

Inject a manually advanced clock into token expiry logic so tests never sleep and boundary conditions stay reproducible.

RustResilience

Code

rustsnippet
51 lines
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::Arc;
use std::time::Duration;

#[derive(Clone)]
struct FakeClock {
    millis: Arc<AtomicU64>,
}

impl FakeClock {
    fn new() -> Self {
        Self {
            millis: Arc::new(AtomicU64::new(0)),
        }
    }

    fn now(&self) -> Duration {
        Duration::from_millis(self.millis.load(Ordering::SeqCst))
    }

    fn advance(&self, delta: Duration) {
        self.millis
            .fetch_add(delta.as_millis() as u64, Ordering::SeqCst);
    }
}

struct Token {
    expires_at: Duration,
}

impl Token {
    fn issue(clock: &FakeClock, ttl: Duration) -> Self {
        Self {
            expires_at: clock.now() + ttl,
        }
    }

    fn expired(&self, clock: &FakeClock) -> bool {
        clock.now() >= self.expires_at
    }
}

fn main() {
    let clock = FakeClock::new();
    let token = Token::issue(&clock, Duration::from_secs(60));
    clock.advance(Duration::from_secs(59));
    println!("expired at 59s: {}", token.expired(&clock));
    clock.advance(Duration::from_secs(1));
    println!("expired at 60s: {}", token.expired(&clock));
}

Inside the snippet

Fake Clock for Deterministic Tests keeps everything in the functions new, now, advance and issue.

Putting it to use

The primary signature is fn new() -> Self

Running the file prints labeled results such as expired at 59s:, expired at 60s: — each operation’s effect is visible in the output.

main is the driver: it invokes new, issue, advance and expired before returning.

Core lines

fn issue(clock: &FakeClock, ttl: Duration) -> Self {
Self {
expires_at: clock.now() + ttl,
}
}
fn expired(&self, clock: &FakeClock) -> bool {
clock.now() >= self.expires_at
}
fn advance(&self, delta: Duration) {
self.millis
.fetch_add(delta.as_millis() as u64, Ordering::SeqCst);
}

Interactive Tools for This Topic

FAQ

What does Fake Clock for Deterministic Tests print when run?
Running the file directly is enough — expect labeled output lines such as `expired at 59s:`, `expired at 60s:`.