#![allow(
clippy::indexing_slicing,
clippy::panic,
clippy::unwrap_used,
reason = "test code with known-structure parsed data"
)]
use crate::{Version, Warning as _, json, lint, tariff, test, warning};
use super::{Edit, Fixable as _, Json, Meaning, apply, edits};
const TARIFF: &str = r#"{
"country_code": "NL",
"party_id": "TDR",
"id": "TEST",
"currency": "EUR",
"elements": [
{
"restrictions": {RESTRICTIONS},
"price_components": [
{
"type": "ENERGY",
"price": 0.38,
"step_size": 1
}
]
}
],
"last_updated": "2020-01-01T00:00:00Z"
}"#;
fn field<'buf>(json: &'buf str, name: &str) -> (json::Document<'buf>, json::ElemId) {
let doc = json::parse_object(json).unwrap();
let id = doc.root().find_field(name).unwrap().element().id();
(doc, id)
}
fn linted(json: &str) -> (tariff::Versioned<'_>, warning::Set<lint::tariff::Warning>) {
let doc = json::parse_object(json).unwrap();
let tariff = tariff::from_json(doc, Version::V221).ignore_warnings();
let report = tariff::lint(&tariff);
(tariff, report.warnings)
}
fn lint_warning_ids(json: &str) -> Vec<String> {
let (_tariff, warnings) = linted(json);
warnings
.iter()
.flat_map(|group| group.warnings())
.map(|warning| warning.id().as_str().to_owned())
.collect()
}
#[test]
fn a_list_of_every_day_is_removed() {
let days = r#"{"day_of_week": ["MONDAY", "TUESDAY", "WEDNESDAY", "THURSDAY", "FRIDAY", "SATURDAY", "SUNDAY"]}"#;
let (doc, id) = field(days, "day_of_week");
let element = doc.element(id).unwrap();
assert_eq!(
lint::tariff::Warning::ContainsEntireWeek.fix(element),
Some(Edit::remove(id, Meaning::Preserves))
);
}
#[test]
fn an_unsorted_list_is_put_in_spec_order() {
let (doc, id) = field(r#"{"day_of_week": ["FRIDAY", "MONDAY"]}"#, "day_of_week");
let element = doc.element(id).unwrap();
assert_eq!(
lint::tariff::Warning::DayOfWeekUnsorted.fix(element),
Some(Edit::replace(
id,
Json::string_array(&["MONDAY", "FRIDAY"]),
Meaning::Preserves
))
);
}
#[test]
fn a_repeating_list_keeps_one_of_each_day() {
let (doc, id) = field(
r#"{"day_of_week": ["MONDAY", "MONDAY", "TUESDAY"]}"#,
"day_of_week",
);
let element = doc.element(id).unwrap();
assert_eq!(
lint::tariff::Warning::DayOfWeekDuplicates.fix(element),
Some(Edit::replace(
id,
Json::string_array(&["MONDAY", "TUESDAY"]),
Meaning::Preserves
))
);
}
#[test]
fn an_unsorted_repeating_list_gets_the_same_text_from_either_warning() {
let (doc, id) = field(
r#"{"day_of_week": ["FRIDAY", "MONDAY", "MONDAY"]}"#,
"day_of_week",
);
let element = doc.element(id).unwrap();
assert_eq!(
lint::tariff::Warning::DayOfWeekUnsorted.fix(element),
lint::tariff::Warning::DayOfWeekDuplicates.fix(element)
);
}
#[test]
fn an_empty_list_is_removed() {
let (doc, id) = field(r#"{"day_of_week": []}"#, "day_of_week");
let element = doc.element(id).unwrap();
assert_eq!(
lint::tariff::Warning::DayOfWeekEmpty.fix(element),
Some(Edit::remove(id, Meaning::Preserves))
);
}
#[test]
fn a_list_naming_days_in_lower_case_is_left_alone_by_the_sort() {
let (doc, id) = field(r#"{"day_of_week": ["friday", "monday"]}"#, "day_of_week");
let element = doc.element(id).unwrap();
assert_eq!(lint::tariff::Warning::DayOfWeekUnsorted.fix(element), None);
}
#[test]
fn a_list_holding_something_other_than_a_day_is_left_alone() {
let (doc, id) = field(r#"{"day_of_week": ["FRIDAY", 3]}"#, "day_of_week");
let element = doc.element(id).unwrap();
assert_eq!(lint::tariff::Warning::DayOfWeekUnsorted.fix(element), None);
}
#[test]
fn a_warning_needing_a_human_decision_proposes_nothing() {
let (doc, id) = field(r#"{"day_of_week": ["FRIDAY", "MONDAY"]}"#, "day_of_week");
let element = doc.element(id).unwrap();
let unfixable = [
lint::tariff::Warning::CpoCountryCodeShouldBeAlpha2,
lint::tariff::Warning::ElementExcludesEverySession(
lint::tariff::OtherElements::NoneMayMatch,
),
lint::tariff::Warning::ElementExcludesEverySession(
lint::tariff::OtherElements::TariffRejected,
),
lint::tariff::Warning::EndTimeIsNearEndOfDay,
lint::tariff::Warning::LowerBoundAtOrAboveUpper,
lint::tariff::Warning::MaxZeroNeverMatch,
lint::tariff::Warning::MinPriceIsGreaterThanMax,
lint::tariff::Warning::MinZeroExcludesOnlyNegative,
lint::tariff::Warning::NeverValid,
lint::tariff::Warning::StartDateTimeIsAfterEndDateTime,
];
for warning in unfixable {
assert_eq!(warning.fix(element), None, "for `{warning:?}`");
}
}
#[test]
fn a_tariff_has_its_day_of_week_list_normalized() {
test::setup();
let source = TARIFF.replace(
"{RESTRICTIONS}",
r#"{"day_of_week": ["FRIDAY", "MONDAY", "MONDAY"]}"#,
);
let (tariff, warnings) = linted(&source);
let doc = tariff.as_doc();
let proposed = edits(doc, &warnings).unwrap();
let fixed = apply(doc, &proposed).unwrap();
assert_eq!(
fixed,
TARIFF.replace("{RESTRICTIONS}", r#"{"day_of_week": ["MONDAY", "FRIDAY"]}"#)
);
assert_eq!(lint_warning_ids(&fixed), Vec::<String>::new());
}
#[test]
fn a_tariff_loses_a_day_of_week_list_naming_every_day() {
test::setup();
let days = r#"["MONDAY", "TUESDAY", "WEDNESDAY", "THURSDAY", "FRIDAY", "SATURDAY", "SUNDAY"]"#;
let source = TARIFF.replace("{RESTRICTIONS}", &format!(r#"{{"day_of_week": {days}}}"#));
let (tariff, warnings) = linted(&source);
let doc = tariff.as_doc();
let proposed = edits(doc, &warnings).unwrap();
let fixed = apply(doc, &proposed).unwrap();
assert!(!fixed.contains("day_of_week"), "got:\n{fixed}");
assert_eq!(
lint_warning_ids(&fixed),
vec!["restrictions_empty".to_owned()]
);
}
#[test]
fn removing_a_list_beats_sorting_it() {
test::setup();
let days = r#"["SUNDAY", "MONDAY", "TUESDAY", "WEDNESDAY", "THURSDAY", "FRIDAY", "SATURDAY"]"#;
let source = TARIFF.replace("{RESTRICTIONS}", &format!(r#"{{"day_of_week": {days}}}"#));
let (tariff, warnings) = linted(&source);
let doc = tariff.as_doc();
let proposed = edits(doc, &warnings).unwrap();
let fixed = apply(doc, &proposed).unwrap();
assert!(!fixed.contains("day_of_week"), "got:\n{fixed}");
assert_eq!(
lint_warning_ids(&fixed),
vec!["restrictions_empty".to_owned()]
);
}
#[test]
fn a_min_duration_of_zero_is_removed() {
let (doc, id) = field(r#"{"min_duration": 0}"#, "min_duration");
let element = doc.element(id).unwrap();
assert_eq!(
lint::tariff::Warning::MinDurationZeroAllowsEverySession.fix(element),
Some(Edit::remove(id, Meaning::Preserves))
);
}
#[test]
fn a_tariff_loses_a_min_duration_of_zero() {
test::setup();
let source = TARIFF.replace("{RESTRICTIONS}", r#"{"min_duration": 0}"#);
let (tariff, warnings) = linted(&source);
let doc = tariff.as_doc();
let proposed = edits(doc, &warnings).unwrap();
let fixed = apply(doc, &proposed).unwrap();
assert_eq!(fixed, TARIFF.replace("{RESTRICTIONS}", "{}"));
assert_eq!(
lint_warning_ids(&fixed),
vec!["restrictions_empty".to_owned()]
);
}
#[test]
fn a_time_bound_of_midnight_is_removed() {
for name in ["start_time", "end_time"] {
for value in ["00:00", "0:00"] {
let json = format!(r#"{{"{name}": "{value}"}}"#);
let (doc, id) = field(&json, name);
let element = doc.element(id).unwrap();
assert_eq!(
lint::tariff::Warning::ContainsEntireDay.fix(element),
Some(Edit::remove(id, Meaning::Preserves)),
"for `{name}` of `{value}`"
);
}
}
}
#[test]
fn an_end_time_of_23_59_is_left_alone() {
let (doc, id) = field(r#"{"end_time": "23:59"}"#, "end_time");
let element = doc.element(id).unwrap();
assert_eq!(lint::tariff::Warning::ContainsEntireDay.fix(element), None);
}
#[test]
fn a_tariff_loses_one_bound_of_a_midnight_pair_per_pass() {
test::setup();
let source = TARIFF.replace(
"{RESTRICTIONS}",
r#"{"start_time": "00:00", "end_time": "00:00"}"#,
);
let (tariff, warnings) = linted(&source);
let doc = tariff.as_doc();
let proposed = edits(doc, &warnings).unwrap();
let fixed = apply(doc, &proposed).unwrap();
assert_eq!(
fixed,
TARIFF.replace("{RESTRICTIONS}", r#"{"end_time": "00:00"}"#)
);
assert_eq!(
lint_warning_ids(&fixed),
vec!["contains_entire_day".to_owned()]
);
}
#[test]
fn a_tariff_keeps_an_end_time_of_23_59() {
test::setup();
let source = TARIFF.replace(
"{RESTRICTIONS}",
r#"{"start_time": "00:00", "end_time": "23:59"}"#,
);
let (tariff, warnings) = linted(&source);
let doc = tariff.as_doc();
let proposed = edits(doc, &warnings).unwrap();
let fixed = apply(doc, &proposed).unwrap();
let expected = TARIFF.replace("{RESTRICTIONS}", r#"{"end_time": "23:59"}"#);
assert_eq!(fixed, expected);
let (tariff, warnings) = linted(&fixed);
let proposed = edits(tariff.as_doc(), &warnings).unwrap();
assert_eq!(proposed, Vec::new());
}
#[test]
fn a_tariff_keeps_a_min_duration_written_with_a_decimal_point() {
test::setup();
let source = TARIFF.replace("{RESTRICTIONS}", r#"{"min_duration": 0.0}"#);
let (tariff, warnings) = linted(&source);
let doc = tariff.as_doc();
let proposed = edits(doc, &warnings).unwrap();
let fixed = apply(doc, &proposed).unwrap();
assert_eq!(proposed, Vec::new());
assert_eq!(fixed, source);
assert_eq!(lint_warning_ids(&fixed), vec!["invalid".to_owned()]);
}
struct RepeatedKeyCase {
restrictions: &'static str,
warning: lint::tariff::Warning,
}
impl RepeatedKeyCase {
fn source(&self) -> String {
TARIFF.replace("{RESTRICTIONS}", self.restrictions)
}
}
fn repeated_key_cases() -> [RepeatedKeyCase; 3] {
[
RepeatedKeyCase {
restrictions: r#"{"min_duration": 60, "min_duration": 0}"#,
warning: lint::tariff::Warning::MinDurationZeroAllowsEverySession,
},
RepeatedKeyCase {
restrictions: concat!(
r#"{"day_of_week": ["MONDAY"], "day_of_week": "#,
r#"["MONDAY", "TUESDAY", "WEDNESDAY", "THURSDAY", "FRIDAY", "SATURDAY", "SUNDAY"]}"#,
),
warning: lint::tariff::Warning::ContainsEntireWeek,
},
RepeatedKeyCase {
restrictions: r#"{"max_kwh": 5}, "restrictions": {}"#,
warning: lint::tariff::Warning::RestrictionsEmpty,
},
]
}
#[test]
fn lint_warnings_alone_propose_no_removal_of_a_repeated_key() {
test::setup();
for case in repeated_key_cases() {
let source = case.source();
let doc = json::parse_object(&source).unwrap();
let (tariff, _schema_warnings) = tariff::from_json(doc, Version::V221).into_parts();
let lint_warnings = tariff::lint(&tariff).warnings;
let doc = tariff.as_doc();
let group = lint_warnings
.iter()
.find(|group| group.warnings().contains(&&case.warning))
.unwrap_or_else(|| panic!("expected {:?}\nsource:\n{source}", case.warning));
let (element, _raised) = group.to_parts();
let warned = doc.element(element.id).unwrap();
assert_eq!(
case.warning.fix(warned),
Some(Edit::remove(element.id, Meaning::Preserves)),
"expected the fix for {:?} to remove the field it sits on\nsource:\n{source}",
case.warning
);
let proposed = edits(doc, &lint_warnings).unwrap();
assert_eq!(
proposed,
Vec::new(),
"expected no edits: the only fix in the lint warnings removes the last occurrence of a \
repeated key, which would let an earlier value be used\nsource:\n{source}"
);
}
}
#[test]
fn the_fixing_loop_resolves_a_repeated_key_before_removing_it() {
test::setup();
let without_restrictions = TARIFF.replace("\"restrictions\": {RESTRICTIONS},\n ", "");
for case in repeated_key_cases() {
let source = case.source();
let doc = json::parse_object(&source).unwrap();
let tariff = tariff::from_json(doc, Version::V221).ignore_warnings();
let fixed = tariff::fix(&tariff, lint::fix::Options::default()).unwrap();
assert_eq!(fixed.source, without_restrictions, "source:\n{source}");
}
}
#[test]
fn a_tariff_keeps_a_min_kwh_of_zero() {
test::setup();
let source = TARIFF.replace("{RESTRICTIONS}", r#"{"min_kwh": 0}"#);
let (tariff, warnings) = linted(&source);
let doc = tariff.as_doc();
let proposed = edits(doc, &warnings).unwrap();
let fixed = apply(doc, &proposed).unwrap();
assert_eq!(proposed, Vec::new());
assert_eq!(fixed, source);
assert_eq!(
lint_warning_ids(&fixed),
vec!["min_zero_excludes_only_negative".to_owned()]
);
}