time-rs / time

The most used Rust library for date and time handling.
https://time-rs.github.io
Apache License 2.0
1.09k stars 273 forks source link

`now_local` works in `cargo run` but failed in `cargo test` #538

Closed azzamsa closed 1 year ago

azzamsa commented 1 year ago

Hi.

I am migrating all my crates from chrono to time. It is a great and fun experience. I find the API is simpler than passing UTC or Local type around as chrono did.

One issue that I can't solve is that using OffsetDateTime::now_local() in test module always results in the error Error: The system's UTC offset could not be determined but it works in cargo run.

// [dependencies]
// anyhow = "1.0.68"
// time = { version = "0.3", features = ["macros", "formatting", "local-offset"] }

use anyhow::Result;
use time::{macros::date, Date, OffsetDateTime};

fn date() -> Result<Date> {
    // let date = date!(2021 - 04 - 09); // `date!` works.
    let date = OffsetDateTime::now_local()?.date(); // ⚠ doesn't work in test module️
    println!("{:?}", date);

    Ok(date)
}

fn main() {
    if let Err(err) = date() {
        eprintln!("Error: {:?}", err);
    }
}

#[cfg(test)]
mod tests {
    use anyhow::Result;

    use super::*;

    #[test]
    fn test_date() -> Result<()> {
        assert_eq!("2021-04-09", date()?.to_string());
        Ok(())
    }
}
❯ cargo r --quiet
2022-12-19
❯ cargo t --quiet
running 1 test
F
failures:

---- tests::test_date stdout ----
Error: The system's UTC offset could not be determined

failures:
    tests::test_date
jhpratt commented 1 year ago

Tests are multithreaded by default, which results in time returning the error on Unix-like systems for safety reasons.

azzamsa commented 1 year ago
❯ cargo test -- --test-threads 1
running 1 test
test tests::test_date ... ok

test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s

@jhpratt Thanks. It news to me that I need to pass --test-threads 1. I don't have this issue with chrono::Local::today() or chrono::Local::now().

Would you like to give me more hints why in the chrono side, they did not have this issue?

jhpratt commented 1 year ago

The soundness issue still exists there. They have just chosen to implement a very expensive workaround that still has significant flaws and soundness holes.

azzamsa commented 1 year ago

Ooh, I see.

Do we have any alternative other than passing --test-threads 1 so that we don't slow down the tests?

jhpratt commented 1 year ago

Cargo does not have the option to run a specific test serially, so unfortunately no.

azzamsa commented 1 year ago

Cargo does not have the option to run a specific test serially, so unfortunately no.

Thanks a lot! I will play with nextest and report back here the alternative.

I want to say thank you for maintaining time. Thank you so much! :heart: