Skip to content

Commit

Permalink
clock: add basic tests
Browse files Browse the repository at this point in the history
  • Loading branch information
da2ce7 committed Sep 9, 2022
1 parent 0b96540 commit d70b51a
Showing 1 changed file with 68 additions and 0 deletions.
68 changes: 68 additions & 0 deletions src/protocol/clock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -99,3 +99,71 @@ impl<const T: usize> TryInto<u32> for UnixTime<{ T }> {
self.0.as_secs().try_into()
}
}

#[cfg(test)]
mod tests {
use std::thread;

use super::*;

type FixedTime = UnixTime<{ ClockType::FixedTime as usize }>;

#[test]
fn fixed_time_and_default_time_should_be_the_same() {
// We are testing, so we should default to the fixed time.
assert_eq!(FixedTime::now(), DefaultTime::now())
}

#[test]
fn fixed_time_and_system_time_should_have_different_values() {
assert_ne!(FixedTime::now().0, CurrentTime::now().0)
}

#[test]
fn fixed_time_should_default_to_zero() {
assert_eq!(FixedTime::now().0, Duration::ZERO)
}

#[test]
fn fixed_time_should_be_settable_and_resettable() {
// Check we start with ZERO.
assert_eq!(FixedTime::now().0, Duration::ZERO);

// Set to Current Time and Check
let timestamp = CurrentTime::now();
FixedTime::set_time(&timestamp.0);
assert_eq!(FixedTime::now().0, timestamp.0);

// Reset to ZERO and Check
FixedTime::reset_time();
assert_eq!(FixedTime::now().0, Duration::ZERO);
}

#[test]
fn fixed_time_should_default_to_zero_on_new_and_thread_exit() {
assert_eq!(FixedTime::now().0, Duration::ZERO);
let after5 = CurrentTime::after_sec(5);
FixedTime::set_time(&after5.0);
assert_eq!(FixedTime::now().0, after5.0);

let t = thread::spawn(move || {
// each thread starts out with the initial value of ZERO
assert_eq!(FixedTime::now().0, Duration::ZERO);

// and gets set to the current time.
let timestamp = CurrentTime::now();
FixedTime::set_time(&timestamp.0);
assert_eq!(FixedTime::now().0, timestamp.0);
});

// wait for the thread to complete and bail out on panic
t.join().unwrap();

// we retain our original value of current time + 5sec despite the child thread
assert_eq!(FixedTime::now().0, after5.0);

// Reset to ZERO and Check
FixedTime::reset_time();
assert_eq!(FixedTime::now().0, Duration::ZERO);
}
}

0 comments on commit d70b51a

Please sign in to comment.