qubit-clock 0.2.1

Thread-safe clock abstractions for Rust: monotonic clocks, mock testing, high-precision time meters, and timezone support
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
/*******************************************************************************
 *
 *    Copyright (c) 2025 - 2026.
 *    Haixing Hu, Qubit Co. Ltd.
 *
 *    All rights reserved.
 *
 ******************************************************************************/
//! Tests for MockClock.

use chrono::{DateTime, Duration, Utc};
use qubit_clock::{Clock, ControllableClock, MockClock};
use std::thread;

const CLOCK_DRIFT_TOLERANCE_MS: i64 = 1_000;

/// Asserts that a mock clock reading is close to the expected logical time.
fn assert_close_to_expected_time(actual: DateTime<Utc>, expected: DateTime<Utc>) {
    let diff_ms = (actual - expected).num_milliseconds();
    assert!(
        (0..CLOCK_DRIFT_TOLERANCE_MS).contains(&diff_ms),
        "time should be within {}ms after expected time, diff_ms: {}",
        CLOCK_DRIFT_TOLERANCE_MS,
        diff_ms
    );
}

#[test]
fn test_mock_clock_new() {
    let clock = MockClock::new();
    let millis = clock.millis();
    assert!(millis > 0, "MockClock should return positive milliseconds");
}

#[test]
fn test_mock_clock_default() {
    let clock = MockClock::default();
    let millis = clock.millis();
    assert!(millis > 0, "Default MockClock should work");
}

#[test]
fn test_mock_clock_set_time() {
    let clock = MockClock::new();

    let fixed_time = DateTime::parse_from_rfc3339("2024-01-01T00:00:00Z")
        .unwrap()
        .with_timezone(&Utc);

    clock.set_time(fixed_time);

    let current = clock.time();
    assert_eq!(current, fixed_time);
}

#[test]
fn test_mock_clock_set_time_multiple() {
    let clock = MockClock::new();

    let time1 = DateTime::parse_from_rfc3339("2024-01-01T00:00:00Z")
        .unwrap()
        .with_timezone(&Utc);
    clock.set_time(time1);
    assert_eq!(clock.time(), time1);

    let time2 = DateTime::parse_from_rfc3339("2024-06-15T12:30:45Z")
        .unwrap()
        .with_timezone(&Utc);
    clock.set_time(time2);
    assert_eq!(clock.time(), time2);
}

#[test]
fn test_mock_clock_add_duration() {
    let clock = MockClock::new();
    let initial = clock.time();

    clock.add_duration(Duration::hours(1));

    let after = clock.time();
    assert_eq!(after - initial, Duration::hours(1));
}

#[test]
fn test_mock_clock_add_millis_once() {
    let clock = MockClock::new();
    let before = clock.millis();

    clock.add_millis(1000, false);

    let after = clock.millis();
    assert_eq!(after - before, 1000);

    // Should not add again
    let after2 = clock.millis();
    let diff = (after2 - after).abs();
    assert!(diff < 10, "Should not add again");
}

#[test]
fn test_mock_clock_advance_millis() {
    let clock = MockClock::new();
    let before = clock.millis();

    clock.advance_millis(1500);

    let after = clock.millis();
    assert_eq!(after - before, 1500);
}

#[test]
fn test_mock_clock_add_millis_every_time() {
    let clock = MockClock::new();

    clock.add_millis(100, true);

    let t1 = clock.millis();
    let t2 = clock.millis();
    let t3 = clock.millis();

    assert_eq!(t2 - t1, 100);
    assert_eq!(t3 - t2, 100);
}

#[test]
fn test_mock_clock_set_and_clear_auto_advance() {
    let clock = MockClock::new();
    clock.set_auto_advance_millis(100);

    let t1 = clock.millis();
    let t2 = clock.millis();
    assert_eq!(t2 - t1, 100);

    clock.clear_auto_advance();
    let t3 = clock.millis();
    let t4 = clock.millis();
    assert!((t4 - t3).abs() < 10);
}

#[test]
fn test_mock_clock_add_millis_negative() {
    let clock = MockClock::new();
    let before = clock.millis();

    clock.add_millis(-1000, false);

    let after = clock.millis();
    assert_eq!(after - before, -1000);
}

#[test]
fn test_mock_clock_advance_millis_saturates_positive_overflow() {
    let clock = MockClock::new();

    clock.advance_millis(i64::MAX);
    clock.advance_millis(1);

    assert_eq!(clock.millis(), i64::MAX);
}

#[test]
fn test_mock_clock_advance_millis_saturates_negative_overflow() {
    let clock = MockClock::new();
    clock.set_time(DateTime::<Utc>::UNIX_EPOCH);

    clock.advance_millis(i64::MIN);
    clock.advance_millis(-1);

    let millis = clock.millis();
    assert!(
        millis <= i64::MIN.saturating_add(1_000),
        "negative overflow should stay near i64::MIN, got: {}",
        millis
    );
}

#[test]
fn test_mock_clock_auto_advance_saturates_positive_overflow() {
    let clock = MockClock::new();
    clock.set_time(DateTime::<Utc>::UNIX_EPOCH);
    clock.advance_millis(i64::MAX);
    clock.set_auto_advance_millis(1);

    assert_eq!(clock.millis(), i64::MAX);
    assert_eq!(clock.millis(), i64::MAX);
}

#[test]
fn test_mock_clock_reset() {
    let clock = MockClock::new();
    let initial = clock.time();

    clock.add_duration(Duration::hours(5));
    assert_ne!(clock.time(), initial);

    clock.reset();

    let after_reset = clock.time();
    let diff = (after_reset - initial).num_milliseconds().abs();
    assert!(
        diff < 100,
        "After reset, time should be close to initial time"
    );
}

