ocpi-tariffs 0.54.0

OCPI tariff calculations
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
//! Tests for [`Fixable`] as `lint::tariff::Warning` implements it: which lint warnings a
//! mechanical edit resolves, and which are left for the tariff's author.
//!
//! The `day_of_week` fixes are the ones where the anchoring matters: all four of that list's
//! warnings anchor to the array itself, so one element can carry more than one of them at once. A
//! `min_duration` warning anchors to its own field.
//!
//! Most tests here lint and edit in one step, passing [`edits`] the lint warnings and no schema
//! warnings. They rely on `edits` being safe given any subset of the warnings, including when a
//! key occurs more than once, as its documentation states.

#![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};

/// A tariff with one element, whose `restrictions` object is `{RESTRICTIONS}`.
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"
}"#;

/// A parsed document and the element of its field called `name`, which the warnings anchor to.
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)
}

/// Lint `json` as a v2.2.1 tariff and return it with the warnings linting raised.
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)
}

/// The ids of the warnings linting still raises for `json`.
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()
}

/// All seven days match every day, which is what leaving the list out means.
#[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
        ))
    );
}

/// Both warnings describe the same list, so both ask for the same normalized text.
#[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)
    );
}

/// OCPI reads an empty list the same as leaving the list out.
#[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))
    );
}

/// The list of `an_unsorted_list_is_put_in_spec_order` lower-cased and changed in no other way,
/// so the case is the only thing between this warning being fixed and being left alone.
///
/// The order stays unsorted because the schema accepts a day in any case: this list really does
/// carry `DayOfWeekUnsorted`, and it is the fixer's exact match on the names that declines it,
/// rather than rewriting a list it has only half understood. The case is the schema walk's to
/// report and resolve, after which the list is one this warning does fix.
#[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:?}`");
    }
}

/// The whole round trip, over a list carrying both warnings at once: lint the tariff, propose
/// the edits, apply them. The two proposals agree, so `apply` takes them as one edit.
#[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());
}

/// The list is this element's only restriction, so removing it leaves the object empty, which
/// the next walk reports. This test applies the edits of a single pass, so that object is still
/// here; the fixing loop removes it on the pass after this one.
#[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()]
    );
}

/// A list naming every day out of order carries the removal and the sort at once, and the
/// removal wins because the bytes go away either way. The emptied object is left behind by this
/// single pass, as in the test above.
#[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))
    );
}

/// The `min_duration` is this element's only restriction, so removing it leaves the object empty,
/// which the next walk reports. As in the `day_of_week` tests above, the fixing loop is what
/// removes that object on the following pass.
#[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()]
    );
}

/// The fix removes any bound that the library reads as midnight.
#[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}`"
            );
        }
    }
}

/// The linter raises `ContainsEntireDay` on a lone `end_time` of `23:59`, and the fix keeps the
/// bound. Removing the bound would widen the element's time window by a minute.
#[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);
}

/// This test applies the edits of a single pass, which removes `start_time` alone. With both bounds
/// present the linter raises `ContainsEntireDay` on `start_time` only, and raises it on the lone
/// `end_time` once `start_time` is gone.
#[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()]
    );
}

/// The fix removes the `start_time` of `00:00` and keeps the `end_time` of `23:59`. The linter
/// raises `ContainsEntireDay` again on the lone `end_time`, and the fix proposes nothing for it.
#[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());
}

/// The library reads a duration only when it is written as an integer, so the linter reports
/// `min_duration: 0.0` as `invalid`. The linter never reports that value as a bound that allows
/// every session, so `--fix` leaves it in place and the author has to rewrite it. The value is
/// `0` to a reader and unreadable to the library.
#[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()]);
}

/// A tariff in which one key occurs twice, and the lint warning raised on the last occurrence.
/// That warning's fix removes the last occurrence, which is the one used, so applying it would
/// result in the earlier field's value being used.
struct RepeatedKeyCase {
    /// Substituted for `{RESTRICTIONS}` in `TARIFF`.
    restrictions: &'static str,

    /// The lint warning raised on the last occurrence.
    warning: lint::tariff::Warning,
}

impl RepeatedKeyCase {
    fn source(&self) -> String {
        TARIFF.replace("{RESTRICTIONS}", self.restrictions)
    }
}

/// One case for each lint warning whose fix is a removal.
///
/// `TARIFF` writes `"restrictions": {RESTRICTIONS}`, so the `RestrictionsEmpty` case substitutes an
/// object, then a second `restrictions` field.
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,
        },
    ]
}

/// Each case writes one key twice. Removing the first of the two is the fix for
/// `schema::Warning::DuplicateField`, which is a schema warning, so a caller who gives only the
/// lint warnings to the `edits` function leaves that fix out.
///
/// Some lint warnings also have a removal as their fix, and in each case here that removal would
/// take the second of the two, the one that is used. So `edits` has to guard against a lint
/// warning's removal as well as a schema warning's, and it proposes no edits.
#[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();

        // Check that the case still tests something. If its warning were not raised, or its fix
        // were not a removal, `edits` would have nothing to hold back and the assertion below would
        // pass however `edits` behaved.
        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}"
        );
    }
}

/// `tariff::fix` removes the earlier occurrence first, for `schema::Warning::DuplicateField`, and
/// removes the occurrence that is used on a later pass. In every case the value used restricts
/// nothing, so the whole `restrictions` object goes.
///
/// `tariff::fix` always passes the schema warnings, so this test also passes without the check in
/// `edits`. What it shows is that holding the removal back does not stop `tariff::fix` from
/// finishing.
#[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}");
    }
}

/// A `min_kwh` of `0` excludes a charging period that starts once the session's consumed energy has
/// gone negative, so removing the bound would change what that session costs. The linter reports
/// the bound and `--fix` leaves it in place.
#[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()]
    );
}