Skip to main content

einvoice_validator/
report.rs

1//! The result of validating one document.
2
3use std::fmt;
4
5use einvoice_xpath::QName;
6use einvoice_xslt_exec::{CompactOutput, ResultObserver};
7
8pub use einvoice_xsd::{ErrorKind as SchemaErrorKind, ValidationError as SchemaError};
9
10use crate::Error;
11
12/// The SVRL namespace.
13const SVRL_NS: &str = "http://purl.oclc.org/dsdl/svrl";
14
15/// The overall verdict on a document.
16#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
17pub enum Verdict {
18    /// No schema error and no finding with severity [`Severity::Fatal`] (and, in a rule
19    /// set that selects by scenario, one scenario matched).
20    Valid,
21    /// At least one schema error or one finding with severity [`Severity::Fatal`], or, in
22    /// a rule set that selects by scenario, no scenario for the document
23    /// ([`Report::no_scenario`]).
24    Invalid,
25}
26
27impl Verdict {
28    /// `valid` or `invalid`.
29    #[must_use]
30    pub const fn as_str(self) -> &'static str {
31        match self {
32            Self::Valid => "valid",
33            Self::Invalid => "invalid",
34        }
35    }
36}
37
38impl fmt::Display for Verdict {
39    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
40        f.write_str(self.as_str())
41    }
42}
43
44/// The severity of a finding, from its Schematron `flag`, as the official rule sets use
45/// it, and from the manifest of the rule set: a failed assert without a flag has the
46/// severity of its stylesheet's `unflagged-assert`
47/// ([`StylesheetEntry::unflagged_assert`](crate::StylesheetEntry::unflagged_assert)), and
48/// the scenario a document matches gives the rule ids it lists their severities, whatever
49/// their flags ([`Scenario`](crate::Scenario)).
50#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
51pub enum Severity {
52    /// `flag="fatal"`: the document does not conform; the verdict is
53    /// [`Verdict::Invalid`].
54    Fatal,
55    /// `flag="warning"`: reported, the document still conforms.
56    Warning,
57    /// Any other flag, or none: reported, the document still conforms (unless the
58    /// validation fails closed: [`ValidateOptions::fail_closed`](crate::ValidateOptions::fail_closed)).
59    Other,
60}
61
62impl Severity {
63    /// The severity a Schematron flag stands for.
64    #[must_use]
65    pub fn from_flag(flag: Option<&str>) -> Self {
66        match flag {
67            Some("fatal") => Self::Fatal,
68            Some("warning") => Self::Warning,
69            _ => Self::Other,
70        }
71    }
72
73    /// The severity a Schematron flag stands for when failing closed: as
74    /// [`Severity::from_flag`], but any other flag, or none, is [`Severity::Fatal`].
75    #[must_use]
76    pub fn from_flag_fail_closed(flag: Option<&str>) -> Self {
77        match Self::from_flag(flag) {
78            Self::Other => Self::Fatal,
79            severity => severity,
80        }
81    }
82
83    /// `fatal`, `warning` or `other`.
84    #[must_use]
85    pub const fn as_str(self) -> &'static str {
86        match self {
87            Self::Fatal => "fatal",
88            Self::Warning => "warning",
89            Self::Other => "other",
90        }
91    }
92}
93
94impl fmt::Display for Severity {
95    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
96        f.write_str(self.as_str())
97    }
98}
99
100/// What a finding is in the SVRL report.
101#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
102pub enum FindingKind {
103    /// `svrl:failed-assert`: an assertion that does not hold.
104    FailedAssert,
105    /// `svrl:successful-report`: a report whose condition holds.
106    SuccessfulReport,
107}
108
109impl FindingKind {
110    /// `failed-assert` or `successful-report`.
111    #[must_use]
112    pub const fn as_str(self) -> &'static str {
113        match self {
114            Self::FailedAssert => "failed-assert",
115            Self::SuccessfulReport => "successful-report",
116        }
117    }
118}
119
120impl fmt::Display for FindingKind {
121    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
122        f.write_str(self.as_str())
123    }
124}
125
126/// A failed assert or a successful report of a stylesheet, as the SVRL report states it.
127#[derive(Debug, Clone, PartialEq, Eq)]
128#[non_exhaustive]
129pub struct Finding {
130    /// Failed assert or successful report.
131    pub kind: FindingKind,
132    /// The rule id (`BR-02`), if the rule has one.
133    pub id: Option<String>,
134    /// The Schematron flag (`fatal`, `warning`), if any.
135    pub flag: Option<String>,
136    /// The severity of the finding (see [`Severity`]): the one the flag stands for,
137    /// unless the manifest of the rule set gives another.
138    pub severity: Severity,
139    /// The Schematron role, if any.
140    pub role: Option<String>,
141    /// The XPath of the node concerned, as the stylesheet writes it.
142    pub location: String,
143    /// The context of the rule that fired (its `svrl:fired-rule/@context`).
144    pub context: Option<String>,
145    /// The id of the pattern the rule belongs to (`svrl:active-pattern/@id`).
146    pub pattern: Option<String>,
147    /// The XPath test of the assert or report.
148    pub test: String,
149    /// The message, whitespace normalised.
150    pub text: String,
151}
152
153/// What one stylesheet of the rule set reported on a document.
154#[derive(Debug, Clone, PartialEq, Eq)]
155#[non_exhaustive]
156pub struct StylesheetReport {
157    /// The stylesheet, by its name in the bundle.
158    pub name: String,
159    /// The version of the rule set it implements.
160    pub version: String,
161    /// The SHA-256 of the stylesheet that ran.
162    pub sha256: String,
163    /// The SVRL report, exactly as the stylesheet wrote it, kept compactly (see
164    /// [`StylesheetReport::svrl`]).
165    svrl: CompactOutput,
166    /// Its failed asserts and successful reports, in report order.
167    pub findings: Vec<Finding>,
168    /// The number of rules that fired (its `svrl:fired-rule` elements): none means the
169    /// stylesheet matched nothing in the document (a document of another syntax, ...).
170    pub fired_rules: usize,
171    /// Recoverable conditions the transformation reported (ambiguous rule matches,
172    /// dynamic errors raised while matching a pattern, after which the rule did not
173    /// match), as the reference engine reports them: each distinct message once.
174    pub warnings: Vec<String>,
175    /// The dynamic error that stopped the stylesheet, if it did not finish: then
176    /// [`StylesheetReport::svrl`] is empty and there are no findings. This only happens
177    /// in a report with schema errors (see
178    /// [`Validator::validate_with`](crate::Validator::validate_with)).
179    pub failure: Option<StylesheetFailure>,
180    pub(crate) document_uri: Option<String>,
181}
182
183/// A dynamic error raised by a stylesheet on a document (the reference engine raises it
184/// as well), which stopped the stylesheet.
185#[derive(Debug, Clone, PartialEq, Eq)]
186#[non_exhaustive]
187pub struct StylesheetFailure {
188    /// The XPath or XSLT error code (`FORG0001`, ...).
189    pub code: String,
190    /// The line of the stylesheet instruction, when known.
191    pub line: Option<u32>,
192    /// The explanation.
193    pub message: String,
194}
195
196impl StylesheetReport {
197    /// The SVRL report, exactly as the stylesheet wrote it: empty when the stylesheet
198    /// did not finish.
199    ///
200    /// It is kept compactly, each distinct piece of its text once (a compiled Schematron
201    /// writes the same `svrl:fired-rule` element each time a rule fires): its text is
202    /// made only when asked for, with [`CompactOutput::to_text`], `to_string()` or
203    /// written with `{}`; it compares equal to a `&str`.
204    #[must_use]
205    pub const fn svrl(&self) -> &CompactOutput {
206        &self.svrl
207    }
208
209    /// The SVRL report in the canonical text form of the `einvoice-svrl` crate (version
210    /// 1, or 2 for a report with `svrl:metadata`), in which the document's URI is written
211    /// `{document}`: the form the expected results of the reference engine are stored
212    /// in.
213    ///
214    /// # Errors
215    ///
216    /// [`Error::Transform`] when the stylesheet did not finish (there is no report);
217    /// [`Error::Internal`] when the report holds something the canonical form cannot
218    /// represent.
219    pub fn canonical_svrl(&self) -> Result<String, Error> {
220        if let Some(failure) = &self.failure {
221            return Err(Error::Transform {
222                stylesheet: self.name.clone(),
223                code: failure.code.clone(),
224                line: failure.line,
225                message: failure.message.clone(),
226            });
227        }
228        let uri = self.document_uri.as_deref();
229        einvoice_svrl::canonicalize(&self.svrl.to_text(), &|u| Some(u) == uri)
230            .map_err(|e| Error::internal(format!("stylesheet {}: {e}", self.name)))
231    }
232
233    /// The report of a stylesheet that finished: its SVRL report, as `reader` read it
234    /// while it was written.
235    pub(crate) fn new(
236        entry: &crate::StylesheetEntry,
237        svrl: CompactOutput,
238        reader: SvrlReader,
239        warnings: Vec<String>,
240        document_uri: Option<&str>,
241    ) -> Result<Self, Error> {
242        // A stylesheet that does not write SVRL is not a validation stylesheet: the
243        // bundle is wrong.
244        let (findings, fired_rules) = reader.finish(&svrl).map_err(|m| {
245            Error::bundle(format!(
246                "stylesheet {}: its result is not an SVRL report: {m}",
247                entry.name()
248            ))
249        })?;
250        Ok(Self {
251            name: entry.name().to_owned(),
252            version: entry.version().to_owned(),
253            sha256: entry.sha256().to_owned(),
254            svrl,
255            findings,
256            fired_rules,
257            warnings,
258            failure: None,
259            document_uri: document_uri.map(str::to_owned),
260        })
261    }
262
263    pub(crate) fn failed(
264        entry: &crate::StylesheetEntry,
265        failure: StylesheetFailure,
266        document_uri: Option<&str>,
267    ) -> Self {
268        Self {
269            name: entry.name().to_owned(),
270            version: entry.version().to_owned(),
271            sha256: entry.sha256().to_owned(),
272            svrl: CompactOutput::default(),
273            findings: Vec::new(),
274            fired_rules: 0,
275            warnings: Vec::new(),
276            failure: Some(failure),
277            document_uri: document_uri.map(str::to_owned),
278        }
279    }
280}
281
282/// The rule set a report was produced with.
283#[derive(Debug, Clone, PartialEq, Eq)]
284#[non_exhaustive]
285pub struct RuleSetVersion {
286    /// Its short name (`cen-ubl`).
287    pub name: String,
288    /// Its title.
289    pub title: String,
290    /// Its version (`1.3.17`).
291    pub version: String,
292    /// The schema the document was validated against, if any.
293    pub schema: Option<crate::SchemaId>,
294    /// The XML schema the reference validator of the rule set also validates documents
295    /// against, and this rule set does not, as its manifest names it
296    /// ([`RuleSet::unchecked_schema`](crate::RuleSet::unchecked_schema)): a document valid
297    /// here may still be rejected there for an error of that schema.
298    pub unchecked_schema: Option<String>,
299}
300
301/// Why a document has no scenario, in a rule set that selects by scenario
302/// ([`RuleSet::selects_by_scenario`](crate::RuleSet::selects_by_scenario)): the document
303/// is then invalid and no stylesheet runs on it, as the KoSIT validator rejects a
304/// document with its fallback scenario.
305#[derive(Debug, Clone, PartialEq, Eq)]
306#[non_exhaustive]
307pub enum NoScenario {
308    /// The `match` expression of no scenario is true on the document.
309    NoneMatches,
310    /// Those of several scenarios are: their names, in the order of the manifest.
311    SeveralMatch(Vec<String>),
312}
313
314impl fmt::Display for NoScenario {
315    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
316        match self {
317            Self::NoneMatches => f.write_str("no scenario of the rule set matches the document"),
318            Self::SeveralMatch(names) => write!(
319                f,
320                "{} scenarios of the rule set match the document, one is required: {}",
321                names.len(),
322                names.join(", ")
323            ),
324        }
325    }
326}
327
328/// The result of validating one document: the schema errors, then what each stylesheet
329/// of the rule set reported.
330#[derive(Debug, Clone, PartialEq, Eq)]
331#[non_exhaustive]
332pub struct Report {
333    /// The rule set used.
334    pub rule_set: RuleSetVersion,
335    /// The URI the document was given, if any (`document-uri(/)` in the stylesheets).
336    pub document_uri: Option<String>,
337    /// The name of the scenario of the rule set the document matched, whose severities
338    /// apply to its findings and, in a rule set that selects by scenario, whose
339    /// stylesheets ran ([`RuleSet::scenarios`](crate::RuleSet::scenarios)), if any.
340    pub scenario: Option<String>,
341    /// In a rule set that selects by scenario, why the document has none, if it has
342    /// none: it is then invalid, no stylesheet ran on it and no schema error is reported
343    /// (the KoSIT validator validates a document against the schema of its scenario).
344    pub no_scenario: Option<NoScenario>,
345    /// The schema validity errors, sorted by position; empty when the document is valid
346    /// against the schema, or when the rule set has no schema.
347    pub schema_errors: Vec<SchemaError>,
348    /// One report per stylesheet that ran, in the order they ran: every stylesheet of
349    /// the rule set, or those of the scenario the document matched in a rule set that
350    /// selects by scenario.
351    pub stylesheets: Vec<StylesheetReport>,
352}
353
354impl Report {
355    /// [`Verdict::Valid`] if there is no schema error and no fatal finding, and, in a
356    /// rule set that selects by scenario, the document matched one.
357    #[must_use]
358    pub fn verdict(&self) -> Verdict {
359        if self.no_scenario.is_none()
360            && self.schema_errors.is_empty()
361            && self.count(Severity::Fatal) == 0
362        {
363            Verdict::Valid
364        } else {
365            Verdict::Invalid
366        }
367    }
368
369    /// Whether every stylesheet ran to the end (see [`StylesheetReport::failure`]).
370    #[must_use]
371    pub fn is_complete(&self) -> bool {
372        self.stylesheets.iter().all(|s| s.failure.is_none())
373    }
374
375    /// Whether the verdict is [`Verdict::Valid`].
376    #[must_use]
377    pub fn is_valid(&self) -> bool {
378        self.verdict() == Verdict::Valid
379    }
380
381    /// Every finding of every stylesheet, in order.
382    pub fn findings(&self) -> impl Iterator<Item = &Finding> {
383        self.stylesheets.iter().flat_map(|s| s.findings.iter())
384    }
385
386    /// The number of findings with the given severity.
387    #[must_use]
388    pub fn count(&self, severity: Severity) -> usize {
389        self.findings().filter(|f| f.severity == severity).count()
390    }
391}
392
393/// How the findings of one stylesheet get their severities: from their flags, the
394/// stylesheet's severity of an unflagged failed assert, the levels of the scenario the
395/// document matched, and whether the validation fails closed.
396#[derive(Debug, Clone, Copy)]
397pub(crate) struct Severities<'a> {
398    /// See [`crate::ValidateOptions::fail_closed`].
399    pub(crate) fail_closed: bool,
400    /// See [`crate::StylesheetEntry::unflagged_assert`].
401    pub(crate) unflagged_assert: Severity,
402    /// The scenario the document matched, if any.
403    pub(crate) scenario: Option<&'a crate::Scenario>,
404}
405
406impl Default for Severities<'_> {
407    fn default() -> Self {
408        Self {
409            fail_closed: false,
410            unflagged_assert: Severity::Other,
411            scenario: None,
412        }
413    }
414}
415
416impl Severities<'_> {
417    /// The severity of a finding: the scenario's level of its rule id, if it gives one;
418    /// otherwise the one its flag stands for ([`Severity::from_flag`]), a failed assert
419    /// without a flag taking the stylesheet's; and when the validation fails closed,
420    /// [`Severity::Fatal`] in place of [`Severity::Other`].
421    pub(crate) fn of(self, kind: FindingKind, flag: Option<&str>, id: Option<&str>) -> Severity {
422        let severity = id
423            .and_then(|id| self.scenario.and_then(|s| s.level(id)))
424            .unwrap_or_else(|| match (kind, flag) {
425                (FindingKind::FailedAssert, None) => self.unflagged_assert,
426                _ => Severity::from_flag(flag),
427            });
428        if self.fail_closed && severity == Severity::Other {
429            Severity::Fatal
430        } else {
431            severity
432        }
433    }
434}
435
436/// Reads the failed asserts and successful reports of an SVRL report as the stylesheet
437/// writes it, with the context of the last fired rule and the id of the last active
438/// pattern before each, and counts the fired rules: what a parser of the report's text
439/// reads, without the text.
440#[derive(Debug, Default)]
441pub(crate) struct SvrlReader<'a> {
442    /// How the findings get their severities.
443    severities: Severities<'a>,
444    /// The number of open elements.
445    depth: usize,
446    /// The number of elements at the top of the report: a document has one.
447    roots: usize,
448    /// Whether the first of them is `svrl:schematron-output`.
449    root_is_svrl: bool,
450    /// Whether a comment holds `--` or ends with `-`, which XML forbids.
451    bad_comment: bool,
452    findings: Vec<Finding>,
453    fired_rules: usize,
454    pattern: Option<String>,
455    context: Option<String>,
456    /// The finding being read.
457    finding: Option<Reading>,
458}
459
460/// A finding being read.
461#[derive(Debug)]
462struct Reading {
463    finding: Finding,
464    /// The text of its `svrl:text` children so far.
465    text: String,
466    /// Whether the text read is in one of them.
467    in_text: bool,
468}
469
470impl<'a> SvrlReader<'a> {
471    pub(crate) fn new(severities: Severities<'a>) -> Self {
472        Self {
473            severities,
474            ..Self::default()
475        }
476    }
477
478    /// The findings and the number of fired rules; or why `svrl`, the text read, is not
479    /// an SVRL report: the error of a parser of the text when it is not well-formed.
480    fn finish(self, svrl: &CompactOutput) -> Result<(Vec<Finding>, usize), String> {
481        if self.roots != 1 || self.bad_comment {
482            // Not a well-formed document: the parser says where.
483            einvoice_xml::check(&svrl.to_text()).map_err(|e| e.to_string())?;
484            if self.roots != 1 {
485                return Err(format!(
486                    "{} elements at the top of the document, instead of one",
487                    self.roots
488                ));
489            }
490        }
491        if !self.root_is_svrl {
492            return Err("the root is not svrl:schematron-output".to_owned());
493        }
494        Ok((self.findings, self.fired_rules))
495    }
496}
497
498/// Whether `name` is the SVRL element `local`.
499fn is_svrl(name: &QName, local: &str) -> bool {
500    name.namespace.as_deref() == Some(SVRL_NS) && name.local == local
501}
502
503/// The value of the attribute in no namespace named `local`.
504fn attribute(attributes: &[(QName, String)], local: &str) -> Option<String> {
505    attributes
506        .iter()
507        .find(|(name, _)| {
508            name.namespace.as_deref().is_none_or(str::is_empty) && name.local == local
509        })
510        .map(|(_, value)| value.clone())
511}
512
513impl ResultObserver for SvrlReader<'_> {
514    fn start_element(&mut self, name: &QName, attributes: &[(QName, String)]) {
515        self.depth += 1;
516        match self.depth {
517            1 => {
518                self.roots += 1;
519                if self.roots == 1 {
520                    self.root_is_svrl = is_svrl(name, "schematron-output");
521                }
522            }
523            // The children of the root.
524            2 if self.roots == 1 && name.namespace.as_deref() == Some(SVRL_NS) => {
525                let kind = match name.local.as_str() {
526                    "active-pattern" => {
527                        self.pattern =
528                            attribute(attributes, "id").or_else(|| attribute(attributes, "name"));
529                        self.context = None;
530                        return;
531                    }
532                    "fired-rule" => {
533                        self.fired_rules += 1;
534                        self.context = attribute(attributes, "context");
535                        return;
536                    }
537                    "failed-assert" => FindingKind::FailedAssert,
538                    "successful-report" => FindingKind::SuccessfulReport,
539                    _ => return,
540                };
541                let flag = attribute(attributes, "flag");
542                let id = attribute(attributes, "id");
543                let severity = self.severities.of(kind, flag.as_deref(), id.as_deref());
544                let finding = Finding {
545                    kind,
546                    id,
547                    severity,
548                    flag,
549                    role: attribute(attributes, "role"),
550                    location: attribute(attributes, "location").unwrap_or_default(),
551                    context: self.context.clone(),
552                    pattern: self.pattern.clone(),
553                    test: attribute(attributes, "test").unwrap_or_default(),
554                    text: String::new(),
555                };
556                self.finding = Some(Reading {
557                    finding,
558                    text: String::new(),
559                    in_text: false,
560                });
561            }
562            // The children of a finding.
563            3 if is_svrl(name, "text") => {
564                if let Some(reading) = &mut self.finding {
565                    reading.in_text = true;
566                }
567            }
568            _ => {}
569        }
570    }
571
572    fn end_element(&mut self) {
573        match self.depth {
574            2 => {
575                if let Some(Reading {
576                    mut finding, text, ..
577                }) = self.finding.take()
578                {
579                    finding.text = einvoice_svrl::normalize_space(&text);
580                    self.findings.push(finding);
581                }
582            }
583            3 => {
584                if let Some(reading) = &mut self.finding {
585                    reading.in_text = false;
586                }
587            }
588            _ => {}
589        }
590        self.depth = self.depth.saturating_sub(1);
591    }
592
593    fn text(&mut self, text: &str) {
594        if let Some(reading) = &mut self.finding
595            && reading.in_text
596        {
597            reading.text.push_str(text);
598        }
599    }
600
601    fn comment(&mut self, text: &str) {
602        if text.contains("--") || text.ends_with('-') {
603            self.bad_comment = true;
604        }
605    }
606}
607
608#[cfg(test)]
609mod tests {
610    use super::*;
611
612    /// The findings of an SVRL report read from its text, the parser's events given to
613    /// [`SvrlReader`] as the serializer gives them.
614    fn findings(svrl: &str, fail_closed: bool) -> Result<(Vec<Finding>, usize), String> {
615        let qname = |name: einvoice_xml::Name<'_, '_>| QName {
616            prefix: (!name.prefix.is_empty()).then(|| name.prefix.to_owned()),
617            namespace: name.namespace.map(str::to_owned),
618            local: name.local.to_owned(),
619        };
620        let mut reader = SvrlReader::new(Severities {
621            fail_closed,
622            ..Severities::default()
623        });
624        let mut parser = einvoice_xml::Reader::new(svrl);
625        let mut depth = 0;
626        while let Ok(Some(event)) = parser.next_event() {
627            match event {
628                einvoice_xml::Event::Start(start) => {
629                    let attributes: Vec<(QName, String)> = start
630                        .attributes()
631                        .map(|a| (qname(a.name), a.value.to_string()))
632                        .collect();
633                    reader.start_element(&qname(start.name()), &attributes);
634                    depth += 1;
635                }
636                einvoice_xml::Event::End(_) => {
637                    reader.end_element();
638                    depth -= 1;
639                }
640                einvoice_xml::Event::Text(text) if depth > 0 => reader.text(&text.value),
641                einvoice_xml::Event::Comment(comment) => reader.comment(&comment.value),
642                _ => {}
643            }
644        }
645        reader.finish(&CompactOutput::from(svrl))
646    }
647
648    #[test]
649    fn reads_findings_with_their_rule_and_pattern() {
650        let svrl = r#"<svrl:schematron-output xmlns:svrl="http://purl.oclc.org/dsdl/svrl">
651  <svrl:active-pattern id="P1"/>
652  <svrl:fired-rule context="/a"/>
653  <svrl:failed-assert id="R-1" flag="fatal" location="/a[1]" test="b">
654    <svrl:text>  [R-1] two
655      lines </svrl:text>
656  </svrl:failed-assert>
657  <svrl:active-pattern name="P2"/>
658  <svrl:successful-report id="R-2" flag="warning" role="r" location="/" test="c"><svrl:text/></svrl:successful-report>
659  <svrl:fired-rule context="/z"/>
660  <svrl:failed-assert location="/" test="d"/>
661</svrl:schematron-output>"#;
662        let (f, fired_rules) = findings(svrl, false).unwrap();
663        assert_eq!(fired_rules, 2);
664        assert_eq!(f.len(), 3);
665        assert_eq!(f[0].kind, FindingKind::FailedAssert);
666        assert_eq!(f[0].id.as_deref(), Some("R-1"));
667        assert_eq!(f[0].severity, Severity::Fatal);
668        assert_eq!(f[0].context.as_deref(), Some("/a"));
669        assert_eq!(f[0].pattern.as_deref(), Some("P1"));
670        assert_eq!(f[0].text, "[R-1] two lines");
671        assert_eq!(f[1].kind, FindingKind::SuccessfulReport);
672        assert_eq!(f[1].severity, Severity::Warning);
673        assert_eq!(f[1].role.as_deref(), Some("r"));
674        assert_eq!(f[1].context, None);
675        assert_eq!(f[1].pattern.as_deref(), Some("P2"));
676        assert_eq!(f[2].severity, Severity::Other);
677        assert_eq!(f[2].id, None);
678        assert_eq!(f[2].context.as_deref(), Some("/z"));
679        let (closed, _) = findings(svrl, true).unwrap();
680        let severities: Vec<Severity> = closed.iter().map(|f| f.severity).collect();
681        assert_eq!(
682            severities,
683            [Severity::Fatal, Severity::Warning, Severity::Fatal]
684        );
685    }
686
687    /// The error of the parser that read the reports before (`roxmltree`), which the
688    /// streaming parser reproduces.
689    fn parser_error(text: &str) -> String {
690        let options = roxmltree::ParsingOptions {
691            allow_dtd: false,
692            nodes_limit: u32::MAX,
693            ..roxmltree::ParsingOptions::default()
694        };
695        let roxmltree = roxmltree::Document::parse_with_options(text, options)
696            .unwrap_err()
697            .to_string();
698        assert_eq!(
699            einvoice_xml::check(text).unwrap_err().to_string(),
700            roxmltree
701        );
702        roxmltree
703    }
704
705    fn svrl_name(local: &str) -> QName {
706        QName {
707            prefix: Some("svrl".to_owned()),
708            namespace: Some(SVRL_NS.to_owned()),
709            local: local.to_owned(),
710        }
711    }
712
713    #[test]
714    fn refuses_what_is_not_svrl() {
715        assert_eq!(
716            findings("<a/>", false).unwrap_err(),
717            "the root is not svrl:schematron-output"
718        );
719        // Not well-formed: the parser's error.
720        for text in ["<a", ""] {
721            assert_eq!(
722                findings(text, false).unwrap_err(),
723                parser_error(text),
724                "{text}"
725            );
726        }
727        // What the serializer can write and a parser refuses (the parser stops before
728        // giving the events): two elements at the top, comments that XML forbids.
729        let root = svrl_name("schematron-output");
730        let mut reader = SvrlReader::default();
731        for _ in 0..2 {
732            reader.start_element(&root, &[]);
733            reader.end_element();
734        }
735        let text = format!("<svrl:schematron-output xmlns:svrl=\"{SVRL_NS}\"/><a/>");
736        assert_eq!(
737            reader.finish(&CompactOutput::from(text.as_str())),
738            Err(parser_error(&text))
739        );
740        for comment in ["x -- y", "x-"] {
741            let mut reader = SvrlReader::default();
742            reader.start_element(&root, &[]);
743            reader.comment(comment);
744            reader.end_element();
745            let text = format!(
746                "<svrl:schematron-output xmlns:svrl=\"{SVRL_NS}\"><!--{comment}--></svrl:schematron-output>"
747            );
748            assert_eq!(
749                reader.finish(&CompactOutput::from(text.as_str())),
750                Err(parser_error(&text)),
751                "{comment}"
752            );
753        }
754        // Events the text does not have, which the parser accepts.
755        let mut reader = SvrlReader::default();
756        for _ in 0..2 {
757            reader.start_element(&root, &[]);
758            reader.end_element();
759        }
760        assert_eq!(
761            reader.finish(&CompactOutput::from("<a/>")).unwrap_err(),
762            "2 elements at the top of the document, instead of one"
763        );
764    }
765
766    #[test]
767    fn severities() {
768        assert_eq!(Severity::from_flag(Some("fatal")), Severity::Fatal);
769        assert_eq!(Severity::from_flag(Some("warning")), Severity::Warning);
770        assert_eq!(Severity::from_flag(Some("information")), Severity::Other);
771        assert_eq!(Severity::from_flag(None), Severity::Other);
772        assert_eq!(
773            Severity::from_flag_fail_closed(Some("fatal")),
774            Severity::Fatal
775        );
776        assert_eq!(
777            Severity::from_flag_fail_closed(Some("warning")),
778            Severity::Warning
779        );
780        assert_eq!(
781            Severity::from_flag_fail_closed(Some("information")),
782            Severity::Fatal
783        );
784        assert_eq!(Severity::from_flag_fail_closed(None), Severity::Fatal);
785    }
786
787    /// The severities of the findings of a stylesheet, as the manifest and the options
788    /// set them.
789    #[test]
790    fn severities_of_a_stylesheet() {
791        use FindingKind::{FailedAssert as A, SuccessfulReport as R};
792        let manifest = "format = 2\nname = \"n\"\ntitle = \"t\"\nversion = \"1\"\n\n[[stylesheet]]\nname = \"s\"\npath = \"s.xsl\"\nsha256 = \"0000000000000000000000000000000000000000000000000000000000000000\"\n\n[[scenario]]\nname = \"x\"\nnamespace = \"urn:oasis:names:specification:ubl:schema:xsd:Invoice-2\"\nroot = \"Invoice\"\nidentifier = \"urn:x\"\nfatal = \"UP\"\nother = \"DOWN\"\n";
793        let rule_set = crate::RuleSet::parse(manifest).unwrap();
794        let scenario = rule_set.scenarios().first();
795        let findings = [
796            (A, Some("fatal"), Some("R")),
797            (A, Some("warning"), Some("R")),
798            (A, Some("information"), Some("R")),
799            (A, None, Some("R")),
800            (A, None, None),
801            (R, None, Some("R")),
802            (R, Some("fatal"), None),
803            (A, Some("warning"), Some("UP")),
804            (R, None, Some("UP")),
805            (A, Some("fatal"), Some("DOWN")),
806            (A, None, Some("DOWN")),
807        ];
808        let severities = |severities: Severities<'_>| -> Vec<&str> {
809            findings
810                .iter()
811                .map(|(kind, flag, id)| severities.of(*kind, *flag, *id).as_str())
812                .collect()
813        };
814        let base = Severities::default();
815        assert_eq!(
816            severities(base),
817            [
818                "fatal", "warning", "other", "other", "other", "other", "fatal", "warning",
819                "other", "fatal", "other"
820            ]
821        );
822        // An unflagged failed assert is fatal: an unflagged successful report is not.
823        let unflagged = Severities {
824            unflagged_assert: Severity::Fatal,
825            ..base
826        };
827        assert_eq!(
828            severities(unflagged),
829            [
830                "fatal", "warning", "other", "fatal", "fatal", "other", "fatal", "warning",
831                "other", "fatal", "fatal"
832            ]
833        );
834        // The scenario's levels win over the flags and over the unflagged severity.
835        let with_scenario = Severities {
836            scenario,
837            ..unflagged
838        };
839        assert_eq!(
840            severities(with_scenario),
841            [
842                "fatal", "warning", "other", "fatal", "fatal", "other", "fatal", "fatal", "fatal",
843                "other", "other"
844            ]
845        );
846        // Failing closed: whatever is still other is fatal.
847        let closed = Severities {
848            fail_closed: true,
849            ..with_scenario
850        };
851        assert_eq!(
852            severities(closed),
853            [
854                "fatal", "warning", "fatal", "fatal", "fatal", "fatal", "fatal", "fatal", "fatal",
855                "fatal", "fatal"
856            ]
857        );
858    }
859}