use std::fmt;
use crate::client::{BusinessLogic, Client, ClientError, VirtualEndNode};
mod report;
mod suite;
pub use report::RunMeta;
pub use suite::checks;
pub const RUN_PREFIX: &str = "oadr-conformance-";
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum Severity {
Required,
Recommended,
Extension,
}
impl fmt::Display for Severity {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(match self {
Severity::Required => "required",
Severity::Recommended => "recommended",
Severity::Extension => "extension",
})
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Needs {
BusinessLogic,
BothRoles,
Nothing,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Check {
pub id: &'static str,
pub clause: &'static str,
pub title: &'static str,
pub severity: Severity,
pub needs: Needs,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Outcome {
Passed,
Failed(String),
Skipped(String),
}
impl Outcome {
pub fn is_passed(&self) -> bool {
matches!(self, Outcome::Passed)
}
pub fn is_failed(&self) -> bool {
matches!(self, Outcome::Failed(_))
}
pub fn is_skipped(&self) -> bool {
matches!(self, Outcome::Skipped(_))
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Finding {
pub check: Check,
pub outcome: Outcome,
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Report {
pub target: String,
pub findings: Vec<Finding>,
}
impl Report {
pub fn tally(&self, severity: Severity) -> (usize, usize, usize) {
let mut counts = (0, 0, 0);
for finding in self
.findings
.iter()
.filter(|f| f.check.severity == severity)
{
match finding.outcome {
Outcome::Passed => counts.0 += 1,
Outcome::Failed(_) => counts.1 += 1,
Outcome::Skipped(_) => counts.2 += 1,
}
}
counts
}
pub fn failures(&self) -> impl Iterator<Item = &Finding> {
self.findings.iter().filter(|f| f.outcome.is_failed())
}
pub fn to_json(&self) -> serde_json::Value {
serde_json::json!({
"target": self.target,
"conformant": self.is_conformant(),
"findings": self.findings.iter().map(|f| serde_json::json!({
"id": f.check.id,
"clause": f.check.clause,
"title": f.check.title,
"severity": f.check.severity.to_string(),
"outcome": match &f.outcome {
Outcome::Passed => "passed",
Outcome::Failed(_) => "failed",
Outcome::Skipped(_) => "skipped",
},
"detail": match &f.outcome {
Outcome::Passed => None,
Outcome::Failed(m) | Outcome::Skipped(m) => Some(m.clone()),
},
})).collect::<Vec<_>>(),
})
}
}
impl fmt::Display for Report {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
writeln!(f, "openadr conformance — {}", self.target)?;
writeln!(f)?;
for finding in &self.findings {
let mark = match finding.outcome {
Outcome::Passed => "pass",
Outcome::Failed(_) => "FAIL",
Outcome::Skipped(_) => "skip",
};
writeln!(
f,
"{mark} {:<38} {} {}",
finding.check.id, finding.check.clause, finding.check.title
)?;
match &finding.outcome {
Outcome::Failed(message) => writeln!(f, " → {message}")?,
Outcome::Skipped(message) => writeln!(f, " ~ {message}")?,
Outcome::Passed => {}
}
}
writeln!(f)?;
for severity in [
Severity::Required,
Severity::Recommended,
Severity::Extension,
] {
let (passed, failed, skipped) = self.tally(severity);
if passed + failed + skipped == 0 {
continue;
}
writeln!(
f,
"{severity:<12} {passed} passed, {failed} failed, {skipped} skipped"
)?;
}
writeln!(f)?;
let (passed, failed, _) = self.tally(Severity::Required);
if passed + failed == 0 {
writeln!(
f,
"Nothing was measured: no required check could be attempted."
)
} else if self.is_conformant() {
writeln!(f, "No required check failed.")
} else {
writeln!(
f,
"NOT CONFORMANT: {} required check(s) failed.",
self.tally(Severity::Required).1
)
}
}
}
#[derive(Debug, Clone)]
pub struct Target {
pub base_url: String,
pub business_logic: Option<Credential>,
pub ven: Option<Credential>,
pub ven_client_id: Option<String>,
}
#[derive(Clone)]
pub enum Credential {
Token(String),
ClientCredentials {
id: String,
secret: String,
},
}
impl fmt::Debug for Credential {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Credential::Token(_) => f.write_str("Token(<redacted>)"),
Credential::ClientCredentials { id, .. } => f
.debug_struct("ClientCredentials")
.field("id", id)
.field("secret", &"<redacted>")
.finish(),
}
}
}
impl Target {
pub fn new(base_url: impl Into<String>) -> Self {
Self {
base_url: base_url.into(),
business_logic: None,
ven: None,
ven_client_id: None,
}
}
pub fn with_business_logic(mut self, credential: Credential) -> Self {
self.business_logic = Some(credential);
self
}
pub fn with_ven(mut self, credential: Credential, client_id: impl Into<String>) -> Self {
self.ven = Some(credential);
self.ven_client_id = Some(client_id.into());
self
}
}
pub struct Runner {
target: Target,
bl: Option<Client<BusinessLogic>>,
ven: Option<Client<VirtualEndNode>>,
litter: std::sync::Mutex<Vec<(&'static str, String)>>,
}
impl fmt::Debug for Runner {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Runner")
.field("target", &self.target)
.finish_non_exhaustive()
}
}
impl Runner {
pub fn new(target: Target) -> Result<Self, ClientError> {
let bl = target
.business_logic
.as_ref()
.map(|c| build::<BusinessLogic>(&target.base_url, c))
.transpose()?;
let ven = target
.ven
.as_ref()
.map(|c| build::<VirtualEndNode>(&target.base_url, c))
.transpose()?;
Ok(Self {
target,
bl,
ven,
litter: std::sync::Mutex::new(Vec::new()),
})
}
fn anonymous(&self) -> Result<Client<BusinessLogic>, ClientError> {
Client::<BusinessLogic>::builder(&self.target.base_url)?.build()
}
pub async fn run(&self) -> Report {
let mut report = Report {
target: self.target.base_url.clone(),
findings: Vec::new(),
};
for check in checks() {
let outcome = match self.precondition(check) {
Some(reason) => Outcome::Skipped(reason),
None => suite::run_one(self, check).await,
};
report.findings.push(Finding {
check: *check,
outcome,
});
}
self.cleanup().await;
report
}
fn precondition(&self, check: &Check) -> Option<String> {
match check.needs {
Needs::Nothing => None,
Needs::BusinessLogic if self.bl.is_none() => {
Some("no business-logic credential was supplied".into())
}
Needs::BothRoles if self.bl.is_none() => {
Some("no business-logic credential was supplied".into())
}
Needs::BothRoles if self.ven.is_none() => Some("no VEN credential was supplied".into()),
Needs::BothRoles if self.target.ven_client_id.is_none() => {
Some("the VEN's clientID was not supplied".into())
}
_ => None,
}
}
pub async fn cleanup(&self) {
let litter = {
let mut guard = self.litter.lock().unwrap_or_else(|e| e.into_inner());
std::mem::take(&mut *guard)
};
let Some(bl) = &self.bl else { return };
for (collection, id) in litter.into_iter().rev() {
let _ = bl
.exchange(
"DELETE",
&format!("{collection}/{id}"),
&crate::client::Query::new(),
None,
&[],
)
.await;
}
}
fn track(&self, collection: &'static str, id: impl Into<String>) {
self.litter
.lock()
.unwrap_or_else(|e| e.into_inner())
.push((collection, id.into()));
}
fn business_logic(&self) -> &Client<BusinessLogic> {
self.bl
.as_ref()
.expect("the precondition check guarantees a business-logic client")
}
fn virtual_end_node(&self) -> &Client<VirtualEndNode> {
self.ven
.as_ref()
.expect("the precondition check guarantees a VEN client")
}
}
fn build<R: crate::client::Role>(
base_url: &str,
credential: &Credential,
) -> Result<Client<R>, ClientError> {
let builder = Client::<R>::builder(base_url)?;
match credential {
Credential::Token(token) => builder.bearer_token(token),
Credential::ClientCredentials { id, secret } => {
builder.credentials(crate::client::Credentials::new(id, secret))
}
}
.build()
}
#[cfg(test)]
mod tests {
use super::*;
fn finding(id: &'static str, severity: Severity, outcome: Outcome) -> Finding {
Finding {
check: Check {
id,
clause: "[API]",
title: "t",
severity,
needs: Needs::Nothing,
},
outcome,
}
}
#[test]
fn a_skip_is_not_a_pass() {
let report = Report {
target: "https://vtn.test".into(),
findings: vec![
finding("a", Severity::Required, Outcome::Passed),
finding(
"b",
Severity::Required,
Outcome::Skipped("no broker".into()),
),
],
};
assert_eq!(report.tally(Severity::Required), (1, 0, 1));
assert!(
report.is_conformant(),
"a skip is not a failure either — it is an absence of evidence"
);
assert!(report.to_string().contains("skip"));
}
#[test]
fn an_extension_failure_does_not_overturn_a_required_pass() {
let mut report = Report {
target: "https://vtn.test".into(),
findings: vec![
finding("baseline", Severity::Required, Outcome::Passed),
finding(
"ext",
Severity::Extension,
Outcome::Failed("no ETag".into()),
),
],
};
assert!(
report.is_conformant(),
"an extension this VTN happens not to implement is information, not non-conformance"
);
report.findings.push(finding(
"req",
Severity::Required,
Outcome::Failed("no".into()),
));
assert!(!report.is_conformant());
assert_eq!(report.failures().count(), 2);
assert!(report.to_string().contains("NOT CONFORMANT"));
}
#[test]
fn every_check_is_uniquely_identified_and_cites_a_clause() {
let mut ids: Vec<&str> = checks().iter().map(|c| c.id).collect();
let count = ids.len();
ids.sort_unstable();
ids.dedup();
assert_eq!(ids.len(), count, "two checks share an identifier");
for check in checks() {
assert!(!check.clause.is_empty(), "{} cites nothing", check.id);
assert!(
check.severity != Severity::Extension || check.clause.contains("extension"),
"{} is marked Extension but cites {}",
check.id,
check.clause
);
}
}
#[test]
fn the_report_renders_as_json_for_a_matrix() {
let report = Report {
target: "https://vtn.test".into(),
findings: vec![finding(
"a",
Severity::Required,
Outcome::Failed("expected 201".into()),
)],
};
let json = report.to_json();
assert_eq!(json["conformant"], false);
assert_eq!(json["findings"][0]["outcome"], "failed");
assert_eq!(json["findings"][0]["detail"], "expected 201");
}
#[test]
fn a_credential_never_prints_its_secret() {
let rendered = format!(
"{:?}",
Credential::ClientCredentials {
id: "bl-1".into(),
secret: "hunter2".into(),
}
);
assert!(!rendered.contains("hunter2"), "{rendered}");
assert!(rendered.contains("bl-1"));
assert!(!format!("{:?}", Credential::Token("t0ken".into())).contains("t0ken"));
}
}