use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use serde_json::{Map, Value, json};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum Outcome {
Passed,
Failed,
Error,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum Verbosity {
Off,
Error,
Warn,
Info,
Debug,
Trace,
}
pub const VERBOSITY_ENV: &str = "GRIZ_VERBOSITY";
impl Verbosity {
pub fn resolve(explicit: Option<&str>) -> Result<Self, String> {
let env = std::env::var(VERBOSITY_ENV).ok();
match explicit.or(env.as_deref()).unwrap_or("error") {
"off" => Ok(Self::Off),
"error" => Ok(Self::Error),
"warn" => Ok(Self::Warn),
"info" => Ok(Self::Info),
"debug" => Ok(Self::Debug),
"trace" => Ok(Self::Trace),
other => Err(format!(
"unknown verbosity `{other}`; use off, error, warn, info, debug, or trace"
)),
}
}
}
#[derive(Debug, Clone)]
pub struct Rendered {
pub id: String,
pub outcome: Outcome,
pub reason: Option<String>,
pub summary: Value,
pub detail: Value,
pub record: Value,
}
impl Rendered {
#[must_use]
pub fn with_outcome(mut self, outcome: Outcome) -> Self {
self.outcome = outcome;
self
}
#[must_use]
pub fn at(&self, level: Verbosity, replayed: bool) -> Value {
if level == Verbosity::Trace {
return self.traced(replayed);
}
let mut out = Map::new();
out.insert("id".into(), json!(self.id));
out.insert("outcome".into(), json!(self.outcome));
insert_replayed(&mut out, replayed);
let reason = self
.reason
.as_ref()
.filter(|_| self.outcome != Outcome::Passed);
if let Some(reason) = reason.filter(|_| level >= Verbosity::Warn) {
out.insert("reason".into(), json!(reason));
}
if level >= Verbosity::Info {
out.insert("summary".into(), self.summary.clone());
}
if level >= Verbosity::Debug {
out.insert("detail".into(), self.detail.clone());
}
Value::Object(out)
}
fn traced(&self, replayed: bool) -> Value {
let mut record = self.record.clone();
if let Value::Object(map) = &mut record {
map.insert("outcome".into(), json!(self.outcome));
insert_replayed(map, replayed);
}
record
}
}
fn insert_replayed(map: &mut Map<String, Value>, replayed: bool) {
if replayed {
map.insert("replayed".into(), json!(true));
}
}
#[must_use]
pub fn unmet(label: &str, expected: Option<usize>, actual: usize) -> Option<String> {
let expected = expected?;
(expected != actual).then(|| format!("expected {expected} {label}, observed {actual}"))
}