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
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
use super::{BuilderKind, Cardinality, Field, Object, Scalar, Schema, Warning, walk};
use crate::json::{self, parse};

static NAME_OBJ: Object = Object {
    fields: &[
        Field::required("first", Scalar::String),
        Field::required("last", Scalar::String),
    ],
    kind: BuilderKind::Ignore,
};
static NAME_SCHEMA: Schema = Schema::Object(&NAME_OBJ);
static PERSON_OBJ: Object = Object {
    fields: &[
        Field::optional("age", Scalar::Number),
        Field::required_object("name", &NAME_OBJ),
    ],
    kind: BuilderKind::Ignore,
};
static PERSON_SCHEMA: Schema = Schema::Object(&PERSON_OBJ);
static NAMES_ARRAY_SCHEMA: Schema = Schema::Array {
    item: &NAME_SCHEMA,
    cardinality: Cardinality::ZeroOrMore,
};
static NAMES_ARRAY_ONE_OR_MORE: Schema = Schema::Array {
    item: &NAME_SCHEMA,
    cardinality: Cardinality::OneOrMore,
};

#[test]
fn empty_object_reports_missing_required() {
    let doc = parse("{}".into()).unwrap();
    let warnings = walk(&doc, &PERSON_SCHEMA).into_warnings();
    assert_eq!(warnings.len_warnings(), 1);
    assert_eq!(
        warnings.path_map()["$"],
        vec![&Warning::MissingField { name: "name" }]
    );
}

