prism3_clock/mock.rs
1/*******************************************************************************
2 *
3 * Copyright (c) 2025.
4 * 3-Prism Co. Ltd.
5 *
6 * All rights reserved.
7 *
8 ******************************************************************************/
9//! Mock clock implementation for testing.
10//!
11//! This module provides [`MockClock`], a controllable clock implementation
12//! designed for testing scenarios where precise control over time is needed.
13//!
14//! # Author
15//!
16//! Haixing Hu
17
18use crate::{Clock, ControllableClock, MonotonicClock};
19use chrono::{DateTime, Duration, Utc};
20use parking_lot::Mutex;
21use std::sync::Arc;
22
23/// A controllable clock implementation for testing.
24///
25/// `MockClock` allows you to manually control the passage of time, making it
26/// ideal for testing time-dependent code. It uses [`MonotonicClock`] as its
27/// internal time base to ensure stability during tests.
28///
29/// # Features
30///
31/// - Set the clock to a specific time
32/// - Advance the clock by a duration
33/// - Automatically advance time on each call
34/// - Reset to initial state
35///
36/// # Thread Safety
37///
38/// This type is thread-safe, using `Arc<Mutex<>>` internally to protect its
39/// mutable state.
40///
41/// # Examples
42///
43/// ```
44/// use prism3_clock::{Clock, ControllableClock, MockClock};
45/// use chrono::{DateTime, Duration, Utc};
46///
47/// let clock = MockClock::new();
48///
49/// // Set to a specific time
50/// let fixed_time = DateTime::parse_from_rfc3339(
51/// "2024-01-01T00:00:00Z"
52/// ).unwrap().with_timezone(&Utc);
53/// clock.set_time(fixed_time);
54/// assert_eq!(clock.time(), fixed_time);
55///
56/// // Advance by 1 hour
57/// clock.add_duration(Duration::hours(1));
58/// assert_eq!(clock.time(), fixed_time + Duration::hours(1));
59///
60/// // Reset to initial state
61/// clock.reset();
62/// ```
63///
64/// # Author
65///
66/// Haixing Hu
67#[derive(Debug, Clone)]
68pub struct MockClock {
69 inner: Arc<Mutex<MockClockInner>>,
70}
71
72#[derive(Debug)]
73struct MockClockInner {
74 /// The monotonic clock used as the time base.
75 monotonic_clock: MonotonicClock,
76 /// The time when this clock was created (milliseconds since epoch).
77 create_time: i64,
78 /// The epoch time to use as the base (milliseconds since epoch).
79 epoch: i64,
80 /// Additional milliseconds to add to the current time.
81 millis_to_add: i64,
82 /// Milliseconds to add on each call to `millis()`.
83 millis_to_add_each_time: i64,
84 /// Whether to automatically add `millis_to_add_each_time` on each call.
85 add_every_time: bool,
86}
87
88impl MockClock {
89 /// Creates a new `MockClock`.
90 ///
91 /// The clock is initialized with the current system time and uses a
92 /// [`MonotonicClock`] as its internal time base.
93 ///
94 /// # Returns
95 ///
96 /// A new `MockClock` instance.
97 ///
98 /// # Examples
99 ///
100 /// ```
101 /// use prism3_clock::MockClock;
102 ///
103 /// let clock = MockClock::new();
104 /// ```
105 ///
106 pub fn new() -> Self {
107 let monotonic_clock = MonotonicClock::new();
108 let create_time = monotonic_clock.millis();
109 MockClock {
110 inner: Arc::new(Mutex::new(MockClockInner {
111 monotonic_clock,
112 create_time,
113 epoch: create_time,
114 millis_to_add: 0,
115 millis_to_add_each_time: 0,
116 add_every_time: false,
117 })),
118 }
119 }
120
121 /// Adds a fixed amount of milliseconds to the clock.
122 ///
123 /// # Arguments
124 ///
125 /// * `millis` - The number of milliseconds to add.
126 /// * `add_every_time` - If `true`, the specified milliseconds will be
127 /// added on every call to [`millis()`](Clock::millis). If `false`, the
128 /// milliseconds are added only once.
129 ///
130 /// # Examples
131 ///
132 /// ```
133 /// use prism3_clock::{Clock, MockClock};
134 ///
135 /// let clock = MockClock::new();
136 /// let before = clock.millis();
137 ///
138 /// // Add 1000ms once
139 /// clock.add_millis(1000, false);
140 /// assert_eq!(clock.millis(), before + 1000);
141 ///
142 /// // Add 100ms on every call
143 /// clock.add_millis(100, true);
144 /// let t1 = clock.millis();
145 /// let t2 = clock.millis();
146 /// assert_eq!(t2 - t1, 100);
147 /// ```
148 ///
149 pub fn add_millis(&self, millis: i64, add_every_time: bool) {
150 let mut inner = self.inner.lock();
151 if add_every_time {
152 inner.millis_to_add_each_time = millis;
153 inner.add_every_time = true;
154 } else {
155 inner.millis_to_add += millis;
156 }
157 }
158}
159
160impl Default for MockClock {
161 fn default() -> Self {
162 Self::new()
163 }
164}
165
166impl Clock for MockClock {
167 fn millis(&self) -> i64 {
168 let mut inner = self.inner.lock();
169 let elapsed = inner.monotonic_clock.millis() - inner.create_time;
170 let result = inner.epoch + elapsed + inner.millis_to_add;
171
172 if inner.add_every_time {
173 inner.millis_to_add += inner.millis_to_add_each_time;
174 }
175
176 result
177 }
178}
179
180impl ControllableClock for MockClock {
181 fn set_time(&self, instant: DateTime<Utc>) {
182 let mut inner = self.inner.lock();
183 let current_monotonic = inner.monotonic_clock.millis();
184 let elapsed = current_monotonic - inner.create_time;
185 inner.epoch = instant.timestamp_millis() - elapsed;
186 inner.millis_to_add = 0;
187 inner.millis_to_add_each_time = 0;
188 inner.add_every_time = false;
189 }
190
191 fn add_duration(&self, duration: Duration) {
192 let millis = duration.num_milliseconds();
193 self.add_millis(millis, false);
194 }
195
196 fn reset(&self) {
197 let mut inner = self.inner.lock();
198 inner.epoch = inner.create_time;
199 inner.millis_to_add = 0;
200 inner.millis_to_add_each_time = 0;
201 inner.add_every_time = false;
202 }
203}