ocpi-tariffs 0.55.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
517
518
519
520
521
522
523
524
525
526
527
528
529
530
//! Tests for [`apply`]: splicing a set of [`Edit`]s into a document's source.

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

use std::{
    assert_matches,
    time::{Duration, Instant},
};

use crate::json;

use super::{Edit, Error, Json, Meaning, Splice, apply, splice};

fn parsed(s: &str) -> json::Document<'_> {
    json::parse(s.into()).unwrap()
}

fn field_id(element: &json::Element<'_>, key: &str) -> json::ElemId {
    element.find_field(key).unwrap().element().id()
}

fn item_id(element: &json::Element<'_>, index: usize) -> json::ElemId {
    element.as_array().unwrap()[index].id()
}

/// The payloads here are whole JSON values rather than string content, since what is under test is
/// the splicing and not the writing, so they go in verbatim.
fn replace(elem: json::ElemId, json: &str) -> Edit {
    Edit::replace(elem, Json::raw(json), Meaning::Preserves)
}

#[test]
fn no_edits_leave_the_source_alone() {
    let source = r#"{"a": 1, "b": 2}"#;
    let doc = parsed(source);

    assert_eq!(apply(&doc, &[]), Ok(source.to_owned()));
}

#[test]
fn remove_a_field() {
    let source = r#"{"a": 1, "b": 2}"#;
    let doc = parsed(source);
    let edits = [Edit::remove(field_id(doc.root(), "a"), Meaning::Preserves)];

    assert_eq!(apply(&doc, &edits), Ok(r#"{"b": 2}"#.to_owned()));
}

#[test]
fn replace_a_value_and_keep_the_key() {
    let source = r#"{"min_duration": 1.5, "b": 2}"#;
    let doc = parsed(source);
    let edits = [replace(field_id(doc.root(), "min_duration"), "2")];

    assert_eq!(
        apply(&doc, &edits),
        Ok(r#"{"min_duration": 2, "b": 2}"#.to_owned())
    );
}

#[test]
fn replace_a_scalar_with_an_object() {
    let source = r#"{"a": 1, "b": 2}"#;
    let doc = parsed(source);
    let edits = [replace(field_id(doc.root(), "a"), r#"{"c": [3]}"#)];

    assert_eq!(
        apply(&doc, &edits),
        Ok(r#"{"a": {"c": [3]}, "b": 2}"#.to_owned())
    );
}

#[test]
fn replace_an_array_item() {
    let source = "[1, 2, 3]";
    let doc = parsed(source);
    let edits = [replace(item_id(doc.root(), 1), "20")];

    assert_eq!(apply(&doc, &edits), Ok("[1, 20, 3]".to_owned()));
}

/// Every span is resolved against the original source, so a replacement that is longer than
/// the text it replaces must not shift the edits that come after it.
#[test]
fn a_longer_replacement_does_not_shift_later_edits() {
    let source = r#"{"a": 1, "b": 2, "c": 3}"#;
    let doc = parsed(source);
    let edits = [
        replace(
            field_id(doc.root(), "a"),
            r#""a much longer value than before""#,
        ),
        Edit::remove(field_id(doc.root(), "c"), Meaning::Preserves),
    ];

    assert_eq!(
        apply(&doc, &edits),
        Ok(r#"{"a": "a much longer value than before", "b": 2}"#.to_owned())
    );
}

#[test]
fn remove_and_replace_different_elements() {
    let source = r#"{"a": 1, "b": 2, "c": 3}"#;
    let doc = parsed(source);
    let edits = [
        Edit::remove(field_id(doc.root(), "a"), Meaning::Preserves),
        replace(field_id(doc.root(), "c"), "30"),
    ];

    assert_eq!(apply(&doc, &edits), Ok(r#"{"b": 2, "c": 30}"#.to_owned()));
}

/// Two warnings on one element can each ask for it to go; it is removed once.
#[test]
fn removing_the_same_element_twice_removes_it_once() {
    let source = r#"{"a": 1, "b": 2}"#;
    let doc = parsed(source);
    let id = field_id(doc.root(), "a");
    let edits = [
        Edit::remove(id, Meaning::Preserves),
        Edit::remove(id, Meaning::Preserves),
    ];

    assert_eq!(apply(&doc, &edits), Ok(r#"{"b": 2}"#.to_owned()));
}

#[test]
fn a_removal_makes_a_replacement_of_the_same_element_redundant() {
    let source = r#"{"a": 1, "b": 2}"#;
    let doc = parsed(source);
    let id = field_id(doc.root(), "a");
    let edits = [Edit::remove(id, Meaning::Preserves), replace(id, "99")];

    assert_eq!(apply(&doc, &edits), Ok(r#"{"b": 2}"#.to_owned()));
}

/// A removal of an element makes a pending fix inside it redundant.
#[test]
fn a_removal_makes_a_replacement_nested_inside_it_redundant() {
    let source = r#"{"a": {"max_kwh": 1.5}, "b": 2}"#;
    let doc = parsed(source);
    let outer = doc.root().find_field("a").unwrap().element();
    let edits = [
        Edit::remove(outer.id(), Meaning::Preserves),
        replace(field_id(outer, "max_kwh"), "2"),
    ];

    assert_eq!(apply(&doc, &edits), Ok(r#"{"b": 2}"#.to_owned()));
}

#[test]
fn replacing_the_same_element_twice_is_a_duplicate() {
    let source = r#"{"a": 1}"#;
    let doc = parsed(source);
    let id = field_id(doc.root(), "a");
    let edits = [replace(id, "2"), replace(id, "3")];

    assert_eq!(apply(&doc, &edits), Err(Error::Duplicate(id)));
}

/// Two warnings can describe the same defect from different angles and ask for the same text,
/// which is one edit proposed twice rather than a disagreement about what to write.
#[test]
fn replacing_the_same_element_twice_with_the_same_text_is_not() {
    let source = r#"{"a": 1}"#;
    let doc = parsed(source);
    let id = field_id(doc.root(), "a");
    let edits = [replace(id, "2"), replace(id, "2")];

    assert_eq!(apply(&doc, &edits), Ok(r#"{"a": 2}"#.to_owned()));
}

/// A replacement's payload was written without knowledge of the inner edit, so applying it
/// would discard that edit silently.
#[test]
fn a_replacement_nested_in_a_replacement_is_a_conflict() {
    let source = r#"{"a": {"b": 1}}"#;
    let doc = parsed(source);
    let outer = doc.root().find_field("a").unwrap().element();
    let edits = [
        replace(outer.id(), r#"{"b": 2}"#),
        replace(field_id(outer, "b"), "3"),
    ];

    assert_eq!(
        apply(&doc, &edits),
        Err(Error::Conflict {
            outer: outer.id(),
            inner: field_id(outer, "b"),
        })
    );
}

#[test]
fn a_removal_nested_in_a_replacement_is_a_conflict() {
    let source = r#"{"a": {"b": 1, "c": 2}}"#;
    let doc = parsed(source);
    let outer = doc.root().find_field("a").unwrap().element();
    let edits = [
        replace(outer.id(), r#"{"b": 1}"#),
        Edit::remove(field_id(outer, "c"), Meaning::Preserves),
    ];

    assert_eq!(
        apply(&doc, &edits),
        Err(Error::Conflict {
            outer: outer.id(),
            inner: field_id(outer, "c"),
        })
    );
}

#[test]
fn rename_a_key_and_keep_the_value() {
    let source = r#"{"a\u0062": 1, "c": 2}"#;
    let doc = parsed(source);
    let id = doc.root().as_object_fields().unwrap()[0].element().id();
    let edits = [Edit::rename(id, Json::string("ab"), Meaning::Preserves)];

    assert_eq!(apply(&doc, &edits), Ok(r#"{"ab": 1, "c": 2}"#.to_owned()));
}

/// One field can need both edits, such as `"typ\u0065": "energy"`, whose name has an escape and
/// whose value is miscased.
#[test]
fn a_rename_and_a_replacement_of_the_same_element_both_apply() {
    let source = r#"{"a": 1}"#;
    let doc = parsed(source);
    let id = field_id(doc.root(), "a");
    let edits = [
        Edit::rename(id, Json::string("b"), Meaning::Preserves),
        replace(id, "2"),
    ];

    assert_eq!(apply(&doc, &edits), Ok(r#"{"b": 2}"#.to_owned()));
}

#[test]
fn a_removal_makes_a_rename_of_the_same_element_redundant() {
    let source = r#"{"a": 1, "c": 2}"#;
    let doc = parsed(source);
    let id = field_id(doc.root(), "a");
    let edits = [
        Edit::rename(id, Json::string("b"), Meaning::Preserves),
        Edit::remove(id, Meaning::Preserves),
    ];

    assert_eq!(apply(&doc, &edits), Ok(r#"{"c": 2}"#.to_owned()));
}

/// A removal makes a rename redundant for every field nested inside the removed element, not only
/// for the removed field itself.
#[test]
fn a_removal_makes_a_rename_nested_inside_it_redundant() {
    let source = r#"{"a": {"b": 1}, "c": 2}"#;
    let doc = parsed(source);
    let outer = doc.root().find_field("a").unwrap().element();
    let edits = [
        Edit::remove(outer.id(), Meaning::Preserves),
        Edit::rename(field_id(outer, "b"), Json::string("d"), Meaning::Preserves),
    ];

    assert_eq!(apply(&doc, &edits), Ok(r#"{"c": 2}"#.to_owned()));
}

#[test]
fn renaming_the_same_element_twice_is_a_duplicate() {
    let source = r#"{"a": 1}"#;
    let doc = parsed(source);
    let id = field_id(doc.root(), "a");
    let edits = [
        Edit::rename(id, Json::string("b"), Meaning::Preserves),
        Edit::rename(id, Json::string("c"), Meaning::Preserves),
    ];

    assert_eq!(apply(&doc, &edits), Err(Error::Duplicate(id)));
}

#[test]
fn a_rename_nested_in_a_replacement_is_a_conflict() {
    let source = r#"{"a": {"b": 1}}"#;
    let doc = parsed(source);
    let outer = doc.root().find_field("a").unwrap().element();
    let edits = [
        replace(outer.id(), r#"{"b": 2}"#),
        Edit::rename(field_id(outer, "b"), Json::string("c"), Meaning::Preserves),
    ];

    assert_eq!(
        apply(&doc, &edits),
        Err(Error::Conflict {
            outer: outer.id(),
            inner: field_id(outer, "b"),
        })
    );
}

#[test]
fn renaming_an_array_item_is_reported() {
    let source = r#"{"a": [1]}"#;
    let doc = parsed(source);
    let item = item_id(doc.root().find_field("a").unwrap().element(), 0);
    let edits = [Edit::rename(item, Json::string("b"), Meaning::Preserves)];

    assert_eq!(apply(&doc, &edits), Err(Error::NotAField(item)));
}

/// An object field has room for one value. Several items written over a field value
/// aren't JSON, and the re-parse in `apply` reports them as a bug in this module.
#[test]
fn replacing_a_field_value_with_several_items_is_reported() {
    let source = r#"{"a": 1}"#;
    let doc = parsed(source);
    let value = field_id(doc.root(), "a");
    let items = Json::items(&["1".to_owned(), "2".to_owned()], ", ");
    let edits = [Edit::replace_with_items(value, items, Meaning::Preserves)];

    assert_matches!(apply(&doc, &edits), Err(Error::Internal(_)));
}

#[test]
fn an_id_from_beyond_the_document_is_reported() {
    let source = r#"{"a": 1}"#;
    let doc = parsed(source);
    let unknown = json::ElemId::from(99);
    let edits = [replace(unknown, "2")];

    assert_eq!(apply(&doc, &edits), Err(Error::UnknownElement(unknown)));
}

#[test]
fn removing_the_root_is_reported() {
    let source = r#"{"a": 1}"#;
    let doc = parsed(source);
    let edits = [Edit::remove(doc.root().id(), Meaning::Preserves)];

    assert_eq!(
        apply(&doc, &edits),
        Err(Error::Removal(json::RemovalError::Root))
    );
}

/// Resolution is meant to make this unreachable, so the spans are handed to `splice` directly.
#[test]
fn overlapping_spans_are_reported_rather_than_spliced() {
    let source = r#"{"a": 1, "b": 2}"#;
    let first = json::Span { start: 1, end: 7 };
    let second = json::Span { start: 4, end: 9 };
    let splices = [
        Splice {
            span: first,
            text: "",
        },
        Splice {
            span: second,
            text: "",
        },
    ];

    assert_eq!(
        splice(source, &splices),
        Err(Error::OverlappingSpans { first, second })
    );
}

#[test]
fn edits_apply_to_pretty_printed_json() {
    let source = "{\n  \"a\": 1,\n  \"b\": null,\n  \"c\": 3\n}";
    let doc = parsed(source);
    let edits = [
        Edit::remove(field_id(doc.root(), "b"), Meaning::Preserves),
        replace(field_id(doc.root(), "c"), "30"),
    ];

    assert_eq!(
        apply(&doc, &edits),
        Ok("{\n  \"a\": 1,\n  \"c\": 30\n}".to_owned())
    );
}

#[test]
fn applying_removals_and_replacements_takes_time_in_proportion_to_their_count() {
    // Deciding whether an edit lies inside a removal or a replacement must not take time that grows
    // with the square of the number of edits. Checking and linting a tariff take far longer than
    // applying its fixes, so the `fix` check in the `cli` crate's `test_scaling` target can't see
    // this step below the input cap. This test times `apply` alone.
    const SMALL_FIELD_COUNT: usize = 1000;

    assert_apply_scales_linearly(
        SMALL_FIELD_COUNT,
        object_of_objects,
        remove_and_replace_in_each_field,
    );
}

#[test]
fn renaming_and_removing_alternate_fields_takes_time_in_proportion_to_their_count() {
    // Each rename looks up the key it rewrites among the object's fields. `apply` then checks the
    // key against the removed spans. Neither step may take time that grows with the square of the
    // field count.
    const SMALL_FIELD_COUNT: usize = 2000;

    assert_apply_scales_linearly(
        SMALL_FIELD_COUNT,
        object_of_scalars,
        rename_even_fields_and_remove_odd_ones,
    );
}

/// Times applying edits to a document of `small_count` fields and to one `SCALE_FACTOR`
/// times larger. `make_source` builds each document from its field count. `make_edits` proposes
/// the edits applied to it. Fails when the larger run takes more than `MAX_SLOWDOWN` times as
/// long as the smaller.
///
/// The constants match the ones the `cli` crate's `test_scaling` target uses.
/// `json/test_removal.rs` has a third copy.
#[track_caller]
fn assert_apply_scales_linearly(
    small_count: usize,
    make_source: fn(usize) -> String,
    make_edits: fn(&json::Document<'_>) -> Vec<Edit>,
) {
    const SCALE_FACTOR: usize = 8;
    const MAX_SLOWDOWN: u32 = 22;
    const ROUNDS: usize = 5;

    let small_source = make_source(small_count);
    let large_source = make_source(small_count.saturating_mul(SCALE_FACTOR));
    let small_doc = parsed(&small_source);
    let large_doc = parsed(&large_source);
    let small_edits = make_edits(&small_doc);
    let large_edits = make_edits(&large_doc);

    let mut best_small = Duration::MAX;
    let mut best_large = Duration::MAX;
    for _ in 0..ROUNDS {
        best_small = best_small.min(time_apply(&small_doc, &small_edits));
        best_large = best_large.min(time_apply(&large_doc, &large_edits));
    }

    let limit = best_small.saturating_mul(MAX_SLOWDOWN);
    assert!(
        best_large <= limit,
        "applying {} edits took {best_large:?}, more than {MAX_SLOWDOWN} times the {best_small:?} \
         that {} took",
        large_edits.len(),
        small_edits.len()
    );
}

fn time_apply(doc: &json::Document<'_>, edits: &[Edit]) -> Duration {
    let start = Instant::now();
    let edited = apply(doc, edits).unwrap();
    let elapsed = start.elapsed();
    std::hint::black_box(edited);
    elapsed
}

/// An object of `count` fields, each holding an object with the fields `drop` and `keep`.
fn object_of_objects(count: usize) -> String {
    let mut json = String::from("{");
    for i in 0..count {
        if i > 0 {
            json.push(',');
        }
        json.push_str("\"k");
        json.push_str(&i.to_string());
        json.push_str("\": {\"drop\": 0, \"keep\": 1}");
    }
    json.push('}');
    json
}

/// For each field of the root of `doc`, a removal of its `drop` and a replacement of its
/// `keep`.
fn remove_and_replace_in_each_field(doc: &json::Document<'_>) -> Vec<Edit> {
    let fields = doc.root().as_object_fields().unwrap();
    let mut edits = Vec::with_capacity(fields.len().saturating_mul(2));

    for field in fields {
        let value = field.element();
        edits.push(Edit::remove(field_id(value, "drop"), Meaning::Preserves));
        edits.push(replace(field_id(value, "keep"), "2"));
    }

    edits
}

/// An object of `count` fields, each holding `0`.
fn object_of_scalars(count: usize) -> String {
    let mut json = String::from("{");
    for i in 0..count {
        if i > 0 {
            json.push(',');
        }
        json.push_str("\"k");
        json.push_str(&i.to_string());
        json.push_str("\": 0");
    }
    json.push('}');
    json
}

/// For each field of the root of `doc`, a rename to a key of its own if the field is at an even
/// index, and a removal if it is at an odd one. Removing alternate fields keeps each removal a
/// span of its own.
fn rename_even_fields_and_remove_odd_ones(doc: &json::Document<'_>) -> Vec<Edit> {
    let fields = doc.root().as_object_fields().unwrap();
    let mut edits = Vec::with_capacity(fields.len());

    for (i, field) in fields.iter().enumerate() {
        let id = field.element().id();

        if i % 2 == 1 {
            edits.push(Edit::remove(id, Meaning::Preserves));
            continue;
        }

        let key = Json::raw(&format!("\"renamed{i}\""));
        edits.push(Edit::rename(id, key, Meaning::Preserves));
    }

    edits
}