#[test]
fn test_mock_clock_reset_after_set_time() {
    let clock = MockClock::new();
    let initial = clock.time();

    let fixed_time = DateTime::parse_from_rfc3339("2024-01-01T00:00:00Z")
        .unwrap()
        .with_timezone(&Utc);
    clock.set_time(fixed_time);

    clock.reset();

    let after_reset = clock.time();
    let diff = (after_reset - initial).num_milliseconds().abs();
    assert!(
        diff < 100,
        "After reset, time should be close to initial time"
    );
}

#[test]
fn test_mock_clock_reset_clears_add_every_time() {
    let clock = MockClock::new();

    clock.add_millis(100, true);
    let t1 = clock.millis();
    let t2 = clock.millis();
    assert_eq!(t2 - t1, 100);

    clock.reset();

    let t3 = clock.millis();
    let t4 = clock.millis();
    let diff = (t4 - t3).abs();
    assert!(diff < 10, "After reset, should not add every time");
}

#[test]
fn test_mock_clock_complex_scenario() {
    let clock = MockClock::new();

    // Set to a known time
    let start_time = DateTime::parse_from_rfc3339("2024-01-01T00:00:00Z")
        .unwrap()
        .with_timezone(&Utc);
    clock.set_time(start_time);

    // Advance by 1 day
    clock.add_duration(Duration::days(1));
    let after_day = clock.time();
    assert_close_to_expected_time(after_day, start_time + Duration::days(1));

    // Advance by 12 hours
    clock.add_duration(Duration::hours(12));
    let after_hours = clock.time();
    assert_close_to_expected_time(
        after_hours,
        start_time + Duration::days(1) + Duration::hours(12),
    );

    // Go back 6 hours
    clock.add_duration(Duration::hours(-6));
    let after_back = clock.time();
    assert_close_to_expected_time(
        after_back,
        start_time + Duration::days(1) + Duration::hours(6),
    );
}

#[test]
fn test_mock_clock_clone() {
    let clock1 = MockClock::new();
    let fixed_time = DateTime::parse_from_rfc3339("2024-01-01T00:00:00Z")
        .unwrap()
        .with_timezone(&Utc);
    clock1.set_time(fixed_time);

    let clock2 = clock1.clone();

    // Both clocks should share the same internal state
    assert_eq!(clock1.time(), clock2.time());

    // Modifying one should affect the other
    clock1.add_duration(Duration::hours(1));
    assert_eq!(clock1.time(), clock2.time());
}

#[test]
fn test_mock_clock_debug() {
    let clock = MockClock::new();
    let debug_str = format!("{:?}", clock);
    assert!(
        debug_str.contains("MockClock"),
        "Debug output should contain 'MockClock'"
    );
}

#[test]
fn test_mock_clock_send_sync() {
    fn assert_send<T: Send>() {}
    fn assert_sync<T: Sync>() {}

    assert_send::<MockClock>();
    assert_sync::<MockClock>();
}

#[test]
fn test_mock_clock_in_thread() {
    use std::sync::Arc;

    let clock = Arc::new(MockClock::new());
    let fixed_time = DateTime::parse_from_rfc3339("2024-01-01T00:00:00Z")
        .unwrap()
        .with_timezone(&Utc);
    clock.set_time(fixed_time);

    let clock_clone = clock.clone();

    let handle = thread::spawn(move || {
        clock_clone.add_duration(Duration::hours(1));
        clock_clone.time()
    });

    let result = handle.join().unwrap();
    assert_close_to_expected_time(result, fixed_time + Duration::hours(1));

    // Main thread should see the change
    assert_close_to_expected_time(clock.time(), fixed_time + Duration::hours(1));
}

#[test]
fn test_mock_clock_multiple_threads() {
    use std::sync::Arc;

    let clock = Arc::new(MockClock::new());
    let fixed_time = DateTime::parse_from_rfc3339("2024-01-01T00:00:00Z")
        .unwrap()
        .with_timezone(&Utc);
    clock.set_time(fixed_time);

    let mut handles = vec![];

    for i in 0..10 {
        let clock_clone = clock.clone();
        let handle = thread::spawn(move || {
            clock_clone.add_duration(Duration::hours(i));
        });
        handles.push(handle);
    }

    for handle in handles {
        handle.join().unwrap();
    }

    // All additions should have accumulated
    let final_time = clock.time();
    let expected_hours = (0..10).sum::<i64>();
    let expected_base = fixed_time + Duration::hours(expected_hours);
    let diff_ms = (final_time - expected_base).num_milliseconds();
    assert!(
        (0..1000).contains(&diff_ms),
        "Final time should be within 1s after expected time, diff_ms: {}",
        diff_ms
    );
}

#[test]
fn test_mock_clock_progresses_after_set_time() {
    let clock = MockClock::new();
    let fixed_time = DateTime::parse_from_rfc3339("2024-01-01T00:00:00Z")
        .unwrap()
        .with_timezone(&Utc);
    clock.set_time(fixed_time);

    // Sleep and verify time has progressed naturally
    thread::sleep(std::time::Duration::from_millis(50));

    let current = clock.time();
    let diff = (current - fixed_time).num_milliseconds();
    assert!(
        diff >= 50,
        "Time should progress naturally after set_time, diff: {}",
        diff
    );
    assert!(
        diff < 150,
        "Time should not progress too much, diff: {}",
        diff
    );
}

#[test]
fn test_mock_clock_progresses_naturally() {
    let clock = MockClock::new();
    let start = clock.millis();

    // Without any manipulation, time should progress naturally
    // (based on the internal monotonic clock)
    thread::sleep(std::time::Duration::from_millis(50));

    let elapsed = clock.millis() - start;
    assert!(
        elapsed >= 50,
        "Time should progress naturally, elapsed: {}",
        elapsed
    );
}