pub mod rules;
pub mod state;
mod messages;
use alloc::format;
use alloc::string::{String, ToString};
use alloc::vec::Vec;
use crate::message::MessageKind;
use crate::schema;
use crate::types::common::{
CommodityQuantity, ControlType, EnergyManagementRole, InstructionStatus, NumberRange,
ReceptionStatusValues, ResourceManagerDetails, RevokableObjects,
};
use crate::types::{Duration, Id, Timestamp, WireProfile, ddbc, frbc, ombc, pebc, ppbc};
pub use rules::Rule;
pub use state::{Allowance, Phase, allowed};
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct RuleId(pub &'static str);
impl RuleId {
#[must_use]
pub const fn as_str(self) -> &'static str {
self.0
}
#[must_use]
pub fn rule(self) -> Option<&'static Rule> {
Rule::find(self)
}
}
impl core::fmt::Display for RuleId {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.write_str(self.0)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Severity {
Error,
Warning,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Violation {
pub rule: RuleId,
pub severity: Severity,
pub path: String,
pub message: String,
pub related: Vec<Id>,
}
impl core::fmt::Display for Violation {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
if self.path.is_empty() {
write!(f, "{}: {}", self.rule, self.message)
} else {
write!(f, "{} at {}: {}", self.rule, self.path, self.message)
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct Report {
violations: Vec<Violation>,
}
impl Report {
#[must_use]
pub const fn new() -> Self {
Self {
violations: Vec::new(),
}
}
pub fn push(&mut self, rule: RuleId, path: &str, message: impl Into<String>) {
let severity = rule.rule().map_or(Severity::Error, |r| r.severity);
self.violations.push(Violation {
rule,
severity,
path: path.to_string(),
message: message.into(),
related: Vec::new(),
});
}
pub fn push_related(
&mut self,
rule: RuleId,
path: &str,
message: impl Into<String>,
related: impl IntoIterator<Item = Id>,
) {
self.push(rule, path, message);
if let Some(last) = self.violations.last_mut() {
last.related = related.into_iter().collect();
}
}
#[must_use]
pub fn violations(&self) -> &[Violation] {
&self.violations
}
pub fn errors(&self) -> impl Iterator<Item = &Violation> {
self.violations
.iter()
.filter(|v| v.severity == Severity::Error)
}
pub fn warnings(&self) -> impl Iterator<Item = &Violation> {
self.violations
.iter()
.filter(|v| v.severity == Severity::Warning)
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.violations.is_empty()
}
#[must_use]
pub fn has_errors(&self) -> bool {
self.errors().next().is_some()
}
#[must_use]
pub fn first_error(&self) -> Option<&Violation> {
self.errors().next()
}
#[must_use]
pub fn contains(&self, rule: RuleId) -> bool {
self.violations.iter().any(|v| v.rule == rule)
}
pub fn fired(&self) -> impl Iterator<Item = RuleId> + '_ {
self.violations.iter().map(|v| v.rule)
}
#[must_use]
pub fn reception_status(&self) -> ReceptionStatusValues {
if self.has_errors() {
ReceptionStatusValues::InvalidContent
} else {
ReceptionStatusValues::Ok
}
}
#[must_use]
pub fn diagnostic_label(&self) -> Option<String> {
self.first_error().map(ToString::to_string)
}
pub fn extend(&mut self, other: Report) {
self.violations.extend(other.violations);
}
}
impl core::fmt::Display for Report {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
for (i, v) in self.violations.iter().enumerate() {
if i > 0 {
writeln!(f)?;
}
write!(f, "{v}")?;
}
Ok(())
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct TimerState {
pub actuator: Id,
pub timer: Id,
pub finished_at: Timestamp,
}
#[derive(Debug, Clone, Copy, Default)]
pub struct Context<'a> {
pub profile: WireProfile,
pub sender: Option<EnergyManagementRole>,
pub phase: Phase,
pub s2_connect: bool,
pub details: Option<&'a ResourceManagerDetails>,
pub frbc: Option<&'a frbc::SystemDescription>,
pub ombc: Option<&'a ombc::SystemDescription>,
pub ddbc: Option<&'a ddbc::SystemDescription>,
pub pebc_constraints: &'a [pebc::PowerConstraints],
pub ppbc_profiles: &'a [ppbc::PowerProfileDefinition],
pub instructions: &'a [Id],
pub instruction_messages: &'a [(Id, Id)],
pub instruction_statuses: &'a [(Id, InstructionStatus)],
pub seen_message_ids: &'a [Id],
pub published: &'a [(RevokableObjects, Id)],
pub active_modes: &'a [(Id, Id)],
pub timers: &'a [TimerState],
pub fill_level: Option<f64>,
pub now: Option<Timestamp>,
pub skew_tolerance: Duration,
}
impl<'a> Context<'a> {
#[must_use]
pub fn empty() -> Self {
Self {
skew_tolerance: Duration::from_secs(30),
..Self::default()
}
}
#[must_use]
pub fn with_details(mut self, details: &'a ResourceManagerDetails) -> Self {
self.details = Some(details);
self
}
#[must_use]
pub fn at(mut self, now: Timestamp) -> Self {
self.now = Some(now);
self
}
#[must_use]
pub fn sent_by(mut self, sender: EnergyManagementRole) -> Self {
self.sender = Some(sender);
self
}
#[must_use]
pub fn active(mut self, control_type: ControlType) -> Self {
self.phase = Phase::selected(control_type);
self
}
#[must_use]
pub const fn in_phase(mut self, phase: Phase) -> Self {
self.phase = phase;
self
}
#[must_use]
pub const fn active_control_type(&self) -> Option<ControlType> {
self.phase.active_control_type()
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.sender.is_none() && self.details.is_none() && self.phase == Phase::Connected
}
fn timer_finished_at(&self, actuator: &Id, timer: &Id) -> Option<Timestamp> {
self.timers
.iter()
.find(|t| t.actuator == *actuator && t.timer == *timer)
.map(|t| t.finished_at)
}
fn active_mode_of(&self, actuator: &Id) -> Option<Id> {
self.active_modes
.iter()
.find(|(a, _)| a == actuator)
.map(|(_, m)| *m)
}
}
pub trait Validate {
fn validate_at(&self, path: &str, ctx: &Context<'_>, out: &mut Report);
fn validate(&self, ctx: &Context<'_>) -> Report {
let mut report = Report::new();
self.validate_at("", ctx, &mut report);
report
}
}
#[must_use]
#[allow(clippy::format_push_string)] pub fn rules_markdown() -> String {
let mut out = String::from(
"# Rule catalogue\n\n\
Generated from `s2_kit::validate::rules::RULES` — do not edit.\n\n\
Every rule quotes the sentence it implements. An **error** is a requirement the\n\
standard states plainly; a **warning** is one it leaves ambiguous, silent or\n\
self-contradictory, and never refuses traffic. The identifier travels in the\n\
`diagnostic_label` of every failing `ReceptionStatus` this crate sends.\n\n",
);
let errors = rules::RULES
.iter()
.filter(|r| r.severity == Severity::Error)
.count();
out.push_str(&format!(
"{} rules: {} errors, {} warnings.\n\n",
rules::RULES.len(),
errors,
rules::RULES.len() - errors
));
out.push_str("| Rule | Severity | Needs session | Checks | Source |\n|---|---|---|---|---|\n");
for rule in rules::RULES {
out.push_str(&format!(
"| `{}` | {} | {} | {} | {} |\n",
rule.id,
match rule.severity {
Severity::Error => "error",
Severity::Warning => "warning",
},
if rule.needs_context { "yes" } else { "no" },
rule.summary,
rule.source.replace('|', "\\|")
));
}
out
}
pub(crate) fn child(path: &str, name: &str) -> String {
format!("{path}/{name}")
}
pub(crate) fn index(path: &str, i: usize) -> String {
format!("{path}/{i}")
}
pub(crate) fn check_finite(value: f64, path: &str, out: &mut Report) {
if !value.is_finite() {
out.push(
rules::NON_FINITE,
path,
format!("{value} cannot be represented in JSON"),
);
}
}
pub(crate) fn check_interpolated(range: NumberRange, path: &str, out: &mut Report) {
check_finite(range.start_of_range, &child(path, "start_of_range"), out);
check_finite(range.end_of_range, &child(path, "end_of_range"), out);
}
pub(crate) fn check_range(range: NumberRange, path: &str, out: &mut Report) {
check_finite(range.start_of_range, &child(path, "start_of_range"), out);
check_finite(range.end_of_range, &child(path, "end_of_range"), out);
if range.is_finite() && range.start_of_range > range.end_of_range {
out.push(
rules::RANGE_ORDER,
path,
format!(
"start_of_range {} is after end_of_range {}",
range.start_of_range, range.end_of_range
),
);
}
}
pub(crate) fn check_band(range: NumberRange, path: &str, out: &mut Report) {
check_finite(range.start_of_range, &child(path, "start_of_range"), out);
check_finite(range.end_of_range, &child(path, "end_of_range"), out);
if range.is_finite() && range.start_of_range >= range.end_of_range {
out.push(
rules::RANGE_STRICT_ORDER,
path,
format!(
"fill level band {}..{} is empty; the start must be below the end",
range.start_of_range, range.end_of_range
),
);
}
}
pub(crate) fn check_factor(factor: f64, path: &str, out: &mut Report) {
check_finite(factor, path, out);
if factor.is_finite() && !(0.0..=1.0).contains(&factor) {
out.push(
rules::FACTOR_RANGE,
path,
format!("operation mode factor {factor} is outside [0, 1]"),
);
}
}
pub(crate) fn check_array(
type_name: &str,
property: &str,
len: usize,
path: &str,
out: &mut Report,
) {
let Some(bounds) = schema::type_spec(type_name)
.and_then(|t| t.property(property))
.and_then(|p| p.kind.bounds())
else {
return;
};
if !bounds.accepts(len as u64) {
out.push(
rules::ARRAY_BOUNDS,
&child(path, property),
format!(
"{len} items, but the schema allows {}..={}",
bounds.min.unwrap_or(0),
bounds
.max
.map_or_else(|| "unbounded".to_string(), |m| m.to_string())
),
);
}
}
pub(crate) fn check_unique_quantities<I>(quantities: I, path: &str, out: &mut Report)
where
I: IntoIterator<Item = CommodityQuantity>,
{
let mut seen: Vec<CommodityQuantity> = Vec::new();
let mut per_phase = false;
let mut symmetric = false;
for q in quantities {
if seen.contains(&q) {
out.push(
rules::ONE_VALUE_PER_QUANTITY,
path,
format!("{} appears more than once", q.as_str()),
);
} else {
seen.push(q);
}
per_phase |= q.is_per_phase_electric();
symmetric |= q == CommodityQuantity::ElectricPower3PhaseSymmetric;
}
if per_phase && symmetric {
out.push(
rules::PHASE_EXCLUSIVITY,
path,
"per-phase and three-phase-symmetric electric power are both present; \
a CEM cannot tell whether to add them or choose between them",
);
}
}
pub(crate) fn check_unique_ids<'i, I>(ids: I, scope: &str, path: &str, out: &mut Report)
where
I: IntoIterator<Item = &'i Id>,
{
let mut seen: Vec<&Id> = Vec::new();
for id in ids {
if seen.contains(&id) {
out.push_related(
rules::DUPLICATE_ID,
path,
format!("{id} appears more than once within {scope}"),
[*id],
);
} else {
seen.push(id);
}
}
}
pub(crate) fn check_contiguous(
ranges: &[NumberRange],
rule: RuleId,
what: &str,
path: &str,
out: &mut Report,
) {
for (i, pair) in ranges.windows(2).enumerate() {
let [a, b] = pair else { continue };
if !a.is_finite() || !b.is_finite() {
continue;
}
let tolerance =
4.0 * f64::EPSILON * a.end_of_range.abs().max(b.start_of_range.abs()).max(1.0);
if (a.end_of_range - b.start_of_range).abs() > tolerance {
out.push(
rule,
&index(path, i + 1),
format!(
"{what} are not contiguous: the previous band ends at {} and this one starts at {}",
a.end_of_range, b.start_of_range
),
);
}
}
}
pub(crate) fn check_percentiles(
bands: &[(&'static str, Option<f64>); 7],
path: &str,
out: &mut Report,
) {
let mut previous: Option<(&str, f64)> = None;
for (name, value) in bands {
let Some(value) = *value else { continue };
check_finite(value, &child(path, name), out);
if let Some((previous_name, previous_value)) = previous
&& value.is_finite()
&& previous_value.is_finite()
&& value < previous_value
{
out.push(
rules::PERCENTILE_ORDER,
&child(path, name),
format!("{name} ({value}) is below {previous_name} ({previous_value})"),
);
}
if value.is_finite() {
previous = Some((name, value));
}
}
}
pub(crate) const SCHEDULING_HORIZON: Duration = Duration::from_secs(365 * 86_400);
pub(crate) fn check_observed(at: Timestamp, path: &str, ctx: &Context<'_>, out: &mut Report) {
let Some(now) = ctx.now else { return };
let ahead = at.saturating_duration_since(now);
if ahead > ctx.skew_tolerance {
out.push(
rules::TIMESTAMP_SKEW,
path,
format!(
"{at} says something has already happened, but it is {} ms ahead of \
the local clock ({now}), which tolerates {} ms of skew",
ahead.as_millis(),
ctx.skew_tolerance.as_millis()
),
);
}
}
pub(crate) fn check_scheduled(at: Timestamp, path: &str, ctx: &Context<'_>, out: &mut Report) {
let Some(now) = ctx.now else { return };
let ahead = at.saturating_duration_since(now);
if ahead > SCHEDULING_HORIZON {
out.push(
rules::TIMESTAMP_SKEW,
path,
format!("{at} is more than a year ahead of the local clock ({now})"),
);
}
}
pub(crate) fn check_transitions(
transitions: &[crate::types::common::Transition],
mode_ids: &[Id],
timer_ids: &[Id],
rule: RuleId,
path: &str,
out: &mut Report,
) {
for (i, transition) in transitions.iter().enumerate() {
let at = index(path, i);
for (field, id) in [("from", &transition.from), ("to", &transition.to)] {
if !mode_ids.contains(id) {
out.push_related(
rule,
&child(&at, field),
format!("{id} is not an operation mode of this description"),
[*id],
);
}
}
for (field, ids) in [
("start_timers", &transition.start_timers),
("blocking_timers", &transition.blocking_timers),
] {
for id in ids {
if !timer_ids.contains(id) {
out.push_related(
rule,
&child(&at, field),
format!("{id} is not a timer of this description"),
[*id],
);
}
}
}
if let Some(cost) = transition.transition_costs {
check_finite(cost, &child(&at, "transition_costs"), out);
}
}
}
pub(crate) struct ModeCheck<'a> {
pub actuator: Option<&'a Id>,
pub mode: &'a Id,
pub abnormal_condition: bool,
pub abnormal_only: bool,
pub transitions: &'a [crate::types::common::Transition],
pub timers: &'a [crate::types::common::Timer],
}
pub(crate) fn check_instruction_context(
check: &ModeCheck<'_>,
path: &str,
ctx: &Context<'_>,
out: &mut Report,
) {
if check.abnormal_only && !check.abnormal_condition {
out.push_related(
rules::ABNORMAL_ONLY,
path,
format!(
"{} may only be used during an abnormal condition, \
and abnormal_condition is false",
check.mode
),
[*check.mode],
);
}
let actuator = check.actuator.copied().unwrap_or(Id::NIL);
let Some(active) = ctx.active_mode_of(&actuator) else {
return;
};
if active == *check.mode {
return;
}
let Some(transition) = check
.transitions
.iter()
.find(|t| t.from == active && t.to == *check.mode)
else {
out.push_related(
rules::NO_SUCH_TRANSITION,
path,
format!("no transition is described from {active} to {}", check.mode),
[active, *check.mode],
);
return;
};
if transition.abnormal_condition_only && !check.abnormal_condition {
out.push_related(
rules::ABNORMAL_ONLY,
path,
format!(
"transition {} may only be used during an abnormal condition",
transition.id
),
[transition.id],
);
}
if let Some(now) = ctx.now {
for timer_id in &transition.blocking_timers {
if let Some(finished_at) = ctx.timer_finished_at(&actuator, timer_id)
&& finished_at > now
{
let label = check
.timers
.iter()
.find(|t| t.id == *timer_id)
.and_then(|t| t.diagnostic_label.as_deref())
.unwrap_or("timer");
out.push_related(
rules::BLOCKED_BY_TIMER,
path,
format!("{label} {timer_id} does not finish until {finished_at}"),
[*timer_id],
);
}
}
}
}
pub(crate) fn check_envelope(
kind: MessageKind,
message_id: Option<Id>,
ctx: &Context<'_>,
out: &mut Report,
) {
if let Some(sender) = ctx.sender {
match state::allowed(ctx.phase, sender, kind) {
Allowance::Yes => {}
Allowance::WrongState => out.push(
rules::NOT_ALLOWED_IN_STATE,
"",
format!(
"{kind} is not allowed while the session is {}",
ctx.phase.label()
),
),
Allowance::WrongRole => out.push(
rules::NOT_ALLOWED_FOR_ROLE,
"",
format!("{kind} is not sent by a {sender:?}"),
),
}
}
if ctx.s2_connect
&& matches!(
kind,
MessageKind::Handshake | MessageKind::HandshakeResponse
)
{
out.push(
rules::HANDSHAKE_UNDER_CONNECT,
"",
"under S2 Connect the version is negotiated during session initiation, \
and handshake messages are redundant",
);
}
if let Some(id) = message_id
&& ctx.seen_message_ids.contains(&id)
{
out.push_related(
rules::DUPLICATE_MESSAGE_ID,
"/message_id",
format!("{id} has already been used on this session"),
[id],
);
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_report_is_ok_until_an_error_is_recorded() {
let mut report = Report::new();
assert!(report.is_empty());
assert_eq!(report.reception_status(), ReceptionStatusValues::Ok);
report.push(rules::PHASE_EXCLUSIVITY, "/values", "mixed phases");
assert!(!report.is_empty());
assert!(!report.has_errors(), "a warning does not refuse a message");
assert_eq!(report.reception_status(), ReceptionStatusValues::Ok);
assert_eq!(report.diagnostic_label(), None);
report.push(rules::FACTOR_RANGE, "/operation_mode_factor", "1.3");
assert!(report.has_errors());
assert_eq!(
report.reception_status(),
ReceptionStatusValues::InvalidContent
);
assert_eq!(
report.diagnostic_label().unwrap(),
"S2-NUM-004 at /operation_mode_factor: 1.3"
);
}
#[test]
fn severity_comes_from_the_catalogue_not_the_call_site() {
let mut report = Report::new();
report.push(rules::PERCENTILE_ORDER, "", "x");
report.push(rules::NON_FINITE, "", "y");
assert_eq!(report.violations()[0].severity, Severity::Warning);
assert_eq!(report.violations()[1].severity, Severity::Error);
}
#[test]
fn contiguity_tolerates_arithmetic_but_not_a_gap() {
let third = 100.0 / 3.0;
let computed = 100.0 - (100.0 / 3.0) - (100.0 / 3.0);
let mut out = Report::new();
check_contiguous(
&[
NumberRange::new(0.0, third),
NumberRange::new(100.0 - third - computed, 100.0),
],
rules::FRBC_ELEMENTS_CONTIGUOUS,
"bands",
"/elements",
&mut out,
);
assert!(out.is_empty(), "{out}");
let mut out = Report::new();
check_contiguous(
&[NumberRange::new(0.0, 50.0), NumberRange::new(50.001, 100.0)],
rules::FRBC_ELEMENTS_CONTIGUOUS,
"bands",
"/elements",
&mut out,
);
assert!(out.contains(rules::FRBC_ELEMENTS_CONTIGUOUS));
}
#[test]
fn contiguity_accepts_touching_bands_and_rejects_gaps_and_overlaps() {
let mut out = Report::new();
check_contiguous(
&[NumberRange::new(0.0, 50.0), NumberRange::new(50.0, 100.0)],
rules::FRBC_ELEMENTS_CONTIGUOUS,
"bands",
"/elements",
&mut out,
);
assert!(out.is_empty(), "{out}");
let mut out = Report::new();
check_contiguous(
&[NumberRange::new(0.0, 40.0), NumberRange::new(50.0, 100.0)],
rules::FRBC_ELEMENTS_CONTIGUOUS,
"bands",
"/elements",
&mut out,
);
assert!(out.contains(rules::FRBC_ELEMENTS_CONTIGUOUS));
assert_eq!(out.violations()[0].path, "/elements/1");
let mut out = Report::new();
check_contiguous(
&[NumberRange::new(0.0, 60.0), NumberRange::new(50.0, 100.0)],
rules::FRBC_ELEMENTS_CONTIGUOUS,
"bands",
"/elements",
&mut out,
);
assert!(out.contains(rules::FRBC_ELEMENTS_CONTIGUOUS));
}
#[test]
fn array_bounds_come_from_the_generated_table() {
let mut out = Report::new();
check_array("PowerForecast", "elements", 0, "", &mut out);
assert!(out.contains(rules::ARRAY_BOUNDS));
assert!(out.violations()[0].message.contains("1..=288"));
let mut out = Report::new();
check_array("PowerForecast", "elements", 288, "", &mut out);
assert!(out.is_empty());
let mut out = Report::new();
check_array("PowerForecast", "elements", 289, "", &mut out);
assert!(out.contains(rules::ARRAY_BOUNDS));
}
#[test]
fn percentiles_must_ascend() {
let mut out = Report::new();
check_percentiles(
&[
("lower_limit", Some(0.0)),
("lower_95", Some(1.0)),
("lower_68", None),
("expected", Some(2.0)),
("upper_68", None),
("upper_95", Some(3.0)),
("upper_limit", Some(4.0)),
],
"/v",
&mut out,
);
assert!(out.is_empty(), "{out}");
let mut out = Report::new();
check_percentiles(
&[
("lower_limit", Some(0.0)),
("lower_95", None),
("lower_68", None),
("expected", Some(2.0)),
("upper_68", Some(1.0)),
("upper_95", None),
("upper_limit", None),
],
"/v",
&mut out,
);
assert!(out.contains(rules::PERCENTILE_ORDER));
assert_eq!(out.violations()[0].path, "/v/upper_68");
}
#[test]
fn skew_is_about_the_past_and_the_horizon_is_about_the_future() {
use crate::types::common::{PowerMeasurement, PowerValue};
use alloc::vec;
let now: Timestamp = "2024-01-01T12:00:00Z".parse().expect("a timestamp");
let ctx = Context {
now: Some(now),
skew_tolerance: Duration::from_secs(30),
..Context::empty()
};
let measured_at = |at: &str| PowerMeasurement {
message_id: Id::new_const("m1"),
measurement_timestamp: at.parse().expect("a timestamp"),
values: vec![PowerValue::new(CommodityQuantity::ElectricPowerL1, 1.0)],
};
assert!(
measured_at("2024-01-01T12:00:29Z")
.validate(&ctx)
.is_empty()
);
assert!(
measured_at("2024-01-01T12:01:00Z")
.validate(&ctx)
.contains(rules::TIMESTAMP_SKEW)
);
assert!(
measured_at("2020-01-01T00:00:00Z")
.validate(&ctx)
.is_empty()
);
let patient = Context {
skew_tolerance: Duration::from_secs(3600),
..ctx
};
assert!(
measured_at("2024-01-01T12:01:00Z")
.validate(&patient)
.is_empty()
);
let mut out = Report::new();
check_scheduled(
"2024-06-01T00:00:00Z".parse().expect("a timestamp"),
"/valid_from",
&ctx,
&mut out,
);
assert!(out.is_empty(), "five months ahead is a plan, not a fault");
let mut out = Report::new();
check_scheduled(
"2030-01-01T00:00:00Z".parse().expect("a timestamp"),
"/valid_from",
&ctx,
&mut out,
);
assert!(out.contains(rules::TIMESTAMP_SKEW));
}
#[test]
fn mixing_phase_conventions_is_reported_once() {
let mut out = Report::new();
check_unique_quantities(
[
CommodityQuantity::ElectricPowerL1,
CommodityQuantity::ElectricPower3PhaseSymmetric,
],
"/values",
&mut out,
);
assert!(out.contains(rules::PHASE_EXCLUSIVITY));
assert!(!out.has_errors(), "E12 is undocumented, so it is a warning");
}
#[test]
fn a_repeated_quantity_is_an_error() {
let mut out = Report::new();
check_unique_quantities(
[
CommodityQuantity::ElectricPowerL1,
CommodityQuantity::ElectricPowerL1,
],
"/values",
&mut out,
);
assert!(out.contains(rules::ONE_VALUE_PER_QUANTITY));
assert!(out.has_errors());
}
}