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
//! Tests for [`Fixable`] as `schema::Warning` implements it: which schema warnings a
//! mechanical edit resolves, and which are left for the document's author.

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

use crate::{Version, Warning as _, json, schema, tariff, test, warning};

use super::{Edit, Fixable as _, Meaning, apply, edits};

/// Validate `json` as a v2.2.1 tariff and return it with its schema warnings.
///
/// The tariff keeps the [`json::Document`] alive, reachable through `as_doc`, which is what
/// turns the `ElemId` on a warning back into the element the edit applies to.
fn validated(json: &str) -> (tariff::Versioned<'_>, warning::Set<schema::Warning>) {
    let doc = json::parse_object(json).unwrap();

    tariff::from_json(doc, Version::V221).into_parts()
}

/// A parsed document and the element of its only field, which the warnings are raised on.
fn only_field(json: &str) -> (json::Document<'_>, json::ElemId) {
    let doc = json::parse_object(json).unwrap();
    let id = doc.root().find_field("a").unwrap().element().id();

    (doc, id)
}

#[test]
fn a_null_field_is_removed() {
    let (doc, id) = only_field(r#"{"a": null}"#);
    let element = doc.element(id).unwrap();

    assert_eq!(
        schema::Warning::NullField.fix(element),
        Some(Edit::remove(id, Meaning::Preserves))
    );
}

#[test]
fn an_unexpected_field_is_removed() {
    let (doc, id) = only_field(r#"{"a": 1}"#);
    let element = doc.element(id).unwrap();

    assert_eq!(
        schema::Warning::UnexpectedField.fix(element),
        Some(Edit::remove(id, Meaning::Preserves))
    );
}

/// The library reads a non-spec field, so removing it would change how a document prices.
#[test]
fn a_non_spec_field_is_left_alone() {
    let (doc, id) = only_field(r#"{"a": 1}"#);
    let element = doc.element(id).unwrap();

    assert_eq!(schema::Warning::NonSpecField.fix(element), None);
}

#[test]
fn a_miscased_enum_value_is_rewritten_in_the_spec_case() {
    let (doc, id) = only_field(r#"{"a": "energy"}"#);
    let element = doc.element(id).unwrap();

    let warning = schema::Warning::IncorrectCase {
        expected: "ENERGY",
        actual: "energy".to_owned(),
    };

    assert_eq!(
        warning.fix(element),
        Some(Edit::replace(
            id,
            super::Json::string("ENERGY"),
            Meaning::Preserves
        ))
    );
}

#[test]
fn a_date_without_leading_zeros_is_rewritten_as_yyyy_mm_dd() {
    let (doc, id) = only_field(r#"{"a": "2023-1-5"}"#);
    let element = doc.element(id).unwrap();

    let warning = schema::Warning::IncorrectFormat {
        expected: "2023-01-05".to_owned(),
        actual: "2023-1-5".to_owned(),
    };

    assert_eq!(
        warning.fix(element),
        Some(Edit::replace(
            id,
            super::Json::string("2023-01-05"),
            Meaning::Preserves
        ))
    );
}

/// The whole round trip over a tariff whose `start_date` has no leading zeros: validate, propose,
/// apply.
#[test]
fn a_tariff_has_its_restriction_date_written_as_yyyy_mm_dd() {
    const TARIFF: &str = r#"{
  "country_code": "NL",
  "party_id": "TDR",
  "id": "TEST",
  "currency": "EUR",
  "elements": [
    {
      "restrictions": {
        "start_date": "2023-1-5"
      },
      "price_components": [
        {
          "type": "ENERGY",
          "price": 0.38,
          "step_size": 1
        }
      ]
    }
  ],
  "last_updated": "2020-01-01T00:00:00Z"
}"#;

    test::setup();

    let (tariff, warnings) = validated(TARIFF);
    let doc = tariff.as_doc();
    let proposed = edits(doc, &warnings).unwrap();
    let fixed = apply(doc, &proposed).unwrap();

    assert_eq!(fixed, TARIFF.replace(r#""2023-1-5""#, r#""2023-01-05""#));
}

/// The whole round trip over a tariff whose `type` is miscased: validate, propose, apply.
#[test]
fn a_tariff_has_its_miscased_enum_value_rewritten() {
    const TARIFF: &str = r#"{
  "country_code": "NL",
  "party_id": "TDR",
  "id": "TEST",
  "currency": "EUR",
  "elements": [
    {
      "price_components": [
        {
          "type": "energy",
          "price": 0.38,
          "step_size": 1
        }
      ]
    }
  ],
  "last_updated": "2020-01-01T00:00:00Z"
}"#;

    test::setup();

    let (tariff, warnings) = validated(TARIFF);
    let doc = tariff.as_doc();
    let proposed = edits(doc, &warnings).unwrap();
    let fixed = apply(doc, &proposed).unwrap();

    assert_eq!(fixed, TARIFF.replace(r#""energy""#, r#""ENERGY""#));
}

#[test]
fn a_field_name_with_escapes_is_rewritten_without_them() {
    let doc = json::parse_object(r#"{"min\u005fkwh": 1}"#).unwrap();
    let element = doc.root().as_object_fields().unwrap()[0].element();

    assert_eq!(
        schema::Warning::FieldNameContainsEscapeCodes.fix(element),
        Some(Edit::rename(
            element.id(),
            super::Json::string("min_kwh"),
            Meaning::Preserves
        ))
    );
}

/// JSON can write `a"b` only with an escape, so renaming this field writes `"a\"b"`. The
/// walk raises the warning for any escape, so it raises the warning again. The next pass decodes
/// `"a\"b"` and proposes a rename to the name the field already has. The fixing loop stops only
/// when a pass proposes no edit, so it would repeat that rename until it reached its limit. The
/// fix proposes nothing for a name JSON can't write without an escape.
#[test]
fn a_field_name_that_needs_an_escape_is_left_alone() {
    let doc = json::parse_object(r#"{"a\u0022b": 1}"#).unwrap();
    let element = doc.root().as_object_fields().unwrap()[0].element();

    assert_eq!(
        schema::Warning::FieldNameContainsEscapeCodes.fix(element),
        None
    );
}

/// The fixing loop holds this rewrite back unless the caller allows changes.
/// The edit's `Meaning` signals that to the loop.
#[test]
fn a_misspelled_enum_value_is_rewritten_as_a_change_of_meaning() {
    let (doc, id) = only_field(r#"{"a": "MONDAI"}"#);
    let element = doc.element(id).unwrap();

    let warning = schema::Warning::MisspelledValue {
        expected: vec!["MONDAY"],
        actual: "MONDAI".to_owned(),
    };

    assert_eq!(
        warning.fix(element),
        Some(Edit::replace(
            id,
            super::Json::string("MONDAY"),
            Meaning::Changes
        ))
    );
}

/// Only the author can choose between variants that are equally near.
#[test]
fn an_enum_value_equally_near_two_variants_is_left_alone() {
    let (doc, id) = only_field(r#"{"a": "IEC_62196_T"}"#);
    let element = doc.element(id).unwrap();

    let warning = schema::Warning::MisspelledValue {
        expected: vec!["IEC_62196_T1", "IEC_62196_T2"],
        actual: "IEC_62196_T".to_owned(),
    };

    assert_eq!(warning.fix(element), None);
}

/// The fixing loop holds this rename back unless the caller allows changes.
/// The edit's `Meaning` signals that to the loop.
#[test]
fn a_misspelled_field_is_renamed_as_a_change_of_meaning() {
    let doc = json::parse_object(r#"{"dayOfWeek": ["MONDAY"]}"#).unwrap();
    let element = doc.root().as_object_fields().unwrap()[0].element();

    let warning = schema::Warning::MisspelledField {
        expected: vec!["day_of_week"],
    };

    assert_eq!(
        warning.fix(element),
        Some(Edit::rename(
            element.id(),
            super::Json::string("day_of_week"),
            Meaning::Changes
        ))
    );
}

/// Only the author can choose between fields that are equally near.
#[test]
fn a_field_equally_near_two_fields_is_left_alone() {
    let doc = json::parse_object(r#"{"man_kwh": 1}"#).unwrap();
    let element = doc.root().as_object_fields().unwrap()[0].element();

    let warning = schema::Warning::MisspelledField {
        expected: vec!["min_kwh", "max_kwh"],
    };

    assert_eq!(warning.fix(element), None);
}

/// Renaming both fields would write `day_of_week` twice in one object.
/// Nothing says which of the two the author meant, so `fix::edits` proposes neither rename.
#[test]
fn two_fields_misspelling_one_field_are_both_left_alone() {
    const TARIFF: &str = r#"{
  "country_code": "NL",
  "party_id": "TDR",
  "id": "TEST",
  "currency": "EUR",
  "elements": [
    {
      "restrictions": {
        "dayOfWeek": ["MONDAY"],
        "DayOfWeek": ["SUNDAY"]
      },
      "price_components": [
        {
          "type": "ENERGY",
          "price": 0.38,
          "step_size": 1
        }
      ]
    }
  ],
  "last_updated": "2020-01-01T00:00:00Z"
}"#;

    test::setup();

    let (tariff, warnings) = validated(TARIFF);
    let doc = tariff.as_doc();
    let misspelled = warnings
        .iter()
        .flat_map(|group| group.to_parts().1)
        .filter(|warning| matches!(warning, schema::Warning::MisspelledField { expected: _ }))
        .count();
    assert_eq!(misspelled, 2, "the premise: both fields are reported");

    assert_eq!(edits(doc, &warnings).unwrap(), Vec::new());
}

#[test]
fn a_warning_needing_a_human_decision_proposes_nothing() {
    let (doc, id) = only_field(r#"{"a": 1}"#);
    let element = doc.element(id).unwrap();

    let unfixable = [
        schema::Warning::MissingField { name: "currency" },
        schema::Warning::Cardinality,
    ];

    for warning in unfixable {
        assert_eq!(warning.fix(element), None, "for `{warning:?}`");
    }
}

/// The whole round trip: validate a tariff, propose the edits, apply them.
#[test]
fn a_tariff_loses_its_null_and_unexpected_fields() {
    const TARIFF: &str = r#"{
  "country_code": "NL",
  "party_id": "TDR",
  "id": "TEST",
  "currency": "EUR",
  "tariff_alt_url": null,
  "made_up_field": "nonsense",
  "elements": [
    {
      "price_components": [
        {
          "type": "ENERGY",
          "price": 0.38,
          "step_size": 1
        }
      ]
    }
  ],
  "last_updated": "2020-01-01T00:00:00Z"
}"#;

    test::setup();

    let (tariff, warnings) = validated(TARIFF);
    let doc = tariff.as_doc();
    let proposed = edits(doc, &warnings).unwrap();
    let fixed = apply(doc, &proposed).unwrap();

    assert!(
        !fixed.contains("tariff_alt_url") && !fixed.contains("made_up_field"),
        "both fields should be gone, got:\n{fixed}"
    );

    // Everything the schema does define is still there, formatting and all.
    assert!(fixed.contains("\"currency\": \"EUR\""), "got:\n{fixed}");
    assert!(fixed.contains("\"price\": 0.38"), "got:\n{fixed}");

    // The fixed tariff has neither warning left.
    let (_tariff, after) = validated(&fixed);
    let remaining: Vec<String> = after
        .iter()
        .flat_map(|group| group.warnings())
        .map(|warning| warning.id().as_str().to_owned())
        .collect();

    assert_eq!(remaining, Vec::<String>::new());
}

/// Filtering the set is how a caller declines a fix, so the trait never has to know.
#[test]
fn filtering_the_set_leaves_the_unexpected_field_in_place() {
    const TARIFF: &str = r#"{"made_up_field": "nonsense", "currency": null}"#;

    test::setup();

    let (tariff, mut warnings) = validated(TARIFF);
    warnings.remove_unexpected_fields();

    let doc = tariff.as_doc();
    let proposed = edits(doc, &warnings).unwrap();
    let fixed = apply(doc, &proposed).unwrap();

    assert_eq!(fixed, r#"{"made_up_field": "nonsense"}"#.to_owned());
}

/// The `null` is the occurrence that is used, so the element has no `max_kwh` bound. Removing the
/// `null` while the earlier `5` is still there would bound the element at 5 kWh. `edits` proposes
/// removing the earlier occurrence, for `DuplicateField`, and leaves the `null` for the next pass.
#[test]
fn a_null_field_stays_while_an_earlier_field_has_its_key() {
    test::setup();

    let restrictions = r#""restrictions": {"max_kwh": 5, "max_kwh": null}"#;
    let source = format!(
        r#"{{"country_code": "NL", "party_id": "TDR", "id": "T", "currency": "EUR",
"elements": [{{{restrictions}, "price_components": [{{"type": "ENERGY", "price": 0.38, "step_size": 1}}]}}],
"last_updated": "2020-01-01T00:00:00Z"}}"#
    );
    let (tariff, warnings) = validated(&source);
    let doc = tariff.as_doc();
    let proposed = edits(doc, &warnings).unwrap();
    let fixed = apply(doc, &proposed).unwrap();

    assert_eq!(
        fixed,
        source.replace(restrictions, r#""restrictions": {"max_kwh": null}"#)
    );
}

/// Every occurrence of `max_kwh` but the last raises `DuplicateField`. The last occurrence is the
/// one used, so removing any of the others is safe, and `edits` proposes all of them in one pass. A
/// check that held back every field whose key an earlier field shares would hold back `2` and `3`
/// as well, removing one occurrence per pass until `tariff::fix` ran out of passes.
#[test]
fn every_superseded_occurrence_is_removed_in_one_pass() {
    test::setup();

    let restrictions =
        r#""restrictions": {"max_kwh": 1, "max_kwh": 2, "max_kwh": 3, "max_kwh": 4}"#;
    let source = format!(
        r#"{{"country_code": "NL", "party_id": "TDR", "id": "T", "currency": "EUR",
"elements": [{{{restrictions}, "price_components": [{{"type": "ENERGY", "price": 0.38, "step_size": 1}}]}}],
"last_updated": "2020-01-01T00:00:00Z"}}"#
    );
    let (tariff, warnings) = validated(&source);
    let doc = tariff.as_doc();
    let proposed = edits(doc, &warnings).unwrap();
    let fixed = apply(doc, &proposed).unwrap();

    assert_eq!(
        fixed,
        source.replace(restrictions, r#""restrictions": {"max_kwh": 4}"#)
    );
}