Skip to content

Commit 496e79f

Browse files
committed
Add MockInstant time utility for testing
To avoid sleeping in tests when using `Instant`s, we introduce a new `MockInstant` that relies on a fake time which can be advanced in tests deterministically.
1 parent 414d8e1 commit 496e79f

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

lightning/src/util/time.rs

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -125,6 +125,27 @@ pub mod tests {
125125
}
126126
}
127127

128+
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
129+
pub struct MockInstant(Duration);
130+
131+
impl MockInstant {
132+
thread_local! {
133+
static TIME: Cell<Duration> = Cell::new(Duration::default());
134+
}
135+
136+
pub fn now() -> Self {
137+
Self(Self::TIME.with(|t| t.get()))
138+
}
139+
140+
pub fn advance(duration: Duration) {
141+
Self::TIME.with(|t| t.set(t.get() + duration))
142+
}
143+
144+
pub fn elapsed(&self) -> Duration {
145+
Self::TIME.with(|t| t.get()) - self.0
146+
}
147+
}
148+
128149
#[test]
129150
fn time_passes_when_advanced() {
130151
let now = SinceEpoch::now();
@@ -149,4 +170,18 @@ pub mod tests {
149170
assert_eq!(now.elapsed(), Duration::from_secs(0));
150171
assert_eq!(later - elapsed, now);
151172
}
173+
174+
#[test]
175+
fn time_passes_when_advanced_for_mock_instant() {
176+
let now = MockInstant::now();
177+
178+
MockInstant::advance(Duration::from_secs(1));
179+
MockInstant::advance(Duration::from_secs(1));
180+
181+
let elapsed = now.elapsed();
182+
let later = MockInstant::now();
183+
184+
assert_eq!(elapsed, Duration::from_secs(2));
185+
assert_eq!(later.elapsed().as_secs(), 0);
186+
}
152187
}

0 commit comments

Comments
 (0)