#[test]
fn unexpected_fields_reported() {
    let doc = parse(r#"{"title": {}, "extra": 1}"#.into()).unwrap();
    let warnings = walk(&doc, &PERSON_SCHEMA).into_warnings();
    let by_path = warnings.path_map();
    assert_eq!(warnings.len_warnings(), 3);
    assert_eq!(by_path["$.title"], vec![&Warning::UnexpectedField]);
    assert_eq!(by_path["$.extra"], vec![&Warning::UnexpectedField]);
    assert_eq!(by_path["$"], vec![&Warning::MissingField { name: "name" }]);
}

/// `nane` misspells the required `name`, so the walk reports the misspelling and also that `name`
/// is missing. `Age` misspells the optional `age`, whose absence the walk doesn't report.
#[test]
fn misspelled_field_reported() {
    let doc = parse(r#"{"nane": {}, "Age": 1}"#.into()).unwrap();
    let warnings = walk(&doc, &PERSON_SCHEMA).into_warnings();
    let by_path = warnings.path_map();
    assert_eq!(warnings.len_warnings(), 3);
    assert_eq!(
        by_path["$.nane"],
        vec![&Warning::MisspelledField {
            expected: vec!["name"]
        }]
    );
    assert_eq!(
        by_path["$.Age"],
        vec![&Warning::MisspelledField {
            expected: vec!["age"]
        }]
    );
    assert_eq!(by_path["$"], vec![&Warning::MissingField { name: "name" }]);
}

/// `ame` is 1 edit from both `age` and `name`, so the walk suggests both, in the order the schema
/// lists them. `name` is required, so the walk also reports it missing.
#[test]
fn a_tie_is_reported_with_every_candidate() {
    let doc = parse(r#"{"ame": 1}"#.into()).unwrap();
    let warnings = walk(&doc, &PERSON_SCHEMA).into_warnings();
    let by_path = warnings.path_map();
    assert_eq!(warnings.len_warnings(), 2);
    assert_eq!(
        by_path["$.ame"],
        vec![&Warning::MisspelledField {
            expected: vec!["age", "name"]
        }]
    );
    assert_eq!(by_path["$"], vec![&Warning::MissingField { name: "name" }]);
}

/// The walk treats `"age": null` as absent, so it reports `Age` as a misspelling of `age` even
/// though the object contains `age`. The fix for `NullField` removes `"age": null`, so renaming
/// `Age` doesn't result in duplicate fields.
#[test]
fn a_null_field_is_suggested() {
    let doc =
        parse(r#"{"age": null, "Age": 1, "name": {"first": "J", "last": "D"}}"#.into()).unwrap();
    let warnings = walk(&doc, &PERSON_SCHEMA).into_warnings();
    let by_path = warnings.path_map();
    assert_eq!(warnings.len_warnings(), 2);
    assert_eq!(by_path["$.age"], vec![&Warning::NullField]);
    assert_eq!(
        by_path["$.Age"],
        vec![&Warning::MisspelledField {
            expected: vec!["age"]
        }]
    );
}

/// Renaming `Age` to `age` would repeat a key the object already has, so the walk suggests only a
/// field absent from the object. The walk visits fields from last to first, so it reaches `Age`
/// before it has seen `age`.
#[test]
fn a_present_field_is_not_suggested() {
    let doc = parse(r#"{"age": 2, "Age": 1, "name": {"first": "J", "last": "D"}}"#.into()).unwrap();
    let warnings = walk(&doc, &PERSON_SCHEMA).into_warnings();
    assert_eq!(warnings.len_warnings(), 1);
    assert_eq!(
        warnings.path_map()["$.Age"],
        vec![&Warning::UnexpectedField]
    );
}

#[test]
fn valid_object_is_clean() {
    let doc = parse(r#"{"name": {"first": "John", "last": "Doe"}}"#.into()).unwrap();
    let warnings = walk(&doc, &PERSON_SCHEMA).into_warnings();
    assert!(warnings.is_empty());
}

#[test]
fn optional_field_present_does_not_warn() {
    let doc = parse(r#"{"age": 30, "name": {"first": "J", "last": "D"}}"#.into()).unwrap();
    let warnings = walk(&doc, &PERSON_SCHEMA).into_warnings();
    assert!(warnings.is_empty());
}

#[test]
fn nested_unexpected_reported_with_path() {
    let doc = parse(r#"{"name": {"first": "J", "last": "D", "middle": "X"}}"#.into()).unwrap();
    let warnings = walk(&doc, &PERSON_SCHEMA).into_warnings();
    assert_eq!(warnings.len_warnings(), 1);
    assert_eq!(
        warnings.path_map()["$.name.middle"],
        vec![&Warning::UnexpectedField]
    );
}

#[test]
fn nested_missing_required_reported_with_path() {
    let doc = parse(r#"{"name": {"first": "J"}}"#.into()).unwrap();
    let warnings = walk(&doc, &PERSON_SCHEMA).into_warnings();
    assert_eq!(warnings.len_warnings(), 1);
    assert_eq!(
        warnings.path_map()["$.name"],
        vec![&Warning::MissingField { name: "last" }]
    );
}

#[test]
fn array_items_each_validated() {
    let doc =
        parse(r#"[{"first": "A", "last": "B"}, {"first": "C", "typo": "D"}]"#.into()).unwrap();
    let warnings = walk(&doc, &NAMES_ARRAY_SCHEMA).into_warnings();
    let by_path = warnings.path_map();
    assert_eq!(warnings.len_warnings(), 2);
    assert_eq!(by_path["$[1].typo"], vec![&Warning::UnexpectedField]);
    assert_eq!(
        by_path["$[1]"],
        vec![&Warning::MissingField { name: "last" }]
    );
}

#[test]
fn any_imposes_no_kind_constraint() {
    // `Scalar::Any` constrains nothing, so arbitrary non-null content is clean.
    // (Nested `null`s are still reported - see `null_inside_any_subtree_is_reported`.)
    let doc = parse(r#"{"anything": [1, 2, {"nested": true}]}"#.into()).unwrap();
    let warnings = walk(&doc, &Schema::Scalar(Scalar::Any)).into_warnings();
    assert!(warnings.is_empty());
}

#[test]
fn non_object_against_object_schema_reported() {
    // An array where an object is expected is a shape violation.
    let doc = parse("[1, 2, 3]".into()).unwrap();
    let warnings = walk(&doc, &PERSON_SCHEMA).into_warnings();
    assert_eq!(warnings.len_warnings(), 1);
    assert_eq!(
        warnings.path_map()["$"],
        vec![&Warning::InvalidType {
            expected: json::ValueKind::Object,
            actual: json::ValueKind::Array,
        }]
    );
}

#[test]
fn scalar_where_object_expected_reported() {
    // `name` is declared as an object; a string value is a shape violation. The
    // object schema is not entered, so its required fields are not chased.
    let doc = parse(r#"{"name": "John Doe"}"#.into()).unwrap();
    let warnings = walk(&doc, &PERSON_SCHEMA).into_warnings();
    assert_eq!(warnings.len_warnings(), 1);
    assert_eq!(
        warnings.path_map()["$.name"],
        vec![&Warning::InvalidType {
            expected: json::ValueKind::Object,
            actual: json::ValueKind::String,
        }]
    );
}

#[test]
fn non_array_against_array_schema_reported() {
    // An object where an array is expected is a shape violation.
    let doc = parse(r#"{"first": "J", "last": "D"}"#.into()).unwrap();
    let warnings = walk(&doc, &NAMES_ARRAY_SCHEMA).into_warnings();
    assert_eq!(warnings.len_warnings(), 1);
    assert_eq!(
        warnings.path_map()["$"],
        vec![&Warning::InvalidType {
            expected: json::ValueKind::Array,
            actual: json::ValueKind::Object,
        }]
    );
}

#[test]
fn scalar_invalid_type_reported() {
    // `age` is declared `Scalar::Number`; a boolean value is a type mismatch.
    let doc = parse(r#"{"age": true, "name": {"first": "J", "last": "D"}}"#.into()).unwrap();
    let warnings = walk(&doc, &PERSON_SCHEMA).into_warnings();
    assert_eq!(warnings.len_warnings(), 1);
    assert_eq!(
        warnings.path_map()["$.age"],
        vec![&Warning::InvalidType {
            expected: json::ValueKind::Number,
            actual: json::ValueKind::Bool,
        }]
    );
}

#[test]
fn number_field_accepts_string_encoding() {
    // OCPI numbers may be serialized as quoted strings; that form is accepted silently
    // (no type mismatch and no warning). A linter may choose to flag it later.
    let doc = parse(r#"{"age": "30", "name": {"first": "J", "last": "D"}}"#.into()).unwrap();
    let warnings = walk(&doc, &PERSON_SCHEMA).into_warnings();
    assert!(warnings.is_empty());
}

#[test]
fn empty_one_or_more_array_reported() {
    // A `+` array must hold at least one element; an empty array is a violation.
    let doc = parse("[]".into()).unwrap();
    let warnings = walk(&doc, &NAMES_ARRAY_ONE_OR_MORE).into_warnings();
    assert_eq!(warnings.len_warnings(), 1);
    assert_eq!(warnings.path_map()["$"], vec![&Warning::Cardinality]);
}

#[test]
fn empty_zero_or_more_array_is_clean() {
    // A `*` array may be empty.
    let doc = parse("[]".into()).unwrap();
    let warnings = walk(&doc, &NAMES_ARRAY_SCHEMA).into_warnings();
    assert!(warnings.is_empty());
}

#[test]
fn non_empty_one_or_more_array_is_clean() {
    let doc = parse(r#"[{"first": "A", "last": "B"}]"#.into()).unwrap();
    let warnings = walk(&doc, &NAMES_ARRAY_ONE_OR_MORE).into_warnings();
    assert!(warnings.is_empty());
}

#[test]
fn null_inside_any_subtree_is_reported() {
    // `Scalar::Any` imposes no kind constraint, but the subtree is still walked,
    // so a nested `null` is reported at full depth.
    static OPAQUE_OBJ: Object = Object {
        fields: &[Field::optional("blob", Scalar::Any)],
        kind: BuilderKind::Ignore,
    };
    static OPAQUE_SCHEMA: Schema = Schema::Object(&OPAQUE_OBJ);
    let doc = parse(r#"{"blob": {"nested": null}}"#.into()).unwrap();
    let warnings = walk(&doc, &OPAQUE_SCHEMA).into_warnings();
    assert_eq!(warnings.len_warnings(), 1);
    assert_eq!(
        warnings.path_map()["$.blob.nested"],
        vec![&Warning::NullField]
    );
}

#[test]
fn invalid_type_subtree_is_not_walked() {
    // `name` expects an object but is given an array; the shape mismatch is
    // reported and the array is NOT walked, so the nested `null` is not seen
    // (the single warning is the mismatch).
    let doc = parse(r#"{"name": [null]}"#.into()).unwrap();
    let warnings = walk(&doc, &PERSON_SCHEMA).into_warnings();
    assert_eq!(warnings.len_warnings(), 1);
    assert_eq!(
        warnings.path_map()["$.name"],
        vec![&Warning::InvalidType {
            expected: json::ValueKind::Object,
            actual: json::ValueKind::Array,
        }]
    );
}

#[test]
fn unexpected_field_subtree_is_not_walked() {
    // An unexpected key is reported, but its subtree is NOT walked, so the nested
    // `null` is not reported (the single warning is the unexpected field).
    let doc =
        parse(r#"{"name": {"first": "J", "last": "D"}, "typo": {"x": null}}"#.into()).unwrap();
    let warnings = walk(&doc, &PERSON_SCHEMA).into_warnings();
    assert_eq!(warnings.len_warnings(), 1);
    assert_eq!(
        warnings.path_map()["$.typo"],
        vec![&Warning::UnexpectedField]
    );
}

// A synthetic enum table for exercising the walk's `Scalar::Enum` handling.
const COLOR_VALUES: &[&str] = &["RED", "GREEN", "BLUE"];
static PAINT_OBJ: Object = Object {
    fields: &[Field::required("color", Scalar::Enum(COLOR_VALUES))],
    kind: BuilderKind::Ignore,
};
static PAINT_SCHEMA: Schema = Schema::Object(&PAINT_OBJ);

#[test]
fn enum_permitted_value_is_clean() {
    let doc = parse(r#"{"color": "GREEN"}"#.into()).unwrap();
    let warnings = walk(&doc, &PAINT_SCHEMA).into_warnings();
    assert!(warnings.is_empty());
}

#[test]
fn enum_value_matched_case_insensitively() {
    // A differently-cased value matches the variant, and the case is reported: the value is
    // read, and the spec calls an enumeration case sensitive.
    let doc = parse(r#"{"color": "green"}"#.into()).unwrap();
    let warnings = walk(&doc, &PAINT_SCHEMA).into_warnings();
    assert_eq!(
        warnings.path_map()["$.color"],
        vec![&Warning::IncorrectCase {
            expected: "GREEN",
            actual: "green".to_owned(),
        }]
    );
}

#[test]
fn enum_value_matched_escape_aware_and_case_insensitively() {
    // The value is compared escape-aware and case-insensitively: the JSON
    // string `\u0067reen` decodes to "green", which matches "GREEN".
    let doc = parse(r#"{"color": "\u0067reen"}"#.into()).unwrap();
    let warnings = walk(&doc, &PAINT_SCHEMA).into_warnings();
    assert_eq!(
        warnings.path_map()["$.color"],
        vec![&Warning::IncorrectCase {
            expected: "GREEN",
            actual: "\\u0067reen".to_owned(),
        }]
    );
}

/// A value written in the spec's own case is read without comment, escapes and all.
#[test]
fn enum_value_in_the_spec_case_is_clean() {
    let doc = parse(r#"{"color": "\u0047REEN"}"#.into()).unwrap();
    let warnings = walk(&doc, &PAINT_SCHEMA).into_warnings();
    assert!(warnings.is_empty());
}

#[test]
fn enum_unknown_value_reported() {
    let doc = parse(r#"{"color": "PURPLE"}"#.into()).unwrap();
    let warnings = walk(&doc, &PAINT_SCHEMA).into_warnings();
    assert_eq!(warnings.len_warnings(), 1);
    assert_eq!(
        warnings.path_map()["$.color"],
        vec![&Warning::InvalidValue {
            expected: COLOR_VALUES,
            actual: "PURPLE".to_owned(),
        }]
    );
}

/// `GREN` is 1 edit from `GREEN` and 2 from `RED`, so the walk names `GREEN` alone.
#[test]
fn enum_misspelled_value_reported_with_the_variant() {
    let doc = parse(r#"{"color": "GREN"}"#.into()).unwrap();
    let warnings = walk(&doc, &PAINT_SCHEMA).into_warnings();
    assert_eq!(warnings.len_warnings(), 1);
    assert_eq!(
        warnings.path_map()["$.color"],
        vec![&Warning::MisspelledValue {
            expected: vec!["GREEN"],
            actual: "GREN".to_owned(),
        }]
    );
}

/// `\u0047` decodes to `G`. The walk compares the decoded value `GREN`, which is 1 edit from
/// `GREEN`. `actual` holds the value as written, escape included.
#[test]
fn enum_misspelled_value_is_compared_decoded() {
    let doc = parse(r#"{"color": "\u0047REN"}"#.into()).unwrap();
    let warnings = walk(&doc, &PAINT_SCHEMA).into_warnings();
    assert_eq!(
        warnings.path_map()["$.color"],
        vec![&Warning::MisspelledValue {
            expected: vec!["GREEN"],
            actual: "\\u0047REN".to_owned(),
        }]
    );
}

/// `\E` is not an escape JSON defines, so the value fails to decode. Read as written, `GR\EN` would
/// be 1 edit from `GREEN`, but the walk doesn't suggest a variant for a malformed value.
#[test]
fn enum_value_with_an_invalid_escape_is_invalid() {
    let doc = parse(r#"{"color": "GR\EN"}"#.into()).unwrap();
    let warnings = walk(&doc, &PAINT_SCHEMA).into_warnings();
    assert_eq!(
        warnings.path_map()["$.color"],
        vec![&Warning::InvalidValue {
            expected: COLOR_VALUES,
            actual: "GR\\EN".to_owned(),
        }]
    );
}

const FOUR_SIZE_VALUES: &[&str] = &["SIZE_A", "SIZE_B", "SIZE_C", "SIZE_D"];
const FIVE_SIZE_VALUES: &[&str] = &["SIZE_A", "SIZE_B", "SIZE_C", "SIZE_D", "SIZE_E"];
static BOX_OBJ: Object = Object {
    fields: &[
        Field::optional("five_sizes", Scalar::Enum(FIVE_SIZE_VALUES)),
        Field::optional("four_sizes", Scalar::Enum(FOUR_SIZE_VALUES)),
    ],
    kind: BuilderKind::Ignore,
};
static BOX_SCHEMA: Schema = Schema::Object(&BOX_OBJ);

/// `SIZE_Z` is 1 edit from every variant of both fields. The walk names all four variants of
/// `four_sizes`, and reports the value of `five_sizes` as invalid because five variants are more
/// than `MISSPELLED_VALUE_MAX_EXPECTED`.
#[test]
fn enum_tie_names_at_most_four_variants() {
    let doc = parse(r#"{"five_sizes": "SIZE_Z", "four_sizes": "SIZE_Z"}"#.into()).unwrap();
    let warnings = walk(&doc, &BOX_SCHEMA).into_warnings();
    let by_path = warnings.path_map();
    assert_eq!(warnings.len_warnings(), 2);
    assert_eq!(
        by_path["$.four_sizes"],
        vec![&Warning::MisspelledValue {
            expected: vec!["SIZE_A", "SIZE_B", "SIZE_C", "SIZE_D"],
            actual: "SIZE_Z".to_owned(),
        }]
    );
    assert_eq!(
        by_path["$.five_sizes"],
        vec![&Warning::InvalidValue {
            expected: FIVE_SIZE_VALUES,
            actual: "SIZE_Z".to_owned(),
        }]
    );
}

#[test]
fn enum_non_string_reported_as_invalid_type() {
    // A non-string value fails the kind check first; the value-membership check
    // is not reached, so only a single type mismatch is reported.
    let doc = parse(r#"{"color": 7}"#.into()).unwrap();
    let warnings = walk(&doc, &PAINT_SCHEMA).into_warnings();
    assert_eq!(warnings.len_warnings(), 1);
    assert_eq!(
        warnings.path_map()["$.color"],
        vec![&Warning::InvalidType {
            expected: json::ValueKind::String,
            actual: json::ValueKind::Number,
        }]
    );
}

static LABEL_OBJ: Object = Object {
    fields: &[Field::required("code", Scalar::StringMax(3))],
    kind: BuilderKind::Ignore,
};
static LABEL_SCHEMA: Schema = Schema::Object(&LABEL_OBJ);

#[test]
fn duplicate_key_reported_once() {
    // Both occurrences are individually valid, so the duplication is the only fault. The
    // warning anchors on the superseded occurrence, which is the one a fix removes.
    let doc = parse(r#"{"name": {"first": "a", "last": "b"}, "age": 1, "age": 2}"#.into()).unwrap();
    let warnings = walk(&doc, &PERSON_SCHEMA).into_warnings();
    assert_eq!(warnings.len_warnings(), 1);
    assert_eq!(warnings.path_map()["$.age"], vec![&Warning::DuplicateField]);
}

/// `\u0061` is `a`, so the walk matches `"\u0061ge"` to the schema's `age` field and raises no
/// `UnexpectedField` for it.
#[test]
fn escaped_field_name_matches_the_schema_and_is_reported() {
    let doc = parse(r#"{"name": {"first": "a", "last": "b"}, "\u0061ge": 1}"#.into()).unwrap();
    let warnings = walk(&doc, &PERSON_SCHEMA).into_warnings();
    assert_eq!(warnings.len_warnings(), 1);
    assert_eq!(
        warnings.path_map()["$.age"],
        vec![&Warning::FieldNameContainsEscapeCodes]
    );
}

/// Both fields have the path `$.age`, so the test reads the warnings in document order rather
/// than through `path_map`, which keeps one entry per path.
#[test]
fn escaped_spelling_of_a_key_is_a_duplicate() {
    let doc =
        parse(r#"{"name": {"first": "a", "last": "b"}, "age": 1, "\u0061ge": 2}"#.into()).unwrap();
    let warnings = walk(&doc, &PERSON_SCHEMA).into_warnings();
    let by_field: Vec<_> = warnings.iter().map(|group| group.warnings()).collect();
    assert_eq!(
        by_field,
        vec![
            vec![&Warning::DuplicateField],
            vec![&Warning::FieldNameContainsEscapeCodes]
        ]
    );
}

/// `"a\\q"` decodes to the text `a\q`. `"a\q"` is a different name, whose escape `\q` fails to
/// decode. Both fields have the path `$.a\q`, so the test reads the warnings in document order
/// rather than through `path_map`, which keeps one entry per path.
#[test]
fn malformed_name_does_not_repeat_a_decoded_one() {
    let doc =
        parse(r#"{"name": {"first": "a", "last": "b"}, "a\\q": 1, "a\q": 2}"#.into()).unwrap();
    let warnings = walk(&doc, &PERSON_SCHEMA).into_warnings();
    let by_field: Vec<_> = warnings.iter().map(|group| group.warnings()).collect();
    assert_eq!(
        by_field,
        vec![
            vec![
                &Warning::FieldNameContainsEscapeCodes,
                &Warning::UnexpectedField
            ],
            vec![&Warning::FieldNameInvalidEscape, &Warning::UnexpectedField]
        ]
    );
}

static EXTRA_OBJ: Object = Object {
    fields: &[Field::non_spec_object("extra", &NAME_OBJ)],
    kind: BuilderKind::Ignore,
};
static EXTRA_SCHEMA: Schema = Schema::Object(&EXTRA_OBJ);

/// The walk raises no `UnexpectedField` inside a `NonSpecObject`, but it still reports an escape in
/// a field name there.
#[test]
fn escaped_field_names_are_reported_inside_a_non_spec_object() {
    let doc = parse(r#"{"extra": {"\u0066irst": "a", "last": "b", "x\q": 1}}"#.into()).unwrap();
    let warnings = walk(&doc, &EXTRA_SCHEMA).into_warnings();
    let by_path = warnings.path_map();
    assert_eq!(warnings.len_warnings(), 3);
    assert_eq!(by_path["$.extra"], vec![&Warning::NonSpecField]);
    assert_eq!(
        by_path["$.extra.first"],
        vec![&Warning::FieldNameContainsEscapeCodes]
    );
    assert_eq!(
        by_path[r"$.extra.x\q"],
        vec![&Warning::FieldNameInvalidEscape]
    );
}

#[test]
fn triplicate_key_reports_every_superseded_occurrence() {
    // Three occurrences leave two superseded, so a fix has two anchors to remove.
    let doc =
        parse(r#"{"name": {"first": "a", "last": "b"}, "age": 1, "age": 2, "age": 3}"#.into())
            .unwrap();
    let warnings = walk(&doc, &PERSON_SCHEMA).into_warnings();
    assert_eq!(warnings.len_warnings(), 2);
}

#[test]
fn single_key_is_not_reported_as_duplicate() {
    let doc = parse(r#"{"name": {"first": "a", "last": "b"}, "age": 1}"#.into()).unwrap();
    let warnings = walk(&doc, &PERSON_SCHEMA).into_warnings();
    assert!(warnings.is_empty());
}

#[test]
fn string_within_max_is_clean() {
    let doc = parse(r#"{"code": "AB"}"#.into()).unwrap();
    let warnings = walk(&doc, &LABEL_SCHEMA).into_warnings();
    assert!(warnings.is_empty());
}

#[test]
fn string_at_max_is_clean() {
    // A value exactly at the limit is permitted (the bound is inclusive).
    let doc = parse(r#"{"code": "ABC"}"#.into()).unwrap();
    let warnings = walk(&doc, &LABEL_SCHEMA).into_warnings();
    assert!(warnings.is_empty());
}

#[test]
fn string_over_max_reported() {
    let doc = parse(r#"{"code": "ABCD"}"#.into()).unwrap();
    let warnings = walk(&doc, &LABEL_SCHEMA).into_warnings();
    assert_eq!(warnings.len_warnings(), 1);
    assert_eq!(
        warnings.path_map()["$.code"],
        vec![&Warning::StringTooLong { max: 3, len: 4 }]
    );
}

#[test]
fn string_max_non_string_reported_as_invalid_type() {
    // A non-string value fails the kind check first; the length check is not
    // reached, so only a single type mismatch is reported.
    let doc = parse(r#"{"code": 7}"#.into()).unwrap();
    let warnings = walk(&doc, &LABEL_SCHEMA).into_warnings();
    assert_eq!(warnings.len_warnings(), 1);
    assert_eq!(
        warnings.path_map()["$.code"],
        vec![&Warning::InvalidType {
            expected: json::ValueKind::String,
            actual: json::ValueKind::Number,
        }]
    );
}

#[test]
fn string_max_counts_decoded_characters() {
    // The JSON value contains three escaped characters (raw form is 18 bytes) that
    // decode to "AAA". The length is measured on the decoded form, so this is clean.
    let doc = parse(r#"{"code": "\u0041\u0041\u0041"}"#.into()).unwrap();
    let warnings = walk(&doc, &LABEL_SCHEMA).into_warnings();
    assert!(warnings.is_empty());
}

#[test]
fn scalar_any_is_not_type_checked() {
    // A field declared `Scalar::Any` accepts any JSON kind, including an object.
    static OPAQUE_OBJ: Object = Object {
        fields: &[Field::optional("blob", Scalar::Any)],
        kind: BuilderKind::Ignore,
    };
    static OPAQUE_SCHEMA: Schema = Schema::Object(&OPAQUE_OBJ);
    let doc = parse(r#"{"blob": {"nested": 1}}"#.into()).unwrap();
    let warnings = walk(&doc, &OPAQUE_SCHEMA).into_warnings();
    assert!(warnings.is_empty());
}

static EVENT_OBJ: Object = Object {
    fields: &[Field::required("on", Scalar::Date)],
    kind: BuilderKind::Ignore,
};
static EVENT_SCHEMA: Schema = Schema::Object(&EVENT_OBJ);

#[test]
fn date_in_the_spec_format_is_clean() {
    let doc = parse(r#"{"on": "2023-01-05"}"#.into()).unwrap();
    let warnings = walk(&doc, &EVENT_SCHEMA).into_warnings();
    assert!(warnings.is_empty());
}

#[test]
fn date_without_leading_zeros_is_reported() {
    let doc = parse(r#"{"on": "2023-1-5"}"#.into()).unwrap();
    let warnings = walk(&doc, &EVENT_SCHEMA).into_warnings();
    assert_eq!(
        warnings.path_map()["$.on"],
        vec![&Warning::IncorrectFormat {
            expected: "2023-01-05".to_owned(),
            actual: "2023-1-5".to_owned(),
        }]
    );
}

/// The walk proposes the date `datetime::parse_date` reads, which is the date the lowering prices,
/// so `--fix` can rewrite the value without changing what a session costs.
#[test]
fn date_in_another_form_the_library_reads_is_reported() {
    let cases = [
        ("2023-1-05", "2023-01-05"),
        ("2023-01-5", "2023-01-05"),
        (" 2023-01-05", "2023-01-05"),
        ("2023-01-05 ", "2023-01-05"),
    ];

    for (actual, expected) in cases {
        let src = format!(r#"{{"on": "{actual}"}}"#);
        let doc = parse(src.as_str().into()).unwrap();
        let warnings = walk(&doc, &EVENT_SCHEMA).into_warnings();
        assert_eq!(
            warnings.path_map()["$.on"],
            vec![&Warning::IncorrectFormat {
                expected: expected.to_owned(),
                actual: actual.to_owned(),
            }],
            "for `{actual}`"
        );
    }
}

/// chrono's `NaiveDate::from_str` reads each of these, but `datetime::parse_date` reads none of
/// them. The walk proposes no date for a value the library does not read.
#[test]
fn date_in_a_form_chrono_reads_and_the_library_does_not_is_not_reported() {
    for actual in ["+2023-01-05", "23-01-05"] {
        let src = format!(r#"{{"on": "{actual}"}}"#);
        let doc = parse(src.as_str().into()).unwrap();
        let warnings = walk(&doc, &EVENT_SCHEMA).into_warnings();
        assert!(warnings.is_empty(), "for `{actual}`");
    }
}

/// The library does not read this value, so there is no date to propose. Reporting it is left to
/// the lowering.
#[test]
fn date_that_does_not_parse_gets_no_rewrite() {
    let doc = parse(r#"{"on": "2023-13-01"}"#.into()).unwrap();
    let warnings = walk(&doc, &EVENT_SCHEMA).into_warnings();
    assert!(warnings.is_empty());
}

/// `\u0035` decodes to `5`, so this value decodes to the unpadded `2023-1-5`.
/// `NaiveDate::from_schema` rejects a date written with escapes, so rewriting it to `2023-01-05`
/// would make the library read a date it otherwise rejects.
#[test]
fn date_written_with_escapes_is_not_reported() {
    let doc = parse(r#"{"on": "2023-1-\u0035"}"#.into()).unwrap();
    let warnings = walk(&doc, &EVENT_SCHEMA).into_warnings();
    assert!(warnings.is_empty());
}

static OPENING_OBJ: Object = Object {
    fields: &[Field::required("at", Scalar::Time)],
    kind: BuilderKind::Ignore,
};
static OPENING_SCHEMA: Schema = Schema::Object(&OPENING_OBJ);

#[test]
fn time_in_the_spec_format_is_clean() {
    let doc = parse(r#"{"at": "09:05"}"#.into()).unwrap();
    let warnings = walk(&doc, &OPENING_SCHEMA).into_warnings();
    assert!(warnings.is_empty());
}

/// The walk proposes the time `datetime::parse_time` reads, which is the time the lowering prices,
/// so `--fix` can rewrite the value without changing what a session costs.
#[test]
fn time_in_another_form_the_library_reads_is_reported() {
    let cases = [
        ("9:05", "09:05"),
        ("09:5", "09:05"),
        ("9:5", "09:05"),
        (" 09:05", "09:05"),
        ("09:05 ", "09:05"),
    ];

    for (actual, expected) in cases {
        let src = format!(r#"{{"at": "{actual}"}}"#);
        let doc = parse(src.as_str().into()).unwrap();
        let warnings = walk(&doc, &OPENING_SCHEMA).into_warnings();
        assert_eq!(
            warnings.path_map()["$.at"],
            vec![&Warning::IncorrectFormat {
                expected: expected.to_owned(),
                actual: actual.to_owned(),
            }],
            "for `{actual}`"
        );
    }
}

/// chrono's `%H:%M` reads `09: 05`, but `datetime::parse_time` does not, and neither reads `24:00`.
/// The walk proposes a time only for a value the library reads, so `--fix` leaves a tariff the
/// library rejects unpriceable.
#[test]
fn time_the_library_does_not_read_gets_no_rewrite() {
    for actual in ["09: 05", "24:00"] {
        let src = format!(r#"{{"at": "{actual}"}}"#);
        let doc = parse(src.as_str().into()).unwrap();
        let warnings = walk(&doc, &OPENING_SCHEMA).into_warnings();
        assert!(warnings.is_empty(), "for `{actual}`");
    }
}