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
//! Tests for the fixing loop: that a fix which only becomes possible once another has been made
//! is reached by a later pass, that a tariff with nothing to fix is left alone, and that the pass
//! limit hands back what the passes that did run produced.

#![allow(
    clippy::panic,
    clippy::unwrap_used,
    reason = "test code with known-structure parsed data"
)]

use crate::{Version, fix, json, tariff, test};

use super::{Fixed, MAX_PASSES, Options, Outcome, UnexpectedFields};

/// A tariff with one restriction, whose `day_of_week` is `{DAYS}`.
const TARIFF: &str = r#"{
  "country_code": "NL",
  "party_id": "TDR",
  "id": "TEST",
  "currency": "EUR",
  "elements": [
    {
      "restrictions": {
        "day_of_week": {DAYS}
      },
      "price_components": [
        {
          "type": "ENERGY",
          "price": 0.25,
          "step_size": 1
        }
      ]
    }
  ],
  "last_updated": "2018-12-17T11:36:01Z"
}"#;

/// A tariff with one restriction, whose whole `restrictions` object is `{RESTRICTIONS}`.
///
/// Separate from [`TARIFF`] because these cases vary the object itself rather than the days
/// inside it, including the case where it holds nothing at all.
const TARIFF_RESTRICTIONS: &str = r#"{
  "country_code": "NL",
  "party_id": "TDR",
  "id": "TEST",
  "currency": "EUR",
  "elements": [
    {
      "restrictions": {RESTRICTIONS},
      "price_components": [
        {
          "type": "ENERGY",
          "price": 0.25,
          "step_size": 1
        }
      ]
    }
  ],
  "last_updated": "2018-12-17T11:36:01Z"
}"#;

/// A `day_of_week` list that is both written in the wrong case and out of order.
///
/// The casing is the schema's finding, one warning per day; the order is the linter's, one
/// warning on the array.
const MISCASED_AND_UNSORTED: &str = r#"["tuesday", "monday"]"#;

