ocpi-tariffs 0.52.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
use std::{
    collections::{BTreeMap, BTreeSet},
    fmt,
};

use super::{
    Caveat, CaveatDeferred, Element, Error, ErrorSet, Group, Id, Set, Source, Verdict, Warning,
};
use crate::{
    json::{self, test::PathGlob},
    test::{ExpectValue, Expectation, WarningMap},
    warning::SetDeferred,
};

/// `Verdict` specific extension methods for the `Result` type.
pub trait VerdictTestExt<T, W: Warning> {
    /// Discard all warnings in the `ErrorSet` variant and keep only the warning that caused the error.
    fn unwrap_only_error(self) -> Error<W>;
}

impl<T, W: Warning> VerdictTestExt<T, W> for Verdict<T, W>
where
    T: fmt::Debug,
{
    fn unwrap_only_error(self) -> Error<W> {
        let error = match self {
            Ok(c) => panic!("called `Result::unwrap_only_error` on an `Ok` value: {c:?}"),
            Err(set) => {
                let ErrorSet { error, warnings: _ } = set;
                *error
            }
        };
        error
    }
}

impl<T, W> Caveat<T, W>
where
    W: Warning,
{
    /// Return the value and assert there are no [`Warning`]s.
    ///
    /// # Panics
    ///
    /// Asserts that the warning is empty.
    #[track_caller]
    pub fn unwrap(self) -> T {
        let Self { value, warnings } = self;
        assert!(warnings.is_empty(), "{:#?}", warnings.path_id_map());
        value
    }

    /// Consume the Caveat and return the warning Set.
    pub fn into_warnings(self) -> Set<W> {
        self.warnings
    }
}

impl<W> ErrorSet<W>
where
    W: Warning,
{
    /// Return the [`Error`] that halted the operation and assert nothing else was reported.
    ///
    /// The mirror of [`Caveat::unwrap`]: a failing operation may have collected [`Warning`]s
    /// before it bailed, and those say something distinct from the bail itself. Use
    /// [`VerdictTestExt::unwrap_only_error`] where they are deliberately not the subject.
    ///
    /// # Panics
    ///
    /// Asserts that the warnings collected before the bail are empty.
    #[track_caller]
    pub fn unwrap(self) -> Error<W> {
        let Self { error, warnings } = self;
        let warnings = Set(warnings);
        assert!(warnings.is_empty(), "{:#?}", warnings.path_id_map());
        *error
    }
}

impl<T, W> CaveatDeferred<T, W>
where
    W: Warning,
{
    /// Return the value and assert there are no [`Warning`]s.
    ///
    /// # Panics
    ///
    /// Asserts that the warning is empty.
    pub fn unwrap(self) -> T {
        let Self { value, warnings } = self;
        assert!(warnings.is_empty(), "{:#?}", warnings.id_map());
        value
    }
}

impl<W> Set<W>
where
    W: Warning,
{
    /// Consume the `Set` and return a map of [`json::Element`] paths to a list of [`Warning`]s.
    ///
    /// This is designed to be used to print out maps of warnings associated with elements.
    pub(crate) fn into_path_as_str_map(self) -> BTreeMap<String, Vec<W>> {
        self.0
            .into_values()
            .map(|Group { element, warnings }| {
                let warnings = warnings.into_iter().map(Source::into_warning).collect();
                (element.path.into_string(), warnings)
            })
            .collect()
    }
}

impl<W: Warning> SetDeferred<W> {
    /// Return true if the [`Warning`] set is empty.
    pub fn is_empty(&self) -> bool {
        self.0.is_empty()
    }

    /// Return the set as a list of `warning::Id`s.
    pub fn id_map(&self) -> Vec<Id> {
        self.0.iter().map(|w| w.id()).collect()
    }

    pub fn into_warnings(self) -> Vec<W> {
        self.0.into_iter().map(|s| s.warning).collect()
    }
}

#[derive(Debug)]
pub struct ErrorSourceContext<'buf, W: Warning> {
    /// The element as source JSON and surrounding context.
    pub context: &'buf str,

    /// The elements path.
    pub element_path: json::Path,

    /// The position of the element in the JSON.
    pub element_position: json::Location,

    /// The `Warning` that caused the failure.
    pub error: W,
}

impl<W: Warning> fmt::Display for ErrorSourceContext<'_, W> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "The element at `{}` path `{}: {}` has an error: {}",
            self.element_position, self.element_path, self.context, self.error
        )
    }
}

pub struct IncorrectSource(());

