ocpi-tariffs 0.54.0

OCPI tariff calculations
Documentation
//! Tests for `parse_date`: which forms of a date the library reads.

#![allow(clippy::unwrap_used, reason = "test code with known-valid dates")]

use chrono::NaiveDate;

use super::{DateError, parse_date};

#[test]
fn a_date_in_the_spec_format_is_read() {
    assert_eq!(
        parse_date("2023-01-05"),
        Ok(NaiveDate::from_ymd_opt(2023, 1, 5).unwrap())
    );
}

#[test]
fn a_month_or_day_without_its_leading_zero_is_read() {
    let expected = Ok(NaiveDate::from_ymd_opt(2023, 1, 5).unwrap());

    for text in ["2023-1-5", "2023-1-05", "2023-01-5"] {
        assert_eq!(parse_date(text), expected, "for `{text}`");
    }
}

#[test]
fn a_date_with_ascii_spaces_around_it_is_read() {
    let expected = Ok(NaiveDate::from_ymd_opt(2023, 1, 5).unwrap());

    for text in [" 2023-01-05", "2023-01-05 ", "  2023-1-5  "] {
        assert_eq!(parse_date(text), expected, "for `{text}`");
    }
}

/// A space inside the date, or whitespace other than the ASCII space around it, is not read.
/// U+00A0 is the no-break space. `str::trim` would read both of the last two, and a no-break space
/// in a date is more likely damage than formatting.
#[test]
fn a_date_with_other_whitespace_is_not_read() {
    for text in ["2023 -01-05", "\u{a0}2023-01-05", "\t2023-01-05"] {
        assert_eq!(parse_date(text), Err(DateError::Syntax), "for `{text}`");
    }
}

/// chrono's `NaiveDate::from_str` reads `+2023-01-05`, `-2023-01-05` and `23-01-05`, the last as
/// the year `0023`.
#[test]
fn a_date_in_any_other_form_is_not_read() {
    let texts = [
        "+2023-01-05",
        "-2023-01-05",
        "23-01-05",
        "02023-01-05",
        "2023-001-05",
        "2023-01-005",
        "2023--1-05",
        "2023-01",
        "2023-01-05-01",
        "2023/01/05",
        "",
    ];

    for text in texts {
        assert_eq!(parse_date(text), Err(DateError::Syntax), "for `{text}`");
    }
}

/// Only a digit in the ASCII range is read. `\u{0663}` is ARABIC-INDIC DIGIT THREE, which is two
/// bytes in UTF-8. `str::len` counts bytes, so the year `2\u{0663}3` has a length of 4 and reaches
/// the digit check rather than failing on its length.
#[test]
fn a_digit_outside_ascii_is_not_read() {
    assert_eq!(parse_date("2\u{0663}3-01-05"), Err(DateError::Syntax));
}

#[test]
fn a_date_the_calendar_does_not_have_is_not_read() {
    for text in [
        "2023-02-29",
        "2023-13-01",
        "2023-00-10",
        "2023-01-00",
        "2023-04-31",
    ] {
        assert_eq!(
            parse_date(text),
            Err(DateError::NotACalendarDate),
            "for `{text}`"
        );
    }
}

#[test]
fn a_leap_day_is_read() {
    assert_eq!(
        parse_date("2024-02-29"),
        Ok(NaiveDate::from_ymd_opt(2024, 2, 29).unwrap())
    );
}