use std::borrow::Cow;
use std::sync::Arc;
use crate::model::Span;
use crate::validator::ValidationLayer;
#[must_use]
pub fn severity_for_error(error: &crate::EdifactError) -> ValidationSeverity {
use crate::EdifactError as E;
match error {
E::InvalidCodeValue { .. }
| E::BlankDataElementValue { .. }
| E::TrailingSeparator { .. }
| E::InsignificantCharacters { .. } => ValidationSeverity::Warning,
_ => ValidationSeverity::Error,
}
}
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum ValidationSeverity {
Critical,
Error,
Warning,
Info,
}
impl ValidationSeverity {
#[must_use]
pub fn as_str(self) -> &'static str {
match self {
Self::Critical => "critical",
Self::Error => "error",
Self::Warning => "warning",
Self::Info => "info",
#[allow(unreachable_patterns)]
_ => "unknown",
}
}
#[must_use]
pub fn numeric_level(self) -> u8 {
match self {
Self::Info => 0,
Self::Warning => 1,
Self::Error => 2,
Self::Critical => 3,
#[allow(unreachable_patterns)]
_ => 0,
}
}
}
impl Ord for ValidationSeverity {
#[inline]
fn cmp(&self, other: &Self) -> std::cmp::Ordering {
self.numeric_level().cmp(&other.numeric_level())
}
}
impl PartialOrd for ValidationSeverity {
#[inline]
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
Some(self.cmp(other))
}
}
impl std::fmt::Display for ValidationSeverity {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(self.as_str())
}
}
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum FindingKind {
Missing,
NotPermitted,
Code,
Representation,
Count,
Placement,
ControlMismatch,
Duplicate,
Envelope,
Charset,
Syntax,
Limit,
Unsupported,
#[cfg_attr(feature = "serde", serde(other))]
Other,
}
impl FindingKind {
#[must_use]
pub fn as_str(self) -> &'static str {
match self {
Self::Missing => "missing",
Self::NotPermitted => "not_permitted",
Self::Code => "code",
Self::Representation => "representation",
Self::Count => "count",
Self::Placement => "placement",
Self::ControlMismatch => "control_mismatch",
Self::Duplicate => "duplicate",
Self::Envelope => "envelope",
Self::Charset => "charset",
Self::Syntax => "syntax",
Self::Limit => "limit",
Self::Unsupported => "unsupported",
Self::Other => "other",
}
}
#[must_use]
pub fn for_error(error: &crate::EdifactError) -> FindingKind {
use crate::EdifactError as E;
match error {
E::UnexpectedEof { .. }
| E::InvalidDelimiter { .. }
| E::InvalidSegmentTag(_)
| E::InvalidUna
| E::InvalidReleaseSequence { .. }
| E::UnexpectedDataToken { .. }
| E::RepetitionSeparatorNotDeclared
| E::SegmentWithoutDataElements { .. }
| E::TrailingSeparator { .. } => Self::Syntax,
E::InvalidText { .. }
| E::InvalidUtf8
| E::UnrecognisedSyntaxIdentifier(_)
| E::CharacterNotInRepertoire { .. }
| E::UnsupportedCharset { .. }
| E::CharacterRepertoireMismatch { .. } => Self::Charset,
E::MessageCountMismatch { .. }
| E::GroupCountMismatch { .. }
| E::SegmentCountMismatch { .. }
| E::QualifierMismatch { .. } => Self::ControlMismatch,
E::MissingRequiredElement { .. }
| E::MissingSegment { .. }
| E::ConditionalRequirementNotMet { .. }
| E::MissingRequiredComponent { .. } => Self::Missing,
E::InvalidSegmentForMessage { .. } | E::SegmentNotPlaced { .. } => Self::Placement,
E::ReservedServiceSegmentTag { .. } => Self::NotPermitted,
E::InvalidElementCount { .. }
| E::InvalidComponentCount { .. }
| E::TooManyRepetitions { .. }
| E::TooManySegmentOccurrences { .. }
| E::TooManyGroupOccurrences { .. } => Self::Count,
E::InvalidCodeValue { .. } => Self::Code,
E::SegmentTooLong { .. } | E::InterchangeTooLarge { .. } | E::LimitExceeded { .. } => {
Self::Limit
}
E::InvalidFieldValue { .. }
| E::NonFiniteNumber { .. }
| E::BlankDataElementValue { .. }
| E::InvalidCharacterType { .. }
| E::DataElementTooLong { .. }
| E::DataElementTooShort { .. }
| E::InsignificantCharacters { .. }
| E::InvalidDateTime { .. } => Self::Representation,
E::DuplicateReference { .. } => Self::Duplicate,
E::EmptyInterchange { .. }
| E::EmptyMessage { .. }
| E::GroupsAndMessagesMixed { .. }
| E::EmptyGroup { .. }
| E::DataAfterInterchangeTrailer { .. } => Self::Envelope,
E::PackageNotSupported { .. }
| E::InteractiveSegmentNotSupported { .. }
| E::SecuritySegmentNotSupported { .. }
| E::UnsupportedSyntaxVersion { .. } => Self::Unsupported,
E::Io(_)
| E::InvalidEventSequence { .. }
| E::InvalidElementPosition
| E::IncompatibleReleaseScopes { .. }
| E::ValidationErrors { .. }
| E::UnknownDataElement { .. }
| E::AmbiguousDataElement { .. }
| E::SegmentLayoutMismatch { .. }
| E::ActionNotPermitted { .. }
| E::InvalidContrlIdentifier { .. }
| E::InvalidGroupSchema { .. }
| E::WriterPoisoned { .. } => Self::Other,
}
}
}
impl std::fmt::Display for FindingKind {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(self.as_str())
}
}
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct GroupStep {
#[cfg_attr(feature = "serde", serde(rename = "group"))]
pub name: Arc<str>,
pub occurrence: u32,
}
impl GroupStep {
#[must_use]
pub fn new(name: impl Into<Arc<str>>, occurrence: usize) -> Option<Self> {
Some(Self {
name: name.into(),
occurrence: u32::try_from(occurrence).ok()?,
})
}
}
impl std::fmt::Display for GroupStep {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"{}[{}]",
crate::error::escape_control(&self.name),
self.occurrence
)
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct GroupPath(Arc<[GroupStep]>);
impl GroupPath {
#[must_use]
pub fn new(steps: impl IntoIterator<Item = GroupStep>) -> Option<Self> {
let steps: Arc<[GroupStep]> = steps.into_iter().collect();
(!steps.is_empty()).then_some(Self(steps))
}
#[must_use]
pub fn child(&self, name: impl Into<Arc<str>>, occurrence: usize) -> Option<Self> {
let step = GroupStep::new(name, occurrence)?;
Some(Self(self.0.iter().cloned().chain([step]).collect()))
}
#[must_use]
pub fn steps(&self) -> &[GroupStep] {
&self.0
}
#[must_use]
pub fn last(&self) -> &GroupStep {
&self.0[self.0.len() - 1]
}
#[must_use]
pub fn depth(&self) -> usize {
self.0.len()
}
}
impl std::fmt::Display for GroupPath {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
for (i, step) in self.0.iter().enumerate() {
if i > 0 {
f.write_str("/")?;
}
std::fmt::Display::fmt(step, f)?;
}
Ok(())
}
}
#[cfg(feature = "serde")]
impl serde::Serialize for GroupPath {
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
serde::Serialize::serialize(&*self.0, serializer)
}
}
#[cfg(feature = "serde")]
impl<'de> serde::Deserialize<'de> for GroupPath {
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
let steps = <Vec<GroupStep> as serde::Deserialize>::deserialize(deserializer)?;
GroupPath::new(steps)
.ok_or_else(|| serde::de::Error::custom("a group path has at least one step"))
}
}
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct ValidationIssue {
#[cfg_attr(
feature = "serde",
serde(default, skip_serializing_if = "Option::is_none")
)]
pub error_code: Option<Cow<'static, str>>,
pub severity: ValidationSeverity,
pub message: String,
pub span: Option<Span>,
pub segment_tag: Option<String>,
pub rule_id: Option<String>,
pub element_index: Option<u16>,
pub component_index: Option<u16>,
pub segment_occurrence: Option<u32>,
#[cfg_attr(
feature = "serde",
serde(default, skip_serializing_if = "Option::is_none")
)]
pub segment_position: Option<u32>,
pub message_ref: Option<String>,
pub suggestion: Option<String>,
pub segment_group: Option<Arc<str>>,
#[cfg_attr(
feature = "serde",
serde(default, skip_serializing_if = "Option::is_none")
)]
pub group_path: Option<GroupPath>,
#[cfg_attr(
feature = "serde",
serde(default, skip_serializing_if = "Option::is_none")
)]
pub layer: Option<ValidationLayer>,
#[cfg_attr(
feature = "serde",
serde(default, skip_serializing_if = "Option::is_none")
)]
pub kind: Option<FindingKind>,
#[cfg_attr(
feature = "serde",
serde(default, skip_serializing_if = "Option::is_none")
)]
pub pack: Option<Arc<str>>,
#[cfg_attr(
feature = "serde",
serde(default, skip_serializing_if = "Vec::is_empty")
)]
pub context: Vec<(String, String)>,
}
impl ValidationIssue {
pub fn new(severity: ValidationSeverity, message: impl Into<String>) -> Self {
Self {
error_code: None,
severity,
message: message.into(),
span: None,
segment_tag: None,
rule_id: None,
element_index: None,
component_index: None,
segment_occurrence: None,
segment_position: None,
message_ref: None,
suggestion: None,
segment_group: None,
group_path: None,
layer: None,
kind: None,
pack: None,
context: Vec::new(),
}
}
pub fn with_error_code(mut self, code: impl Into<Cow<'static, str>>) -> Self {
self.error_code = Some(code.into());
self
}
pub fn with_span(mut self, span: Span) -> Self {
self.span = Some(span);
self
}
pub fn with_segment(mut self, tag: impl Into<String>) -> Self {
self.segment_tag = Some(tag.into());
self
}
pub fn with_rule_id(mut self, rule_id: impl Into<String>) -> Self {
self.rule_id = Some(rule_id.into());
self
}
pub fn with_element_index(mut self, element_index: usize) -> Self {
self.element_index = u16::try_from(element_index).ok();
self
}
pub fn with_component_index(mut self, component_index: usize) -> Self {
self.component_index = u16::try_from(component_index).ok();
self
}
pub fn with_suggestion(mut self, suggestion: impl Into<String>) -> Self {
self.suggestion = Some(suggestion.into());
self
}
pub fn with_segment_occurrence(mut self, occurrence: usize) -> Self {
self.segment_occurrence = u32::try_from(occurrence).ok();
self
}
pub fn with_segment_position(mut self, position: usize) -> Self {
self.segment_position = u32::try_from(position).ok();
self
}
pub fn with_group_path(mut self, path: GroupPath) -> Self {
if self.segment_group.is_none() {
self.segment_group = Some(Arc::clone(&path.last().name));
}
self.group_path = Some(path);
self
}
pub fn with_layer(mut self, layer: ValidationLayer) -> Self {
self.layer = Some(layer);
self
}
pub fn with_kind(mut self, kind: FindingKind) -> Self {
self.kind = Some(kind);
self
}
pub fn with_pack(mut self, pack: impl Into<Arc<str>>) -> Self {
self.pack = Some(pack.into());
self
}
pub fn with_message_ref(mut self, message_ref: impl Into<String>) -> Self {
self.message_ref = Some(message_ref.into());
self
}
pub fn with_segment_group(mut self, group: impl Into<Arc<str>>) -> Self {
self.segment_group = Some(group.into());
self
}
pub fn with_context_entry(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
let key = key.into();
let value = value.into();
if let Some(entry) = self.context.iter_mut().find(|(k, _)| k == &key) {
entry.1 = value;
} else {
self.context.push((key, value));
}
self
}
pub fn with_context_entries<K, V, I>(mut self, entries: I) -> Self
where
K: Into<String>,
V: Into<String>,
I: IntoIterator<Item = (K, V)>,
{
for (k, v) in entries {
let k = k.into();
let v = v.into();
if let Some(entry) = self.context.iter_mut().find(|(key, _)| key == &k) {
entry.1 = v;
} else {
self.context.push((k, v));
}
}
self
}
#[must_use]
#[inline]
pub fn context_get(&self, key: &str) -> Option<&str> {
self.context
.iter()
.find(|(k, _)| k == key)
.map(|(_, v)| v.as_str())
}
#[must_use]
pub fn severity_label(&self) -> &'static str {
match self.severity {
ValidationSeverity::Critical => "CRITICAL",
ValidationSeverity::Error => "ERROR",
ValidationSeverity::Warning => "WARNING",
ValidationSeverity::Info => "INFO",
#[allow(unreachable_patterns)]
_ => "UNKNOWN",
}
}
#[must_use]
#[inline]
pub fn error_code(&self) -> Option<&str> {
self.error_code.as_deref()
}
#[must_use]
#[inline]
pub fn span(&self) -> Option<Span> {
self.span
}
#[must_use]
#[inline]
pub fn start_offset(&self) -> Option<usize> {
self.span.map(|s| s.start)
}
#[must_use]
#[inline]
pub fn segment_tag(&self) -> Option<&str> {
self.segment_tag.as_deref()
}
#[must_use]
#[inline]
pub fn rule_id(&self) -> Option<&str> {
self.rule_id.as_deref()
}
#[must_use]
#[inline]
pub fn element_index(&self) -> Option<u16> {
self.element_index
}
#[must_use]
#[inline]
pub fn component_index(&self) -> Option<u16> {
self.component_index
}
#[must_use]
#[inline]
pub fn segment_occurrence(&self) -> Option<u32> {
self.segment_occurrence
}
#[must_use]
#[inline]
pub fn segment_position(&self) -> Option<u32> {
self.segment_position
}
#[must_use]
#[inline]
pub fn group_path(&self) -> Option<&GroupPath> {
self.group_path.as_ref()
}
#[must_use]
#[inline]
pub fn layer(&self) -> Option<ValidationLayer> {
self.layer
}
#[must_use]
#[inline]
pub fn kind(&self) -> Option<FindingKind> {
self.kind
}
#[must_use]
#[inline]
pub fn pack(&self) -> Option<&str> {
self.pack.as_deref()
}
#[must_use]
#[inline]
pub fn message_ref(&self) -> Option<&str> {
self.message_ref.as_deref()
}
#[must_use]
#[inline]
pub fn suggestion(&self) -> Option<&str> {
self.suggestion.as_deref()
}
#[must_use]
#[inline]
pub fn segment_group(&self) -> Option<&str> {
self.segment_group.as_deref()
}
}
impl std::fmt::Display for ValidationIssue {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"[{}] {}",
self.severity_label(),
crate::error::escape_control(&self.message)
)
}
}
impl std::error::Error for ValidationIssue {}
#[derive(Debug, Clone, Default, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct ValidationReport {
pub(crate) errors: Vec<ValidationIssue>,
pub(crate) warnings: Vec<ValidationIssue>,
pub(crate) infos: Vec<ValidationIssue>,
}
impl ValidationReport {
pub fn from_issues(
errors: Vec<ValidationIssue>,
warnings: Vec<ValidationIssue>,
infos: Vec<ValidationIssue>,
) -> Self {
Self {
errors,
warnings,
infos,
}
}
pub fn errors(&self) -> &[ValidationIssue] {
&self.errors
}
pub fn errors_mut(&mut self) -> &mut [ValidationIssue] {
&mut self.errors
}
pub fn warnings(&self) -> &[ValidationIssue] {
&self.warnings
}
pub fn warnings_mut(&mut self) -> &mut [ValidationIssue] {
&mut self.warnings
}
pub fn infos(&self) -> &[ValidationIssue] {
&self.infos
}
pub fn infos_mut(&mut self) -> &mut [ValidationIssue] {
&mut self.infos
}
pub fn add_error(&mut self, issue: ValidationIssue) {
self.errors.push(issue);
}
pub fn add_warning(&mut self, issue: ValidationIssue) {
self.warnings.push(issue);
}
pub fn add_info(&mut self, issue: ValidationIssue) {
self.infos.push(issue);
}
pub fn has_errors(&self) -> bool {
!self.errors().is_empty()
}
pub fn has_critical_errors(&self) -> bool {
self.errors
.iter()
.any(|i| i.severity == ValidationSeverity::Critical)
}
pub fn has_warnings(&self) -> bool {
!self.warnings().is_empty()
}
pub fn total_issues(&self) -> usize {
self.errors().len() + self.warnings().len() + self.infos().len()
}
pub fn is_valid(&self) -> bool {
self.errors().is_empty()
}
pub fn result(self) -> Result<Self, Self> {
if self.is_valid() { Ok(self) } else { Err(self) }
}
pub fn iter_issues(&self) -> impl Iterator<Item = &ValidationIssue> {
self.errors()
.iter()
.chain(self.warnings().iter())
.chain(self.infos().iter())
}
pub fn has_any_issues(&self) -> bool {
!self.errors().is_empty() || !self.warnings().is_empty() || !self.infos().is_empty()
}
pub fn merge(&mut self, mut other: ValidationReport) {
self.errors.append(&mut other.errors);
self.warnings.append(&mut other.warnings);
self.infos.append(&mut other.infos);
}
pub fn extend_from(&mut self, other: &ValidationReport) {
for issue in &other.errors {
self.add_error(issue.clone());
}
for issue in &other.warnings {
self.add_warning(issue.clone());
}
for issue in &other.infos {
self.add_info(issue.clone());
}
}
pub fn issues_for_rule_id<'a>(
&'a self,
rule_id: &'a str,
) -> impl Iterator<Item = &'a ValidationIssue> + 'a {
self.iter_issues()
.filter(move |issue| issue.rule_id.as_deref() == Some(rule_id))
}
fn filter_report<F>(&self, pred: F) -> Self
where
F: Fn(&ValidationIssue) -> bool,
{
let errors: Vec<ValidationIssue> =
self.errors().iter().filter(|i| pred(i)).cloned().collect();
Self {
errors,
warnings: self
.warnings()
.iter()
.filter(|i| pred(i))
.cloned()
.collect(),
infos: self.infos().iter().filter(|i| pred(i)).cloned().collect(),
}
}
pub fn filter_by_rule_id(&self, rule_id: &str) -> Self {
self.filter_report(|issue| issue.rule_id.as_deref() == Some(rule_id))
}
pub fn filter_by_rule_prefix(&self, prefix: &str) -> Self {
self.filter_report(|issue| {
issue
.rule_id
.as_deref()
.is_some_and(|id| id.starts_with(prefix))
})
}
pub fn for_segment(&self, segment_tag: &str) -> Self {
self.filter_report(|issue| issue.segment_tag.as_deref() == Some(segment_tag))
}
pub fn render_deterministic(&self) -> String {
fn none_last<T: Ord>(left: Option<T>, right: Option<T>) -> std::cmp::Ordering {
match (left, right) {
(Some(l), Some(r)) => l.cmp(&r),
(Some(_), None) => std::cmp::Ordering::Less,
(None, Some(_)) => std::cmp::Ordering::Greater,
(None, None) => std::cmp::Ordering::Equal,
}
}
fn path_key(issue: &ValidationIssue) -> Option<Vec<(&str, u32)>> {
issue.group_path.as_ref().map(|path| {
path.steps()
.iter()
.map(|step| (&*step.name, step.occurrence))
.collect()
})
}
fn sorted_refs(issues: &[ValidationIssue]) -> Vec<&ValidationIssue> {
let mut refs: Vec<&ValidationIssue> = issues.iter().collect();
refs.sort_by(|left, right| {
left.start_offset()
.unwrap_or(usize::MAX)
.cmp(&right.start_offset().unwrap_or(usize::MAX))
.then_with(|| {
left.segment_tag
.as_deref()
.unwrap_or("")
.cmp(right.segment_tag.as_deref().unwrap_or(""))
})
.then_with(|| {
left.rule_id
.as_deref()
.unwrap_or("")
.cmp(right.rule_id.as_deref().unwrap_or(""))
})
.then_with(|| none_last(left.element_index, right.element_index))
.then_with(|| none_last(left.component_index, right.component_index))
.then_with(|| {
left.error_code()
.unwrap_or("")
.cmp(right.error_code().unwrap_or(""))
})
.then_with(|| left.message.cmp(&right.message))
.then_with(|| none_last(left.segment_position, right.segment_position))
.then_with(|| none_last(left.segment_occurrence, right.segment_occurrence))
.then_with(|| {
none_last(
left.layer.map(|l| l.as_str()),
right.layer.map(|l| l.as_str()),
)
})
.then_with(|| {
none_last(
left.kind.map(FindingKind::as_str),
right.kind.map(FindingKind::as_str),
)
})
.then_with(|| none_last(left.pack(), right.pack()))
.then_with(|| none_last(path_key(left), path_key(right)))
});
refs
}
fn render_issue_line(out: &mut String, issue: &ValidationIssue) {
use std::fmt::Write as _;
let mut line = String::new();
render_issue_fields(&mut line, issue);
write!(out, " - {}", crate::error::escape_control(&line)).ok();
}
fn render_issue_fields(out: &mut String, issue: &ValidationIssue) {
use std::fmt::Write as _;
out.push_str(&issue.message);
if let Some(code) = issue.error_code() {
out.push_str(" [");
out.push_str(code);
out.push(']');
}
if let Some(seg) = &issue.segment_tag {
out.push_str(" [segment=");
out.push_str(seg);
out.push(']');
}
if let Some(rule_id) = &issue.rule_id {
out.push_str(" [rule=");
out.push_str(rule_id);
out.push(']');
}
if let Some(element_index) = issue.element_index {
write!(out, " [element={element_index}]").ok();
}
if let Some(component_index) = issue.component_index {
write!(out, " [component={component_index}]").ok();
}
if let Some(occurrence) = issue.segment_occurrence {
write!(out, " [occurrence={occurrence}]").ok();
}
if let Some(position) = issue.segment_position {
write!(out, " [position={position}]").ok();
}
if let Some(path) = &issue.group_path {
write!(out, " [path={path}").ok();
if let Some(seg) = &issue.segment_tag {
out.push('/');
out.push_str(seg);
}
out.push(']');
}
if let Some(layer) = issue.layer {
write!(out, " [layer={}]", layer.as_str()).ok();
}
if let Some(kind) = issue.kind {
write!(out, " [kind={kind}]").ok();
}
if let Some(pack) = &issue.pack {
write!(out, " [pack={pack}]").ok();
}
if let Some(span) = issue.span {
write!(out, " [span={span}]").ok();
}
if let Some(suggestion) = &issue.suggestion {
out.push_str(" [hint=");
out.push_str(suggestion);
out.push(']');
}
}
use std::fmt::Write as _;
let mut out = String::from("Validation Report:");
let errors = sorted_refs(self.errors());
let warnings = sorted_refs(self.warnings());
let infos = sorted_refs(self.infos());
if !errors.is_empty() {
write!(out, "\n Errors ({})", errors.len()).ok();
for issue in &errors {
out.push('\n');
render_issue_line(&mut out, issue);
}
}
if !warnings.is_empty() {
write!(out, "\n Warnings ({})", warnings.len()).ok();
for issue in &warnings {
out.push('\n');
render_issue_line(&mut out, issue);
}
}
if !infos.is_empty() {
write!(out, "\n Info ({})", infos.len()).ok();
for issue in &infos {
out.push('\n');
render_issue_line(&mut out, issue);
}
}
out
}
}
#[cfg(feature = "diagnostics")]
#[cfg_attr(docsrs, doc(cfg(feature = "diagnostics")))]
impl miette::Diagnostic for ValidationIssue {
fn code<'a>(&'a self) -> Option<Box<dyn std::fmt::Display + 'a>> {
self.error_code()
.or(self.rule_id())
.map(|code| Box::new(code) as Box<dyn std::fmt::Display + 'a>)
}
fn severity(&self) -> Option<miette::Severity> {
Some(match self.severity {
ValidationSeverity::Critical | ValidationSeverity::Error => miette::Severity::Error,
ValidationSeverity::Warning => miette::Severity::Warning,
ValidationSeverity::Info => miette::Severity::Advice,
})
}
fn help<'a>(&'a self) -> Option<Box<dyn std::fmt::Display + 'a>> {
self.suggestion().map(|hint| {
Box::new(crate::error::escape_control(hint)) as Box<dyn std::fmt::Display + 'a>
})
}
fn labels(&self) -> Option<Box<dyn Iterator<Item = miette::LabeledSpan> + '_>> {
let span = self.span?;
let location = match (&self.group_path, &self.segment_tag) {
(Some(path), Some(tag)) => Some(format!("{path}/{tag}")),
(Some(path), None) => Some(path.to_string()),
(None, Some(tag)) => Some(tag.clone()),
(None, None) => None,
};
let text = match (self.kind, location) {
(Some(kind), Some(location)) => Some(format!("{kind} at {location}")),
(Some(kind), None) => Some(kind.as_str().to_owned()),
(None, location) => location,
}
.map(|text| crate::error::escape_control(&text).to_string());
Some(Box::new(std::iter::once(miette::LabeledSpan::new(
text,
span.start,
span.end.saturating_sub(span.start),
))))
}
}
#[cfg(feature = "diagnostics")]
#[cfg_attr(docsrs, doc(cfg(feature = "diagnostics")))]
impl miette::Diagnostic for ValidationReport {
fn code<'a>(&'a self) -> Option<Box<dyn std::fmt::Display + 'a>> {
Some(Box::new("VALIDATION"))
}
fn severity(&self) -> Option<miette::Severity> {
if self.has_errors() {
Some(miette::Severity::Error)
} else if self.has_warnings() {
Some(miette::Severity::Warning)
} else {
Some(miette::Severity::Advice)
}
}
fn help<'a>(&'a self) -> Option<Box<dyn std::fmt::Display + 'a>> {
let msg = format!(
"Validation found {} error(s), {} warning(s), {} info(s)",
self.errors().len(),
self.warnings().len(),
self.infos().len()
);
Some(Box::new(msg))
}
fn related<'a>(&'a self) -> Option<Box<dyn Iterator<Item = &'a dyn miette::Diagnostic> + 'a>> {
if !self.has_any_issues() {
return None;
}
Some(Box::new(
self.iter_issues()
.map(|issue| issue as &dyn miette::Diagnostic),
))
}
}
impl std::fmt::Display for ValidationReport {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.render_deterministic())
}
}
impl std::error::Error for ValidationReport {}
impl Extend<ValidationIssue> for ValidationReport {
fn extend<I: IntoIterator<Item = ValidationIssue>>(&mut self, iter: I) {
for issue in iter {
match issue.severity {
ValidationSeverity::Critical | ValidationSeverity::Error => {
self.add_error(issue);
}
ValidationSeverity::Warning => {
self.add_warning(issue);
}
_ => {
self.add_info(issue);
}
}
}
}
}
impl FromIterator<ValidationIssue> for ValidationReport {
fn from_iter<I: IntoIterator<Item = ValidationIssue>>(iter: I) -> Self {
let mut report = ValidationReport::default();
report.extend(iter);
report
}
}
#[cfg(test)]
mod tests {
#[test]
fn severity_orders_by_severity_not_declaration_order() {
use ValidationSeverity::*;
assert!(Critical > Error);
assert!(Error > Warning);
assert!(Warning > Info);
let mut levels = vec![Warning, Critical, Info, Error];
levels.sort();
assert_eq!(levels, vec![Info, Warning, Error, Critical]);
assert_eq!(levels.iter().copied().max(), Some(Critical));
}
use super::*;
#[test]
fn report_collects_errors_and_warnings() {
let mut report = ValidationReport::default();
report.add_error(
ValidationIssue::new(ValidationSeverity::Error, "Test error")
.with_segment("BGM")
.with_span(Span::new(42, 57)),
);
report.add_warning(ValidationIssue::new(
ValidationSeverity::Warning,
"Test warning",
));
assert!(report.has_errors());
assert!(report.has_warnings());
assert_eq!(report.total_issues(), 2);
assert!(!report.is_valid());
}
#[test]
fn report_result_conversion() {
let mut report = ValidationReport::default();
report.add_error(ValidationIssue::new(
ValidationSeverity::Error,
"Critical issue",
));
assert!(report.result().is_err());
}
#[test]
fn report_valid_with_only_warnings() {
let mut report = ValidationReport::default();
report.add_warning(ValidationIssue::new(
ValidationSeverity::Warning,
"Just a warning",
));
assert!(report.is_valid());
assert!(report.result().is_ok());
}
#[test]
fn issue_builder_chain() {
let issue = ValidationIssue::new(ValidationSeverity::Warning, "test message")
.with_error_code("E013")
.with_span(Span::new(100, 118))
.with_segment("NAD")
.with_rule_id("DEMO-P001")
.with_element_index(1)
.with_component_index(2)
.with_suggestion("Check element count");
assert_eq!(issue.error_code(), Some("E013"));
assert_eq!(issue.message, "test message");
assert_eq!(issue.span, Some(Span::new(100, 118)));
assert_eq!(issue.start_offset(), Some(100));
assert_eq!(issue.segment_tag, Some("NAD".to_owned()));
assert_eq!(issue.rule_id, Some("DEMO-P001".to_owned()));
assert_eq!(issue.element_index, Some(1));
assert_eq!(issue.component_index, Some(2));
assert_eq!(issue.suggestion, Some("Check element count".to_owned()));
}
#[test]
fn report_display_format() {
let mut report = ValidationReport::default();
report.add_error(
ValidationIssue::new(ValidationSeverity::Error, "Error 1")
.with_error_code("E011")
.with_span(Span::new(8, 20)),
);
report.add_warning(ValidationIssue::new(
ValidationSeverity::Warning,
"Warning 1",
));
report.add_info(ValidationIssue::new(ValidationSeverity::Info, "Info 1"));
let display_str = format!("{report}");
assert!(display_str.contains("Errors (1)"));
assert!(display_str.contains("Warnings (1)"));
assert!(display_str.contains("Info (1)"));
assert!(display_str.contains("[E011]"));
}
#[test]
fn render_deterministic_sorts_by_span_start() {
let mut report = ValidationReport::default();
report.add_error(
ValidationIssue::new(ValidationSeverity::Error, "later")
.with_segment("BGM")
.with_span(Span::new(20, 30)),
);
report.add_error(
ValidationIssue::new(ValidationSeverity::Error, "earlier")
.with_segment("UNH")
.with_span(Span::new(1, 19)),
);
let rendered = report.render_deterministic();
let first = rendered.find("earlier").expect("missing first issue");
let second = rendered.find("later").expect("missing second issue");
assert!(first < second, "expected deterministic sort by span start");
}
#[cfg(feature = "serde")]
#[test]
fn error_code_survives_a_serde_round_trip() {
let issue = ValidationIssue::new(ValidationSeverity::Error, "BGM code invalid")
.with_error_code("E014")
.with_span(Span::new(9, 22))
.with_rule_id("PROFILE-4711-BGM-M");
let json = serde_json::to_string(&issue).expect("serialize");
let back: ValidationIssue = serde_json::from_str(&json).expect("deserialize");
assert_eq!(back.error_code(), Some("E014"));
assert_eq!(back.span, Some(Span::new(9, 22)));
assert_eq!(back, issue);
}
#[test]
fn filter_by_rule_id() {
let mut report = ValidationReport::default();
report.add_error(
ValidationIssue::new(ValidationSeverity::Error, "orders policy blocked")
.with_rule_id("ORDERS-P001"),
);
report.add_warning(
ValidationIssue::new(ValidationSeverity::Warning, "invoic policy warning")
.with_rule_id("INVOIC-P001"),
);
report.add_info(
ValidationIssue::new(ValidationSeverity::Info, "orders policy info")
.with_rule_id("ORDERS-P002"),
);
let only_orders_block = report.filter_by_rule_id("ORDERS-P001");
assert_eq!(only_orders_block.errors().len(), 1);
assert!(only_orders_block.warnings().is_empty());
assert!(only_orders_block.infos().is_empty());
let orders_family = report.filter_by_rule_prefix("ORDERS-");
assert_eq!(orders_family.total_issues(), 2);
let exact: Vec<_> = report.issues_for_rule_id("INVOIC-P001").collect();
assert_eq!(exact.len(), 1);
assert_eq!(exact[0].message, "invoic policy warning");
}
#[test]
fn context_map_builder() {
let issue = ValidationIssue::new(ValidationSeverity::Error, "BGM code invalid")
.with_context_entry("pid", "4711")
.with_context_entry("partner", "9900123456789");
assert_eq!(issue.context_get("pid"), Some("4711"));
assert_eq!(issue.context_get("partner"), Some("9900123456789"));
assert_eq!(issue.context_get("missing"), None);
}
#[test]
fn context_map_extend() {
let meta = [("pid", "4711"), ("partner", "9900123456789")];
let issue =
ValidationIssue::new(ValidationSeverity::Error, "test").with_context_entries(meta);
assert_eq!(issue.context_get("pid"), Some("4711"));
}
#[test]
fn context_key_overwrite() {
let issue = ValidationIssue::new(ValidationSeverity::Warning, "demo")
.with_context_entry("pid", "old")
.with_context_entry("pid", "new");
assert_eq!(issue.context_get("pid"), Some("new"));
}
#[test]
fn positional_builders_take_usize_and_never_clamp() {
let element: usize = 3;
let component: usize = 1;
let occurrence: usize = 69_999;
let index: usize = 70_002;
let issue = ValidationIssue::new(ValidationSeverity::Error, "x")
.with_element_index(element)
.with_component_index(component)
.with_segment_occurrence(occurrence)
.with_segment_position(index + 1);
assert_eq!(issue.element_index(), Some(3));
assert_eq!(issue.component_index(), Some(1));
assert_eq!(issue.segment_occurrence(), Some(69_999));
assert_eq!(issue.segment_position(), Some(70_003));
let issue = issue
.with_element_index(70_000)
.with_component_index(usize::from(u16::MAX) + 1);
assert_eq!(issue.element_index(), None);
assert_eq!(issue.component_index(), None);
assert_eq!(
ValidationIssue::new(ValidationSeverity::Error, "x")
.with_element_index(usize::from(u16::MAX))
.element_index(),
Some(u16::MAX),
"the largest value that fits is kept as is"
);
}
#[cfg(target_pointer_width = "64")]
#[test]
fn occurrence_and_position_beyond_u32_are_none() {
let too_big = u32::MAX as usize + 1;
let issue = ValidationIssue::new(ValidationSeverity::Error, "x")
.with_segment_occurrence(too_big)
.with_segment_position(too_big);
assert_eq!(issue.segment_occurrence(), None);
assert_eq!(issue.segment_position(), None);
assert!(GroupStep::new("SG4", too_big).is_none());
}
#[test]
fn issue_size_is_reported() {
let size = std::mem::size_of::<ValidationIssue>();
println!("size_of::<ValidationIssue>() = {size}");
#[cfg(target_pointer_width = "64")]
assert!(size <= 272, "ValidationIssue grew to {size} bytes");
}
#[test]
fn group_path_display_steps_and_root() {
let path = GroupPath::new(GroupStep::new("SG4", 0))
.and_then(|p| p.child("SG8", 1))
.expect("path");
assert_eq!(path.to_string(), "SG4[0]/SG8[1]");
assert_eq!(path.depth(), 2);
assert_eq!(path.steps()[0], GroupStep::new("SG4", 0).unwrap());
assert_eq!(&*path.last().name, "SG8");
assert_eq!(path.last().occurrence, 1);
assert!(GroupPath::new(Vec::new()).is_none());
let clone = path.clone();
assert!(std::ptr::eq(path.steps(), clone.steps()));
}
#[test]
fn with_group_path_fills_an_empty_segment_group_only() {
let path = GroupPath::new(GroupStep::new("SG8", 2)).unwrap();
let filled =
ValidationIssue::new(ValidationSeverity::Error, "x").with_group_path(path.clone());
assert_eq!(filled.segment_group(), Some("SG8"));
assert_eq!(filled.group_path(), Some(&path));
let kept = ValidationIssue::new(ValidationSeverity::Error, "x")
.with_segment_group("CUSTOM")
.with_group_path(path);
assert_eq!(kept.segment_group(), Some("CUSTOM"));
}
#[test]
fn render_deterministic_shows_the_new_tokens() {
let path = GroupPath::new(GroupStep::new("SG4", 0))
.and_then(|p| p.child("SG8", 1))
.unwrap();
let mut report = ValidationReport::default();
report.add_error(
ValidationIssue::new(ValidationSeverity::Error, "RFF missing")
.with_segment("RFF")
.with_segment_occurrence(2)
.with_segment_position(17)
.with_group_path(path)
.with_layer(ValidationLayer::Profile)
.with_kind(FindingKind::Missing)
.with_pack("AHB-UTILMD"),
);
let rendered = report.render_deterministic();
assert!(
rendered.contains(
"RFF missing [segment=RFF] [occurrence=2] [position=17] \
[path=SG4[0]/SG8[1]/RFF] [layer=profile] [kind=missing] [pack=AHB-UTILMD]"
),
"{rendered}"
);
}
#[test]
fn render_deterministic_sorts_on_new_keys_after_existing_ones() {
let mut report = ValidationReport::default();
for position in [9_usize, 3, 5] {
report.add_error(
ValidationIssue::new(ValidationSeverity::Error, "same")
.with_segment("QTY")
.with_segment_position(position),
);
}
let rendered = report.render_deterministic();
let at = |p: &str| rendered.find(p).unwrap();
assert!(at("[position=3]") < at("[position=5]"));
assert!(at("[position=5]") < at("[position=9]"));
}
fn every_error() -> Vec<(crate::EdifactError, FindingKind)> {
use crate::EdifactError as E;
use FindingKind as K;
let span = Span::new(0, 1);
let tag = || "QTY".to_owned();
vec![
(E::UnexpectedEof { offset: 0 }, K::Syntax),
(
E::InvalidDelimiter {
byte: b'x',
offset: 0,
},
K::Syntax,
),
(E::InvalidText { offset: 0 }, K::Charset),
(E::InvalidReleaseSequence { offset: 0 }, K::Syntax),
(
E::MessageCountMismatch {
expected: 1,
actual: 2,
span: crate::Span::new(0, 9),
},
K::ControlMismatch,
),
(
E::SegmentCountMismatch {
expected: 1,
actual: 2,
message_ref: "1".into(),
span,
},
K::ControlMismatch,
),
(E::InvalidSegmentTag("x".into()), K::Syntax),
(E::InvalidUna, K::Syntax),
(
E::MissingRequiredElement {
tag: tag(),
element_index: 1,
},
K::Missing,
),
(
E::MissingRequiredComponent {
tag: tag(),
element_index: 1,
component_index: 0,
},
K::Missing,
),
(E::InvalidUtf8, K::Charset),
(E::Io(std::io::Error::other("x").into()), K::Other),
(
E::InvalidSegmentForMessage {
tag: tag(),
message_type: "ORDERS".into(),
span,
},
K::Placement,
),
(
E::InvalidElementCount {
tag: tag(),
min: 1,
max: 2,
actual: 3,
span,
},
K::Count,
),
(
E::InvalidComponentCount {
tag: tag(),
element_index: 0,
expected: 2,
actual: 3,
span,
},
K::Count,
),
(
E::InvalidCodeValue {
tag: tag(),
element_index: 0,
value: "999".into(),
code_list: "6063".into(),
span,
suggestion: None,
},
K::Code,
),
(
E::MissingSegment {
tag: tag(),
expected_position: "after LIN".into(),
},
K::Missing,
),
(
E::QualifierMismatch {
tag: "UNT".into(),
actual: "2".into(),
expected: "1".into(),
span,
},
K::ControlMismatch,
),
(
E::ConditionalRequirementNotMet {
tag: tag(),
element_index: 0,
condition: "x".into(),
span,
},
K::Missing,
),
(
E::ValidationErrors {
error_count: 0,
report: Box::default(),
},
K::Other,
),
(
E::SegmentTooLong {
offset: 0,
limit: 1,
},
K::Limit,
),
(E::InterchangeTooLarge { count: 1 }, K::Limit),
(E::InvalidEventSequence { message: "x" }, K::Other),
(E::InvalidElementPosition, K::Other),
(
E::IncompatibleReleaseScopes {
current: "a".into(),
incoming: "b".into(),
},
K::Other,
),
(
E::InvalidFieldValue {
tag: tag(),
element_index: 0,
value: "x".into(),
},
K::Representation,
),
(E::UnexpectedDataToken { offset: 0 }, K::Syntax),
(E::UnrecognisedSyntaxIdentifier("UNOZ".into()), K::Charset),
(
E::DuplicateReference {
tag: "UNH".into(),
reference: "1".into(),
span,
},
K::Duplicate,
),
(
E::UnknownDataElement {
tag: tag(),
data_element: "9999".into(),
},
K::Other,
),
(
E::AmbiguousDataElement {
tag: tag(),
data_element: "6063".into(),
},
K::Other,
),
(
E::LimitExceeded {
limit: "x",
max: 1,
offset: 0,
},
K::Limit,
),
(E::RepetitionSeparatorNotDeclared, K::Syntax),
(
E::NonFiniteNumber {
value: "NaN".into(),
},
K::Representation,
),
(
E::CharacterNotInRepertoire {
charset: "UNOA",
character: 'a',
offset: 0,
},
K::Charset,
),
(
E::CharacterRepertoireMismatch {
declared: "UNOA".into(),
writer: "UNOC",
},
K::Charset,
),
(
E::UnsupportedCharset {
syntax_identifier: "KECA".into(),
},
K::Charset,
),
(
E::EmptyInterchange {
control_ref: "1".into(),
},
K::Envelope,
),
(
E::EmptyMessage {
message_ref: "1".into(),
span,
},
K::Envelope,
),
(
E::PackageNotSupported {
tag: "UNO".into(),
span,
},
K::Unsupported,
),
(
E::BlankDataElementValue {
tag: tag(),
element_index: 0,
component_index: 0,
span,
},
K::Representation,
),
(
E::SegmentWithoutDataElements { tag: tag(), span },
K::Syntax,
),
(
E::TooManyRepetitions {
tag: tag(),
element_index: 0,
max: 1,
actual: 2,
span,
},
K::Count,
),
(
E::InvalidCharacterType {
tag: tag(),
element_index: 0,
component_index: 0,
repr: "n..3".into(),
value: "x".into(),
span,
},
K::Representation,
),
(
E::DataElementTooLong {
tag: tag(),
element_index: 0,
component_index: 0,
repr: "an..3".into(),
actual: 4,
span,
},
K::Representation,
),
(
E::DataElementTooShort {
tag: tag(),
element_index: 0,
component_index: 0,
repr: "an3".into(),
actual: 2,
span,
},
K::Representation,
),
(
E::TrailingSeparator {
tag: tag(),
element_index: None,
span,
},
K::Syntax,
),
(E::GroupsAndMessagesMixed { span }, K::Envelope),
(
E::InsignificantCharacters {
tag: tag(),
element_index: 0,
component_index: 0,
kind: crate::Insignificant::LeadingZeroes,
span,
},
K::Representation,
),
(
E::SegmentLayoutMismatch {
expected: "a".into(),
actual: "b".into(),
},
K::Other,
),
(
E::ActionNotPermitted {
segment_tag: "UCI",
action: "8",
},
K::Other,
),
(
E::InvalidContrlIdentifier {
data_element: "0057",
value: "TOOLONG".into(),
},
K::Other,
),
(
E::SegmentNotPlaced {
tag: tag(),
reason: crate::group::UnplacedReason::Unknown,
span,
},
K::Placement,
),
(
E::TooManySegmentOccurrences {
tag: tag(),
max: 1,
span,
},
K::Count,
),
(
E::TooManyGroupOccurrences {
group: "SG5".into(),
max: 1,
span,
},
K::Count,
),
(
E::InvalidGroupSchema {
group: "SG5".into(),
reason: "max is 0",
},
K::Other,
),
(
E::WriterPoisoned {
reason: "an earlier write to the sink failed",
},
K::Other,
),
]
}
#[test]
fn finding_kind_for_every_error() {
let all = every_error();
let mut codes: Vec<&str> = all.iter().map(|(e, _)| e.stable_code()).collect();
codes.sort_unstable();
codes.dedup();
assert_eq!(codes.len(), 57, "every EdifactError variant must be listed");
assert_eq!(all.len(), 57);
for (error, kind) in &all {
assert_eq!(
FindingKind::for_error(error),
*kind,
"{} ({error:?})",
error.stable_code()
);
}
}
#[test]
fn finding_kind_and_layer_strings_are_stable() {
let kinds = [
(FindingKind::Missing, "missing"),
(FindingKind::NotPermitted, "not_permitted"),
(FindingKind::Code, "code"),
(FindingKind::Representation, "representation"),
(FindingKind::Count, "count"),
(FindingKind::Placement, "placement"),
(FindingKind::ControlMismatch, "control_mismatch"),
(FindingKind::Duplicate, "duplicate"),
(FindingKind::Envelope, "envelope"),
(FindingKind::Charset, "charset"),
(FindingKind::Syntax, "syntax"),
(FindingKind::Limit, "limit"),
(FindingKind::Unsupported, "unsupported"),
(FindingKind::Other, "other"),
];
for (kind, text) in kinds {
assert_eq!(kind.as_str(), text);
assert_eq!(kind.to_string(), text);
}
let layers = [
(ValidationLayer::Envelope, "envelope"),
(ValidationLayer::Syntax, "syntax"),
(ValidationLayer::Charset, "charset"),
(ValidationLayer::Structure, "structure"),
(ValidationLayer::CodeList, "code_list"),
(ValidationLayer::Profile, "profile"),
];
for (layer, text) in layers {
assert_eq!(layer.as_str(), text);
}
}
#[cfg(feature = "serde")]
fn full_issue() -> ValidationIssue {
ValidationIssue::new(ValidationSeverity::Warning, "every field")
.with_error_code("E014")
.with_span(Span::new(3, 9))
.with_segment("RFF")
.with_rule_id("AHB-RFF-CODE")
.with_element_index(1)
.with_component_index(2)
.with_segment_occurrence(70_000)
.with_segment_position(70_004)
.with_message_ref("MSG1")
.with_suggestion("fix it")
.with_group_path(
GroupPath::new(GroupStep::new("SG4", 0))
.and_then(|p| p.child("SG8", 1))
.unwrap(),
)
.with_layer(ValidationLayer::CodeList)
.with_kind(FindingKind::Code)
.with_pack("AHB-UTILMD")
.with_context_entry("pid", "55001")
}
#[cfg(feature = "serde")]
#[test]
fn serde_round_trips_every_field() {
let issue = full_issue();
let json = serde_json::to_string(&issue).expect("serialize");
let back: ValidationIssue = serde_json::from_str(&json).expect("deserialize");
assert_eq!(back, issue);
let value: serde_json::Value = serde_json::from_str(&json).unwrap();
assert_eq!(value["layer"], "CodeList");
assert_eq!(value["kind"], "Code");
assert_eq!(value["pack"], "AHB-UTILMD");
assert_eq!(value["segment_position"], 70_004);
assert_eq!(
value["group_path"],
serde_json::json!([
{"group": "SG4", "occurrence": 0},
{"group": "SG8", "occurrence": 1}
])
);
}
#[cfg(feature = "serde")]
#[test]
fn serde_omits_unset_new_fields() {
let json = serde_json::to_string(&ValidationIssue::new(ValidationSeverity::Info, "x"))
.expect("serialize");
for field in ["segment_position", "group_path", "layer", "kind", "pack"] {
assert!(!json.contains(field), "{field} in {json}");
}
}
#[cfg(feature = "serde")]
#[test]
fn serde_unknown_kind_reads_as_other() {
let json = r#"{"severity":"Error","message":"x","span":null,"segment_tag":null,
"rule_id":null,"element_index":null,"component_index":null,
"segment_occurrence":null,"message_ref":null,"suggestion":null,
"segment_group":null,"kind":"SomethingNewer"}"#;
let issue: ValidationIssue = serde_json::from_str(json).expect("deserialize");
assert_eq!(issue.kind(), Some(FindingKind::Other));
}
#[cfg(feature = "serde")]
#[test]
fn serde_refuses_an_empty_group_path() {
let json = r#"{"severity":"Error","message":"x","span":null,"segment_tag":null,
"rule_id":null,"element_index":null,"component_index":null,
"segment_occurrence":null,"message_ref":null,"suggestion":null,
"segment_group":null,"group_path":[]}"#;
assert!(serde_json::from_str::<ValidationIssue>(json).is_err());
}
}