impl fmt::Debug for IncorrectSource {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Display::fmt(self, f)
    }
}

impl fmt::Display for IncorrectSource {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_tuple("The JSON given is not the JSON that generated these warnings")
            .field(&self.0)
            .finish()
    }
}

impl std::error::Error for IncorrectSource {}

impl<W: Warning> Error<W> {
    /// Convert the [`Error`] into a source context ready for printing.
    #[expect(
        clippy::as_conversions,
        reason = "The index is guaranteed within bounds by the parser"
    )]
    pub(crate) fn into_context(
        self,
        json: &str,
    ) -> Result<ErrorSourceContext<'_, W>, IncorrectSource> {
        let Self { warning, element } = self;
        let Element {
            id: _,
            span,
            path,
            location: _,
        } = element;

        // Slice up to the start of the span to calculate line and col numbers.
        let Some(lead_in) = json.get(..span.start as usize) else {
            return Err(IncorrectSource(()));
        };
        // We can start the newline check from this byte index the next time.
        let element_position = json::line_col(lead_in);
        let Some(context) = json.get(span.start as usize..span.end as usize) else {
            return Err(IncorrectSource(()));
        };

        Ok(ErrorSourceContext {
            context,
            element_path: path,
            element_position,
            error: warning,
        })
    }
}

/// Assert that the warnings given are the warnings the expect file lists.
///
/// Each key of the [`WarningMap`] is a [`PathGlob`]; every element path it matches must report
/// exactly the warning [`Id`]s listed under it. A key with no `*` component names one element,
/// so a precise expectation and a bulk one are written the same way and a repetitive set (the
/// same warning on every entry of a long array) collapses to a single line.
///
/// Both directions are checked. An element that has warnings but is matched by no key fails, and
/// so does a key that matches no element with warnings. A key left behind after the warning it
/// pinned down stopped being raised is a stale expectation, not a passing test.
///
/// An element matched by more than one key is reported rather than resolved: which of the
/// competing id lists applied would otherwise depend on the order the keys sort in.
///
/// `expectation` names where the [`WarningMap`] was written, phrased to follow "no entry of":
/// the field and file for an expect-file caller, the argument, and helper for an inline one.
/// One `expect` file can hold the expectations of several stages, so a panic has to say which of
/// them to go and edit.
///
/// # Panics
///
/// If the expected warnings don't match the actual the function panics with a print out of the
/// warnings and the expectations if any warnings were unexpected.
#[track_caller]
pub(crate) fn assert_warnings<W>(
    expectation: &str,
    warnings: &Set<W>,
    expected: Expectation<WarningMap>,
) where
    W: Warning,
{
    let reported = warnings
        .iter()
        .map(|group| Reported {
            path: &group.element.path,
            ids: group.warnings.iter().map(|source| source.id()).collect(),
            messages: group
                .warnings
                .iter()
                .map(|source| source.to_string())
                .collect(),
        })
        .collect::<Vec<_>>();

    assert_reported(expectation, &reported, expected);
}

/// Assert the [`Warning`]s of a path map, as [`assert_warnings`] does for a [`Set`].
///
/// A `Set` retains the [`Element`] each warning was reported against; a caller that kept only
/// the paths - see [`price::TariffReport`](crate::price::TariffReport) - has the same
/// expectation checked against what it kept.
#[track_caller]
pub(crate) fn assert_path_map_warnings<W>(
    expectation: &str,
    warnings: &BTreeMap<json::Path, Vec<W>>,
    expected: Expectation<WarningMap>,
) where
    W: Warning,
{
    let reported = warnings
        .iter()
        .map(|(path, warnings)| Reported {
            path,
            ids: warnings.iter().map(Warning::id).collect(),
            messages: warnings.iter().map(ToString::to_string).collect(),
        })
        .collect::<Vec<_>>();

    assert_reported(expectation, &reported, expected);
}

/// One element and what it reported: the [`Id`]s the expectation is compared against, and the
/// messages to show when that comparison fails.
struct Reported<'caller> {
    /// The path of the element the warnings were reported against.
    path: &'caller json::Path,

    /// The ids of those warnings.
    ids: BTreeSet<Id>,

    /// What each of those warnings says.
    messages: Vec<String>,
}

