#![allow(
clippy::indexing_slicing,
clippy::unwrap_in_result,
clippy::panic,
clippy::unwrap_used,
reason = "test code with known-structure parsed data"
)]
use std::path::{Path, PathBuf};
use crate::{
Version, cdr, json, lint, money,
price::{self, test::UnwrapReport as _},
tariff, test, warning,
};
use super::edits;
const TIMEZONE: chrono_tz::Tz = chrono_tz::Tz::Europe__Amsterdam;
#[test_each::file(
glob = "ocpi-tariffs/test_data/v211/fix/preserving/*/tariff.json",
name(segments = 2)
)]
fn fixing_a_v211_tariff_does_not_change_what_a_session_costs(tariff_json: &str, path: &Path) {
test::setup();
assert_fix_preserves_price(Version::V211, tariff_json, path);
}
#[test_each::file(
glob = "ocpi-tariffs/test_data/v221/fix/preserving/*/tariff.json",
name(segments = 2)
)]
fn fixing_a_v221_tariff_does_not_change_what_a_session_costs(tariff_json: &str, path: &Path) {
test::setup();
assert_fix_preserves_price(Version::V221, tariff_json, path);
}
#[test_each::file(
glob = "ocpi-tariffs/test_data/v221/fix/repairing/*/tariff.json",
name(segments = 2)
)]
fn fixing_a_tariff_makes_an_unpriceable_session_priceable(tariff_json: &str, path: &Path) {
test::setup();
let version = Version::V221;
let case = Case::at(path);
let tariff_json_fixed = parse_validate_fix(version, tariff_json);
case.assert_fixed_text(&tariff_json_fixed);
assert!(
prices(version, &case.cdr_json, tariff_json).is_err(),
"the tariff was expected not to price before it was fixed"
);
assert!(
prices(version, &case.cdr_json, &tariff_json_fixed).is_ok(),
"the fixed tariff was expected to price"
);
for (name, cdr_json) in shared_cdrs(&case.dir) {
assert!(
prices(version, &cdr_json, &tariff_json_fixed).is_ok(),
"the fixed tariff was expected to price the `{name}` CDR"
);
}
assert_no_more_fixes(version, &tariff_json_fixed);
}
#[test_each::file(
glob = "ocpi-tariffs/test_data/v221/fix/changing/*/tariff.json",
name(segments = 2)
)]
fn fixing_a_tariff_with_changes_allowed_prices_a_session_as_its_author_meant(
tariff_json: &str,
path: &Path,
) {
test::setup();
let version = Version::V221;
let case = Case::at(path);
assert_eq!(
parse_validate_fix(version, tariff_json),
tariff_json,
"fixing without allowing changes changed the tariff"
);
let changes_allowed = fix_options().allow_changes();
let tariff_json_fixed = fix_with(version, tariff_json, changes_allowed);
case.assert_fixed_text(&tariff_json_fixed);
let fixed = total_cost(version, &case.cdr_json, &tariff_json_fixed)
.expect("the fixed tariff was expected to price");
assert_eq!(
fixed.calculated,
Some(fixed.cdr),
"the fixed tariff does not price the session at the total its CDR states"
);
if let Ok(as_written) = total_cost(version, &case.cdr_json, tariff_json) {
assert_ne!(
as_written.calculated,
Some(as_written.cdr),
"the premise: the tariff as written prices the session at another total"
);
}
assert_no_more_fixes(version, &tariff_json_fixed);
}
#[test]
fn the_compared_text_changes_with_the_warnings_pricing_raises() {
const CDR_JSON: &str = r#"{
"start_date_time": "2022-01-13T14:30:00Z",
"end_date_time": "2022-01-13T14:30:00Z",
"currency": "EUR",
"tariffs": [],
"cdr_location": { "country": "NLD" },
"charging_periods": [
{
"start_date_time": "2022-01-13T14:30:00Z",
"dimensions": [{ "type": "ENERGY", "volume": 0 }]
}
],
"total_cost": { "excl_vat": 0.0, "incl_vat": 0.0 },
"total_energy": 0,
"total_time": 0,
"last_updated": "2022-01-13T00:00:00Z"
}"#;
const TARIFF_JSON: &str = r#"{
"country_code": "DE",
"party_id": "ALL",
"id": "1",
"currency": "EUR",
"elements": [
{ "price_components": [{ "type": "ENERGY", "price": 0.25, "step_size": 1 }] }
],
"last_updated": "2018-12-17T11:36:01Z"
}"#;
test::setup();
let (report, warnings) = price_report(Version::V221, CDR_JSON, TARIFF_JSON);
assert!(
!warnings.is_empty(),
"the premise: pricing this CDR raises a warning"
);
assert_ne!(
rendered(&report, warnings),
rendered(&report, warning::Set::new()),
"the compared text is the same with and without the pricing warnings"
);
}
#[track_caller]
fn assert_fix_preserves_price(version: Version, tariff_json: &str, path: &Path) {
let case = Case::at(path);
let tariff_json_fixed = parse_validate_fix(version, tariff_json);
case.assert_fixed_text(&tariff_json_fixed);
assert_eq!(
priced(version, &case.cdr_json, tariff_json),
priced(version, &case.cdr_json, &tariff_json_fixed),
"fixing the tariff changed the report"
);
for (name, cdr_json) in shared_cdrs(&case.dir) {
assert_eq!(
priced(version, &cdr_json, tariff_json),
priced(version, &cdr_json, &tariff_json_fixed),
"fixing the tariff changed the report for the `{name}` CDR"
);
}
assert_no_more_fixes(version, &tariff_json_fixed);
}
struct Case {
cdr_json: String,
expected: String,
dir: PathBuf,
}
impl Case {
fn at(tariff_path: &Path) -> Self {
let dir = tariff_path
.parent()
.expect("a tariff lives in a case directory");
Self {
cdr_json: read(&dir.join("cdr.json")),
expected: read(&dir.join("tariff_fixed.json")),
dir: dir.to_path_buf(),
}
}
#[track_caller]
fn assert_fixed_text(&self, fixed: &str) {
assert_eq!(
fixed, self.expected,
"the fix did not leave the expected text"
);
}
}
#[track_caller]
fn assert_no_more_fixes(version: Version, tariff_fixed_json: &str) {
assert_eq!(
parse_validate_fix(version, tariff_fixed_json),
tariff_fixed_json,
"fixing is not idempotent"
);
assert_eq!(remaining_edits(version, tariff_fixed_json), Vec::new());
}
fn shared_cdrs(case_dir: &Path) -> Vec<(String, String)> {
let dir = case_dir
.parent()
.and_then(Path::parent)
.expect("a case directory has a grandparent")
.join("cdr");
let entries = std::fs::read_dir(&dir)
.unwrap_or_else(|err| panic!("unable to read `{}`:\n{err}", dir.display()));
let mut cdrs = Vec::new();
for entry in entries {
let path = entry.expect("a readable entry in the CDR directory").path();
if path.extension().is_none_or(|s| s != "json") {
continue;
}
let name = path
.file_stem()
.expect("a CDR file is named")
.to_string_lossy()
.into_owned();
cdrs.push((name, read(&path)));
}
cdrs.sort();
assert!(!cdrs.is_empty(), "no CDRs found in `{}`", dir.display());
cdrs
}
fn read(path: &Path) -> String {
std::fs::read_to_string(path)
.unwrap_or_else(|err| panic!("unable to read `{}`:\n{err}", path.display()))
}
fn parse_validate_fix(version: Version, tariff_json: &str) -> String {
fix_with(version, tariff_json, fix_options())
}
fn fix_options() -> lint::fix::Options {
lint::fix::Options::default().unexpected_fields(lint::fix::UnexpectedFields::Remove)
}
fn fix_with(version: Version, tariff_json: &str, options: lint::fix::Options) -> String {
let doc = json::parse_object(tariff_json).unwrap();
let tariff = tariff::from_json(doc, version).ignore_warnings();
tariff::fix(&tariff, options).unwrap().source
}
fn remaining_edits(version: Version, tariff_json: &str) -> Vec<super::Edit> {
let doc = json::parse_object(tariff_json).unwrap();
let (tariff, schema_warnings) = tariff::from_json(doc, version).into_parts();
let doc = tariff.as_doc();
let lint_warnings = tariff::lint(&tariff).warnings;
let mut proposed = edits(doc, &schema_warnings).unwrap();
proposed.extend(edits(doc, &lint_warnings).unwrap());
proposed
}
fn prices(version: Version, cdr_json: &str, tariff_json: &str) -> Result<(), String> {
let doc = json::parse_object(tariff_json).unwrap();
let tariff = tariff::from_json(doc, version).ignore_warnings();
let doc = json::parse_object(cdr_json).unwrap();
let cdr = cdr::from_json(doc, version).ignore_warnings();
match price::cdr(&cdr, price::TariffSource::Override(vec![tariff]), TIMEZONE) {
Ok(_report) => Ok(()),
Err(errors) => Err(format!("{:?}", errors.into_parts().0)),
}
}
fn total_cost(
version: Version,
cdr_json: &str,
tariff_json: &str,
) -> Result<price::Total<money::Price, Option<money::Price>>, String> {
let doc = json::parse_object(tariff_json).unwrap();
let tariff = tariff::from_json(doc, version).ignore_warnings();
let doc = json::parse_object(cdr_json).unwrap();
let cdr = cdr::from_json(doc, version).ignore_warnings();
match price::cdr(&cdr, price::TariffSource::Override(vec![tariff]), TIMEZONE) {
Ok(report) => Ok(report.ignore_warnings().total_cost),
Err(errors) => Err(format!("{:?}", errors.into_parts().0)),
}
}
fn priced(version: Version, cdr_json: &str, tariff_json: &str) -> String {
let (report, warnings) = price_report(version, cdr_json, tariff_json);
rendered(&report, warnings)
}
fn price_report(
version: Version,
cdr_json: &str,
tariff_json: &str,
) -> (price::Report, warning::Set<price::Warning>) {
let doc = json::parse_object(tariff_json).unwrap();
let tariff = tariff::from_json(doc, version).ignore_warnings();
let doc = json::parse_object(cdr_json).unwrap();
let cdr = cdr::from_json(doc, version).ignore_warnings();
price::cdr(&cdr, price::TariffSource::Override(vec![tariff]), TIMEZONE)
.unwrap_report(cdr.as_json_str())
.into_parts()
}
fn rendered(report: &price::Report, warnings: warning::Set<price::Warning>) -> String {
let price::Report {
periods,
tariff_used,
tariff_reports,
timezone,
billed_charging_time,
billed_energy,
billed_idle_time,
total_charging_time,
total_energy,
total_idle_time,
total_time,
total_cost,
total_energy_cost,
total_fixed_cost,
total_idle_cost,
total_charging_time_cost,
} = report;
format!(
"periods: {periods:#?}\n\
tariff_used: {tariff_used:#?}\n\
tariff_reports: {tariff_reports:#?}\n\
timezone: {timezone:#?}\n\
billed_charging_time: {billed_charging_time:#?}\n\
billed_energy: {billed_energy:#?}\n\
billed_idle_time: {billed_idle_time:#?}\n\
total_charging_time: {total_charging_time:#?}\n\
total_energy: {total_energy:#?}\n\
total_idle_time: {total_idle_time:#?}\n\
total_time: {total_time:#?}\n\
total_cost: {total_cost:#?}\n\
total_energy_cost: {total_energy_cost:#?}\n\
total_fixed_cost: {total_fixed_cost:#?}\n\
total_idle_cost: {total_idle_cost:#?}\n\
total_charging_time_cost: {total_charging_time_cost:#?}\n\
warnings: {warnings:#?}\n",
warnings = warnings.into_path_map(),
)
}