Skip to content

Instantly share code, notes, and snippets.

@metatoaster
Last active July 30, 2023 03:15
Show Gist options
  • Save metatoaster/cbddef0fa2dd7164df0163f38a72a94b to your computer and use it in GitHub Desktop.
Save metatoaster/cbddef0fa2dd7164df0163f38a72a94b to your computer and use it in GitHub Desktop.
Example on how chrono may be mocked.
/*
[dependencies]
chrono = "0.4.26"
*/
use crate::demo::in_the_future;
pub fn main() {
let dt = chrono::Utc::now();
println!("{dt} is in the future: {}", in_the_future(dt));
}
#[cfg(test)]
mod test {
use crate::demo::in_the_future;
use crate::mock_chrono::set_timestamp;
use chrono::{DateTime, Utc};
#[test]
fn test_record_past() {
set_timestamp(1357908642);
assert!(!in_the_future(
"2012-12-12T12:12:12Z"
.parse::<DateTime<Utc>>()
.expect("valid timestamp"),
));
}
#[test]
fn test_record_future() {
set_timestamp(1539706824);
assert!(in_the_future(
"2022-02-22T22:22:22Z"
.parse::<DateTime<Utc>>()
.expect("valid timestamp"),
));
}
}
#[cfg(test)]
mod mock_chrono {
use chrono::{DateTime, NaiveDateTime};
use std::cell::Cell;
thread_local! {
static TIMESTAMP: Cell<i64> = const { Cell::new(0) };
}
pub struct Utc;
impl Utc {
pub fn now() -> DateTime<chrono::Utc> {
DateTime::<chrono::Utc>::from_utc(
TIMESTAMP.with(|timestamp| {
NaiveDateTime::from_timestamp_opt(timestamp.get(), 0)
.expect("a valid timestamp set")
}),
chrono::Utc,
)
}
}
pub fn set_timestamp(timestamp: i64) {
TIMESTAMP.with(|ts| ts.set(timestamp));
}
}
mod demo {
#[cfg(test)]
use crate::mock_chrono::Utc;
use chrono::DateTime;
#[cfg(not(test))]
use chrono::Utc;
pub fn in_the_future(dt: DateTime<chrono::Utc>) -> bool {
dt > Utc::now()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment