Skip to content

Commit

Permalink
feat: Add conversion to/from std::time::SystemTime
Browse files Browse the repository at this point in the history
This is useful for testing with a SystemTime received over the network and you want to compare them with a mocked SystemTime.
  • Loading branch information
caspermeijn committed Feb 16, 2024
1 parent e8be7c4 commit accfb15
Showing 1 changed file with 25 additions and 0 deletions.
25 changes: 25 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -255,6 +255,22 @@ impl std::ops::SubAssign<Duration> for SystemTime {
}
}

impl From<std::time::SystemTime> for SystemTime {
fn from(value: std::time::SystemTime) -> Self {
Self(
value
.duration_since(std::time::SystemTime::UNIX_EPOCH)
.expect("std::time::SystemTime is before UNIX_EPOCH"),
)
}
}

impl From<SystemTime> for std::time::SystemTime {
fn from(value: SystemTime) -> Self {
Self::UNIX_EPOCH + value.0
}
}

/// A simple deterministic Instant wrapped around a modifiable Duration
///
/// This used a thread-local state as the 'wall clock' that is configurable via
Expand Down Expand Up @@ -423,6 +439,15 @@ mod tests {
.is_none());
}

#[test]
fn system_time_from_std_roundtrip() {
let std_now = std::time::SystemTime::now();
let mock_now: SystemTime = std_now.into();
assert!(mock_now.0 > Duration::from_secs(1708041600)); // Friday 16 February 2024 00:00:00 GMT
let roundtrip_now: std::time::SystemTime = mock_now.into();
assert_eq!(std_now, roundtrip_now)
}

#[test]
fn set_time() {
MockClock::set_time(Duration::from_secs(42));
Expand Down

0 comments on commit accfb15

Please sign in to comment.