Last active
May 30, 2024 07:47
-
-
Save metatoaster/cbddef0fa2dd7164df0163f38a72a94b to your computer and use it in GitHub Desktop.
Example on how chrono may be mocked.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
[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; | |
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> { | |
TIMESTAMP.with(|timestamp| DateTime::<chrono::Utc>::from_timestamp( | |
timestamp.get(), | |
0, | |
)).expect("a valid timestamp set") | |
} | |
} | |
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