ocpi-tariffs 0.46.0

OCPI tariff calculations
Documentation
use assert_matches::assert_matches;

use crate::{ParseErrorKind, ReasonableStr};

#[test]
fn should_allow_reasonable_cdr_str() {
    const JSON: &str =
        include_str!("../test_data/v211/real_world/time_and_parking_time_separate_tariff/cdr.json");

    let _cdr = crate::cdr::parse(JSON).expect("Unable to parse CDR JSON");
}

#[test]
fn should_forbid_unreasonable_cdr_str() {
    let json = unreasonable_string();

    let error = crate::cdr::parse(&json)
        .expect_err("The `String` is so large it should fail the `ReasonableStr` checks");
    assert_matches!(error.kind(), ParseErrorKind::SizeExceedsMax);
}

#[test]
fn should_allow_reasonable_tariff_str() {
    const JSON: &str = include_str!(
        "../test_data/v211/real_world/time_and_parking_time_separate_tariff/tariff.json"
    );

    let _tariff = crate::tariff::parse(JSON).expect("Unable to parse CDR JSON");
}

#[test]
fn should_forbid_unreasonable_tariff_str() {
    let json = unreasonable_string();
    // Create a 2 megabytes `String` from a 32 bit fragment `str`.
    let error = crate::tariff::parse(&json)
        .expect_err("The `String` is so large it should fail the `ReasonableStr` checks");
    assert_matches!(error.kind(), ParseErrorKind::SizeExceedsMax);
}

fn unreasonable_string() -> String {
    const TOKEN: &str = "This is an unreasonable size for an input str.";
    const FACTOR: usize = ReasonableStr::MAX_STR_INPUT_LEN / TOKEN.len();

    let s = str::repeat(TOKEN, FACTOR + 1);

    assert!(
        s.len() >= ReasonableStr::MAX_STR_INPUT_LEN,
        "The test `String` len `{}` should be greater than or equal to the `ReasonableStr` max `{}`",
        s.len(),
        ReasonableStr::MAX_STR_INPUT_LEN
    );

    s
}