/// Compare the element paths that reported warnings, and the [`Id`]s each reported, against the
/// expectation. Both [`assert_warnings`] and [`assert_path_map_warnings`] funnel into this.
#[track_caller]
fn assert_reported(
    expectation: &str,
    reported: &[Reported<'_>],
    expected: Expectation<WarningMap>,
) {
    let Expectation::Present(ExpectValue::Some(expected)) = expected else {
        let ids = reported
            .iter()
            .map(|report| (report.path.as_str(), &report.ids))
            .collect::<BTreeMap<_, _>>();
        let messages = reported
            .iter()
            .map(|report| (report.path.as_str(), &report.messages))
            .collect::<BTreeMap<_, _>>();

        assert!(
            reported.is_empty(),
            "There is no {expectation} but these warnings were reported;\n{ids:#?}\n\
            These warnings have the messages:\n{messages:#?}"
        );
        return;
    };

    // The elements that have warnings but whose path is matched by no entry in the `expect` file.
    let mut elems_missing_from_expect = vec![];
    // The elements whose warnings are not the warnings listed by the entry that matched them.
    let mut unequal_warnings = vec![];
    // The elements matched by more than one entry, so no single list of ids applies.
    let mut ambiguous_elems = vec![];

    for report in reported {
        let Reported {
            path,
            ids,
            messages,
        } = report;

        let mut entries_matched = expected.iter().filter(|(glob, _ids)| glob.matches(path));

        let Some((entry, ids_expected)) = entries_matched.next() else {
            elems_missing_from_expect.push(report);
            continue;
        };

        let entries_extra = entries_matched.map(|(glob, _ids)| glob).collect::<Vec<_>>();

        if !entries_extra.is_empty() {
            let entries = std::iter::once(entry).chain(entries_extra).collect();
            ambiguous_elems.push(Ambiguous {
                path: path.as_str(),
                entries,
            });
            continue;
        }

        // Make two sets of actual and expected warnings.
        let ids_expected = ids_expected
            .iter()
            .cloned()
            .map(Id::from_string)
            .collect::<BTreeSet<_>>();

        if *ids != ids_expected {
            unequal_warnings.push(Unequal {
                path: path.as_str(),
                entry,
                expected: ids_expected,
                actual: ids.clone(),
                messages: messages.clone(),
            });
        }
    }

    let entries_unused = expected
        .keys()
        .filter(|glob| !reported.iter().any(|report| glob.matches(report.path)))
        .collect::<Vec<_>>();

    let mut problems = vec![];

    if !elems_missing_from_expect.is_empty() {
        let missing = elems_missing_from_expect
            .iter()
            .map(|report| (report.path.as_str(), &report.ids))
            .collect::<BTreeMap<_, _>>();
        let messages = elems_missing_from_expect
            .iter()
            .map(|report| (report.path.as_str(), &report.messages))
            .collect::<BTreeMap<_, _>>();

        problems.push(format!(
            "Elements with warnings that no entry of {expectation} matches:\n{missing:#?}\n\
            These warnings have the messages:\n{messages:#?}"
        ));
    }

    if !unequal_warnings.is_empty() {
        problems.push(format!(
            "Elements whose warnings are not the warnings listed by {expectation}:\n{unequal_warnings:#?}"
        ));
    }

    if !ambiguous_elems.is_empty() {
        problems.push(format!(
            "Elements matched by more than one entry of {expectation}. Narrow the entries so that \
            each element is matched once:\n{ambiguous_elems:#?}"
        ));
    }

    if !entries_unused.is_empty() {
        problems.push(format!(
            "Entries of {expectation} that match no element with warnings:\n{entries_unused:#?}"
        ));
    }

    assert!(problems.is_empty(), "{}", problems.join("\n\n"));
}

/// An element whose warnings are not the warnings listed by the expect entry that matched it.
#[derive(Debug)]
#[expect(
    dead_code,
    reason = "the fields are read by the derived `Debug` in the panic message"
)]
struct Unequal<'caller> {
    /// The path of the element that has warnings.
    path: &'caller str,

    /// The entry of the `expect` file that matched the path.
    entry: &'caller PathGlob,

    /// The warning ids the entry lists.
    expected: BTreeSet<Id>,

    /// The warning ids actually reported for the element.
    actual: BTreeSet<Id>,

    /// What each of the reported warnings says.
    messages: Vec<String>,
}

/// An element matched by more than one expect entry, so no single list of ids applies to it.
#[derive(Debug)]
#[expect(
    dead_code,
    reason = "the fields are read by the derived `Debug` in the panic message"
)]
struct Ambiguous<'caller> {
    /// The path of the element that has warnings.
    path: &'caller str,

    /// Every entry of the `expect` file that matched the path.
    entries: Vec<&'caller PathGlob>,
}