#[test]
fn a_fix_that_another_fix_enables_is_reached_by_a_later_pass() {
    test::setup();

    let fixed = fix(&TARIFF.replace("{DAYS}", MISCASED_AND_UNSORTED), MAX_PASSES);

    assert_eq!(fixed.outcome, Outcome::AllFixesApplied);
    assert_eq!(fixed.passes, 2);
    assert_eq!(fixed.edits, 3);
    assert!(
        fixed.source.contains(r#"["MONDAY", "TUESDAY"]"#),
        "{}",
        fixed.source
    );
}

#[test]
fn a_tariff_with_nothing_to_fix_is_returned_unchanged() {
    test::setup();

    let source = TARIFF.replace("{DAYS}", r#"["MONDAY", "TUESDAY"]"#);
    let fixed = fix(&source, MAX_PASSES);

    assert_eq!(fixed.outcome, Outcome::AllFixesApplied);
    assert_eq!(fixed.passes, 0);
    assert_eq!(fixed.edits, 0);
    assert_eq!(fixed.source, source);
}

#[test]
fn the_pass_limit_hands_back_the_last_pass_that_ran() {
    test::setup();

    let fixed = fix(&TARIFF.replace("{DAYS}", MISCASED_AND_UNSORTED), 1);

    assert_eq!(fixed.outcome, Outcome::FixLimit);
    assert_eq!(fixed.passes, 1);
    assert_eq!(fixed.edits, 2);
    assert!(
        fixed.source.contains(r#"["TUESDAY", "MONDAY"]"#),
        "{}",
        fixed.source
    );
}

#[test]
fn one_pass_fixes_the_schema_warnings_and_the_lint_warnings_together() {
    test::setup();

    let source = TARIFF
        .replace("{DAYS}", r#"["TUESDAY", "MONDAY", "TUESDAY"]"#)
        .replace(
            r#""currency": "EUR","#,
            "\"currency\": \"EUR\",\n  \"tariff_alt_url\": null,",
        );

    let fixed = fix(&source, MAX_PASSES);

    assert_eq!(fixed.outcome, Outcome::AllFixesApplied);
    assert_eq!(fixed.passes, 1);
    assert!(!fixed.source.contains("tariff_alt_url"), "{}", fixed.source);
    assert!(
        fixed.source.contains(r#"["MONDAY", "TUESDAY"]"#),
        "{}",
        fixed.source
    );
}

#[test]
fn an_unexpected_field_is_removed_when_that_is_asked_for() {
    test::setup();

    let fixed = fix(&unexpected_field_tariff(), MAX_PASSES);

    assert_eq!(fixed.outcome, Outcome::AllFixesApplied);
    assert_eq!(fixed.edits, 1);
    assert!(!fixed.source.contains("surprise"), "{}", fixed.source);
}

#[test]
fn an_unexpected_field_is_left_in_place_by_default() {
    test::setup();

    let source = unexpected_field_tariff();
    let fixed = fix_with(&source, Options::default(), MAX_PASSES);

    assert_eq!(fixed.outcome, Outcome::AllFixesApplied);
    assert_eq!(fixed.edits, 0);
    assert_eq!(fixed.source, source);
}

/// The walk reports `dayOfWeek` as a misspelling of `day_of_week` rather than as unexpected, so
/// `UnexpectedFields::Remove` leaves it in place.
#[test]
fn a_misspelled_field_is_kept_when_unexpected_fields_are_removed() {
    test::setup();

    let source = TARIFF.replace(r#""day_of_week": {DAYS}"#, r#""dayOfWeek": ["MONDAY"]"#);
    let fixed = fix(&source, MAX_PASSES);

    assert_eq!(fixed.edits, 0);
    assert_eq!(fixed.source, source);
}

/// The walk treats `"day_of_week": null` as absent, so it reports `dayOfWeek` as a misspelling
/// rather than as unexpected. `--fix` then removes only the `null` field, even when the caller asks
/// for unexpected fields to be removed.
#[test]
fn a_misspelled_field_beside_a_null_one_is_kept() {
    test::setup();

    let source = TARIFF.replace(
        r#""day_of_week": {DAYS}"#,
        r#""day_of_week": null, "dayOfWeek": ["MONDAY"]"#,
    );
    let fixed = fix(&source, MAX_PASSES);

    assert_eq!(fixed.edits, 1);
    assert!(
        fixed.source.contains(r#""dayOfWeek": ["MONDAY"]"#),
        "{}",
        fixed.source
    );
    assert!(!fixed.source.contains("null"), "{}", fixed.source);
}

/// A field whose name has an escape that fails to decode doesn't match any field the schema lists.
/// `lint --fix` removes the field when the caller asks for unexpected fields to be removed.
#[test]
fn a_field_with_a_malformed_name_is_removed_with_the_unexpected_fields() {
    test::setup();

    let source = TARIFF
        .replace("{DAYS}", r#"["MONDAY", "TUESDAY"]"#)
        .replace(r#""currency": "EUR","#, r#""currency": "EUR", "x\q": 1,"#);
    let fixed = fix(&source, MAX_PASSES);

    assert_eq!(fixed.outcome, Outcome::AllFixesApplied);
    assert_eq!(fixed.edits, 1);
    assert!(!fixed.source.contains(r"x\q"), "{}", fixed.source);
}

/// A name that still needs an escape once rewritten is left as it is, so the fixing loop ends. The
/// test keeps unexpected fields, because removing this one would end the loop whatever the fix
/// proposes for its name.
#[test]
fn a_field_name_that_needs_an_escape_is_left_in_place() {
    test::setup();

    let source = TARIFF
        .replace("{DAYS}", r#"["MONDAY", "TUESDAY"]"#)
        .replace(
            r#""currency": "EUR","#,
            r#""currency": "EUR", "x\u0022y": 1,"#,
        );
    let fixed = fix_with(&source, Options::default(), MAX_PASSES);

    assert_eq!(fixed.outcome, Outcome::AllFixesApplied);
    assert_eq!(fixed.edits, 0);
    assert_eq!(fixed.source, source);
}

/// An object the author wrote empty restricts nothing, so one pass removes it.
#[test]
fn an_object_written_empty_is_removed_in_one_pass() {
    test::setup();

    let fixed = fix(
        &TARIFF_RESTRICTIONS.replace("{RESTRICTIONS}", "{}"),
        MAX_PASSES,
    );

    assert_eq!(fixed.outcome, Outcome::AllFixesApplied);
    assert_eq!(fixed.passes, 1);
    assert_eq!(fixed.edits, 1);
    assert!(!fixed.source.contains("restrictions"), "{}", fixed.source);
}

/// The case the loop exists for: the object is not empty as written, so the first pass
/// cannot see it. Removing the `null` empties it and the second pass is what removes the object.
#[test]
fn an_object_emptied_by_an_earlier_fix_is_removed_by_a_later_pass() {
    test::setup();

    let fixed = fix(
        &TARIFF_RESTRICTIONS.replace("{RESTRICTIONS}", r#"{ "min_kwh": null }"#),
        MAX_PASSES,
    );

    assert_eq!(fixed.outcome, Outcome::AllFixesApplied);
    assert_eq!(fixed.passes, 2);
    assert_eq!(fixed.edits, 2);
    assert!(!fixed.source.contains("restrictions"), "{}", fixed.source);
}

/// `MONDAI` is one edit from `MONDAY` and from no other day, so parsing reports it as a
/// `MisspelledValue` with one variant, and the fix rewrites it to `MONDAY`. This test and the next
/// share that input. The rewrite changes what the tariff means.
#[test]
fn an_edit_that_changes_the_meaning_is_held_back_by_default() {
    test::setup();

    let tariff = TARIFF.replace("{DAYS}", r#"["MONDAI", "TUESDAY"]"#);
    let fixed = fix(&tariff, MAX_PASSES);

    assert_eq!(fixed.outcome, Outcome::AllFixesApplied);
    assert_eq!(fixed.source, tariff);
    assert_eq!(fixed.edits, 0);
    assert_eq!(fixed.changes_held_back, 1);
}

#[test]
fn an_edit_that_changes_the_meaning_is_applied_when_that_is_asked_for() {
    test::setup();

    let tariff = TARIFF.replace("{DAYS}", r#"["MONDAI", "TUESDAY"]"#);
    let options = Options::default()
        .unexpected_fields(UnexpectedFields::Remove)
        .allow_changes();
    let fixed = fix_with(&tariff, options, MAX_PASSES);

    assert_eq!(fixed.outcome, Outcome::AllFixesApplied);
    assert_eq!(
        fixed.source,
        TARIFF.replace("{DAYS}", r#"["MONDAY", "TUESDAY"]"#)
    );
    assert_eq!(fixed.edits, 1);
    assert_eq!(fixed.changes_held_back, 0);
}

/// `day\u004ffWeek` decodes to `dayOfWeek`, so the escape fix and the misspelling's fix
/// both propose a rename of the same key. `apply` can't make two renames of one key that write
/// different text. So the first pass makes only the escape fix's rename, which keeps the meaning,
/// and the second pass makes the misspelling's rename.
#[test]
fn a_field_name_both_escaped_and_misspelled_is_renamed_over_two_passes() {
    test::setup();

    let tariff =
        TARIFF_RESTRICTIONS.replace("{RESTRICTIONS}", r#"{ "day\u004ffWeek": ["MONDAY"] }"#);
    let fixed = fix_with(&tariff, allowing_changes(), MAX_PASSES);

    assert_eq!(fixed.outcome, Outcome::AllFixesApplied);
    assert_eq!(
        fixed.source,
        TARIFF_RESTRICTIONS.replace("{RESTRICTIONS}", r#"{ "day_of_week": ["MONDAY"] }"#)
    );
    assert_eq!(fixed.passes, 2);
}

/// The schema walk treats a `null` field as absent, so it reports `dayOfWeek` as a
/// misspelling of `day_of_week`. The fix removes the last of the two `null` fields only once the
/// first is gone. Until then the object still holds a `day_of_week`, so fixing refuses the
/// rename for that pass, and the fixed tariff keeps the author's days. A later pass makes the
/// rename, so `Fixed::refused` doesn't list it.
#[test]
fn a_misspelled_field_is_not_renamed_onto_a_key_the_object_keeps() {
    test::setup();

    let tariff = TARIFF_RESTRICTIONS.replace(
        "{RESTRICTIONS}",
        r#"{ "dayOfWeek": ["MONDAY"], "day_of_week": null, "day_of_week": null }"#,
    );
    let fixed = fix_with(&tariff, allowing_changes(), MAX_PASSES);

    assert_eq!(fixed.outcome, Outcome::AllFixesApplied);
    assert_eq!(
        fixed.source,
        TARIFF_RESTRICTIONS.replace("{RESTRICTIONS}", r#"{ "day_of_week": ["MONDAY"] }"#)
    );
    assert_eq!(fixed.refused, vec![]);
}

/// The first pass removes the `null` field, whose name `day\u005fof_week` the escape fix
/// would also rewrite to `day_of_week`. `fix::edits` ignores the rename of a field the pass
/// removes, so `dayOfWeek` takes the name `day_of_week` in the same pass.
#[test]
fn a_misspelled_field_takes_the_key_of_a_removed_field_in_one_pass() {
    test::setup();

    let tariff = TARIFF_RESTRICTIONS.replace(
        "{RESTRICTIONS}",
        r#"{ "day\u005fof_week": null, "dayOfWeek": ["MONDAY"] }"#,
    );
    let fixed = fix_with(&tariff, allowing_changes(), MAX_PASSES);

    assert_eq!(fixed.outcome, Outcome::AllFixesApplied);
    assert_eq!(
        fixed.source,
        TARIFF_RESTRICTIONS.replace("{RESTRICTIONS}", r#"{ "day_of_week": ["MONDAY"] }"#)
    );
    assert_eq!(fixed.passes, 1);
}

/// A misspelled field holding `null` records nothing, so removing it keeps the meaning,
/// and fixing it needs no `--allow-changes`.
#[test]
fn a_misspelled_field_holding_null_is_removed_without_allowing_changes() {
    test::setup();

    let tariff =
        TARIFF_RESTRICTIONS.replace("{RESTRICTIONS}", r#"{ "dayOfWeek": null, "max_kwh": 5 }"#);
    let fixed = fix(&tariff, MAX_PASSES);

    assert_eq!(fixed.outcome, Outcome::AllFixesApplied);
    assert_eq!(
        fixed.source,
        TARIFF_RESTRICTIONS.replace("{RESTRICTIONS}", r#"{ "max_kwh": 5 }"#)
    );
    assert_eq!(fixed.changes_held_back, 0);
}

/// Both fields are misspellings of `day_of_week`. The first pass removes the one holding
/// `null`, so the other no longer shares its new name and is renamed in the same pass.
#[test]
fn a_misspelled_field_holding_null_does_not_block_its_sibling_rename() {
    test::setup();

    let tariff = TARIFF_RESTRICTIONS.replace(
        "{RESTRICTIONS}",
        r#"{ "dayOfWeek": null, "DayOfWeek": ["MONDAY"] }"#,
    );
    let fixed = fix_with(&tariff, allowing_changes(), MAX_PASSES);

    assert_eq!(fixed.outcome, Outcome::AllFixesApplied);
    assert_eq!(
        fixed.source,
        TARIFF_RESTRICTIONS.replace("{RESTRICTIONS}", r#"{ "day_of_week": ["MONDAY"] }"#)
    );
    assert_eq!(fixed.passes, 1);
}

/// Both fields are misspellings of `day_of_week`, and nothing says which value the author
/// meant. `lint --fix` relies on `Fixed::refused` to tell the user why it left both alone.
#[test]
fn two_fields_misspelling_one_name_are_both_refused() {
    test::setup();

    let tariff = TARIFF_RESTRICTIONS.replace(
        "{RESTRICTIONS}",
        r#"{ "dayOfWeek": ["MONDAY"], "DayOfWeek": ["SUNDAY"] }"#,
    );
    let fixed = fix_with(&tariff, allowing_changes(), MAX_PASSES);

    assert_eq!(fixed.outcome, Outcome::AllFixesApplied);
    assert_eq!(fixed.source, tariff);
    assert_eq!(fixed.edits, 0);
    assert_eq!(fixed.changes_held_back, 0);
    assert_eq!(
        refused(&fixed),
        vec![
            (
                "$.elements[0].restrictions.dayOfWeek",
                "misspelled_field(day_of_week)",
                fix::Refusal::RenameClashes
            ),
            (
                "$.elements[0].restrictions.DayOfWeek",
                "misspelled_field(day_of_week)",
                fix::Refusal::RenameClashes
            ),
        ]
    );
}

/// Even with changes allowed, fixing doesn't apply a refused rename. So with the default
/// options the rename belongs in `Fixed::refused`, not in `Fixed::changes_held_back`, whose count
/// tells the user to pass `--allow-changes`.
#[test]
fn a_refused_rename_is_not_held_back_by_default() {
    test::setup();

    let tariff = TARIFF_RESTRICTIONS.replace(
        "{RESTRICTIONS}",
        r#"{ "dayOfWeek": ["MONDAY"], "DayOfWeek": ["SUNDAY"] }"#,
    );
    let fixed = fix(&tariff, MAX_PASSES);

    assert_eq!(fixed.changes_held_back, 0);
    assert_eq!(fixed.refused.len(), 2);
}

/// Returns each refused fix in `fixed` as its path, its warning's id and its reason, so a
/// test can compare the list with literals.
fn refused(fixed: &Fixed) -> Vec<(&str, &str, fix::Refusal)> {
    fixed
        .refused
        .iter()
        .map(|refused| {
            (
                refused.path.as_str(),
                refused.warning.as_str(),
                refused.reason,
            )
        })
        .collect()
}

/// The options that remove unexpected fields and allow the fixes that change what a tariff means.
fn allowing_changes() -> Options {
    Options::default()
        .unexpected_fields(UnexpectedFields::Remove)
        .allow_changes()
}

/// A tariff whose only fault is one field the OCPI spec does not define.
fn unexpected_field_tariff() -> String {
    TARIFF
        .replace("{DAYS}", r#"["MONDAY", "TUESDAY"]"#)
        .replace(
            r#""currency": "EUR","#,
            "\"currency\": \"EUR\",\n  \"surprise\": \"not in the spec\",",
        )
}

/// Fix the tariff in `json` within `max_passes`, removing the fields no OCPI version defines.
#[track_caller]
fn fix(json: &str, max_passes: usize) -> Fixed {
    fix_with(
        json,
        Options::default().unexpected_fields(UnexpectedFields::Remove),
        max_passes,
    )
}

/// Fix the tariff in `json` within `max_passes`, applying the fixes `options` allows.
#[track_caller]
fn fix_with(json: &str, options: Options, max_passes: usize) -> Fixed {
    let doc = json::parse_object(json).expect("the tariff parses");
    let (tariff, _warnings) = tariff::from_json(doc, Version::V221).into_parts();

    super::fix_until_no_edits(tariff.as_json_str(), Version::V221, options, max_passes)
        .expect("the fixes apply")
}