Skip to main content

faketime/
lib.rs

1//! This module just reexports `faketime::system` or `faketime::faketime`, depending on whether on
2//! not the rust cfg `disable_faketime` is set. See details in the module document of
3//! [faketime::faketime](faketime/index.html).
4
5#[cfg(not(disable_faketime))]
6pub mod faketime;
7pub mod system;
8#[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
9mod wasm;
10
11#[cfg(not(disable_faketime))]
12pub use crate::faketime::{disable, enable, millis_tempfile, unix_time, write_millis};
13#[cfg(disable_faketime)]
14pub use crate::system::unix_time;
15
16/// Gets elapsed time in milliseconds since *UNIX EPOCH*.
17///
18/// ```
19/// let now = faketime::unix_time();
20/// let millis = faketime::unix_time_as_millis();
21/// assert!(millis / 1000 - now.as_secs() < 60);
22/// ```
23///
24/// This function depends on the return result from `unix_time`. If `unix_time` is faked, this
25/// function is also faked.
26///
27/// ## Panics
28///
29/// Panics if the time is before *UNIX EPOCH*, or `u64` is not enough to store the number of
30/// milliseconds.
31pub fn unix_time_as_millis() -> u64 {
32    let duration = unix_time();
33    duration.as_secs() * 1000 + u64::from(duration.subsec_millis())
34}
35
36#[cfg(test)]
37mod tests {
38    use crate::*;
39
40    #[cfg(disable_faketime)]
41    #[test]
42    fn test_system() {
43        let system_now = system::unix_time();
44        let now = unix_time();
45        assert!((now - system_now).as_secs() < 60);
46    }
47
48    #[cfg(not(disable_faketime))]
49    #[test]
50    fn test_faketime() {
51        let faketime_file = millis_tempfile(123_456).expect("create faketime file");
52        enable(&faketime_file);
53
54        let now = unix_time();
55        assert_eq!(123, now.as_secs());
56        assert_eq!(456, now.subsec_millis());
57    }
58}