Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add clock #2

Merged
merged 1 commit into from
Sep 19, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,10 @@ keywords = ["mock", "mockable", "mocking", "test"]
categories = ["development-tools::testing"]

[features]
clock = ["dep:chrono"]
full = ["clock"]
mock = ["dep:mockall"]

[dependencies]
chrono = { version = "0.4", optional = true }
mockall = { version = "0.11", optional = true }
70 changes: 70 additions & 0 deletions src/clock.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
use chrono::{DateTime, Local, Utc};
use mockall::mock;

// Clock

/// A trait for getting the current time.
///
/// **This is supported on `feature=clock` only.**
/// # Examples
///
/// ```
/// use chrono::{DateTime, Utc, Duration};
/// use mockable::{Clock, DefaultClock, MockClock};
///
/// fn now(clock: &dyn Clock) -> DateTime<Utc> {
/// clock.utc()
/// }
///
/// // Default
/// let time = now(&DefaultClock);
/// assert!(time < Utc::now() + Duration::seconds(1));
///
/// // Mock
/// let expected = Utc::now();
/// let mut clock = MockClock::new();
/// clock
/// .expect_utc()
/// .returning(move || expected);
/// let time = now(&clock);
/// assert_eq!(time, expected);
/// ```
pub trait Clock: Send + Sync {
/// Returns the current time in the local timezone.
fn local(&self) -> DateTime<Local>;

/// Returns the current time in UTC.
fn utc(&self) -> DateTime<Utc>;
}

// DefaultClock

/// Default implementation of `Clock`.
///
/// **This is supported on `feature=clock` only.**
pub struct DefaultClock;

impl Clock for DefaultClock {
fn local(&self) -> DateTime<Local> {
Local::now()
}

fn utc(&self) -> DateTime<Utc> {
Utc::now()
}
}

// MockClock

#[cfg(feature = "mock")]
mock! {
/// `mockall` implementation of `Clock`.
///
/// **This is supported on `feature=clock,mock` only.**
pub Clock {}

impl super::Clock for Clock {
fn local(&self) -> DateTime<Local>;
fn utc(&self) -> DateTime<Utc>;
}
}
8 changes: 8 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
@@ -1 +1,9 @@
// Re-use

#[cfg(feature = "clock")]
pub use self::clock::*;

// Mods

#[cfg(feature = "clock")]
mod clock;
Loading