use std::fs;
use std::path::PathBuf;
use std::time::{SystemTime, UNIX_EPOCH};
use anyhow::{Context, Result};
use musli::{Decode, Encode};
const VERSION: u32 = 1;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Encode, Decode)]
#[musli(Text, name_all = "kebab-case")]
pub(crate) enum Outcome {
Passed,
Failed,
NotRun,
}
#[derive(Debug, Clone, Encode, Decode)]
#[musli(Text, name_all = "kebab-case")]
pub(crate) struct Ran {
pub(crate) name: String,
pub(crate) outcome: Outcome,
#[musli(default, skip_encoding_if = Option::is_none)]
pub(crate) message: Option<String>,
#[musli(default, skip_encoding_if = Option::is_none)]
pub(crate) seconds: Option<f64>,
}
#[derive(Debug, Clone, Encode, Decode)]
#[musli(Text, name_all = "kebab-case")]
pub(crate) struct Session {
version: u32,
pub(crate) name: String,
pub(crate) started: u64,
pub(crate) whole: bool,
pub(crate) tests: Vec<Ran>,
}
impl Session {
pub(crate) fn new(names: impl IntoIterator<Item = String>) -> Self {
let started = now();
Self {
version: VERSION,
name: name_for(started),
started,
whole: false,
tests: names
.into_iter()
.map(|name| Ran {
name,
outcome: Outcome::NotRun,
message: None,
seconds: None,
})
.collect(),
}
}
pub(crate) fn record(
&mut self,
name: &str,
outcome: Outcome,
message: Option<String>,
seconds: Option<f64>,
) {
if let Some(ran) = self.tests.iter_mut().find(|ran| ran.name == name) {
ran.outcome = outcome;
ran.message = message;
ran.seconds = seconds;
}
}
pub(crate) fn failures(&self) -> impl Iterator<Item = (&str, &str, Option<f64>)> {
self.tests.iter().filter_map(|ran| {
let message = ran.message.as_deref()?;
(ran.outcome == Outcome::Failed).then_some((ran.name.as_str(), message, ran.seconds))
})
}
pub(crate) fn slowest(&self, most: usize) -> Vec<(&str, f64)> {
let mut timed = self
.tests
.iter()
.filter_map(|ran| Some((ran.name.as_str(), ran.seconds?)))
.collect::<Vec<_>>();
timed.sort_by(|a, b| b.1.total_cmp(&a.1));
timed.truncate(most);
timed
}
pub(crate) fn unfinished(&self) -> Vec<&str> {
self.tests
.iter()
.filter(|ran| ran.outcome != Outcome::Passed)
.map(|ran| ran.name.as_str())
.collect()
}
pub(crate) fn counts(&self) -> (usize, usize, usize) {
let mut counts = (0, 0, 0);
for ran in &self.tests {
match ran.outcome {
Outcome::Passed => counts.0 += 1,
Outcome::Failed => counts.1 += 1,
Outcome::NotRun => counts.2 += 1,
}
}
counts
}
pub(crate) fn save(&self) -> Result<PathBuf> {
let dir = dir()?;
fs::create_dir_all(&dir).with_context(|| format!("creating {}", dir.display()))?;
let path = dir.join(format!("{}.json", self.name));
let temporary = path.with_extension("json.writing");
let text = musli::json::to_string(self).context("writing the session")?;
fs::write(&temporary, text).with_context(|| format!("writing {}", temporary.display()))?;
fs::rename(&temporary, &path).with_context(|| format!("naming {}", path.display()))?;
Ok(path)
}
}
pub(crate) fn dir() -> Result<PathBuf> {
let name = DIR.get().map_or("e2e-sessions", String::as_str);
Ok(crate::dist::target_dir()?.join(name))
}
static DIR: std::sync::OnceLock<String> = std::sync::OnceLock::new();
pub(crate) fn name_dir(name: &str) {
_ = DIR.set(name.to_owned());
}
pub(crate) fn load(name: &str) -> Result<Session> {
let path = dir()?.join(format!("{name}.json"));
let text = fs::read(&path)
.with_context(|| format!("no session called {name} at {}", path.display()))?;
let session: Session =
musli::json::from_slice(&text).with_context(|| format!("reading {}", path.display()))?;
anyhow::ensure!(
session.version == VERSION,
"{name} was written by another build of the suite"
);
Ok(session)
}
pub(crate) fn latest() -> Result<Session> {
let dir = dir()?;
let Ok(entries) = fs::read_dir(&dir) else {
anyhow::bail!(
"no sessions yet in {} - run the suite once first",
dir.display()
);
};
let mut newest: Option<Session> = None;
for entry in entries.flatten() {
let path = entry.path();
if path.extension().is_none_or(|extension| extension != "json") {
continue;
}
let Ok(text) = fs::read(&path) else {
continue;
};
let Ok(session) = musli::json::from_slice::<Session>(&text) else {
continue;
};
if session.version != VERSION {
continue;
}
if newest
.as_ref()
.is_none_or(|held| session.started > held.started)
{
newest = Some(session);
}
}
newest.with_context(|| format!("no session in {} this build can read", dir.display()))
}
fn now() -> u64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|since| since.as_secs())
.unwrap_or_default()
}
fn name_for(started: u64) -> String {
let (date, time) = stamp(started);
let adjective = ADJECTIVES[rand::random_range(0..ADJECTIVES.len())];
let noun = NOUNS[rand::random_range(0..NOUNS.len())];
let tail = rand::random::<u16>();
format!("{date}-{time}-{adjective}-{noun}-{tail:04x}")
}
fn stamp(seconds: u64) -> (String, String) {
let days = seconds / 86_400;
let rest = seconds % 86_400;
let (year, month, day) = civil(days);
(
format!("{year:04}{month:02}{day:02}"),
format!(
"{:02}{:02}{:02}",
rest / 3_600,
(rest % 3_600) / 60,
rest % 60
),
)
}
fn civil(days: u64) -> (u64, u64, u64) {
let days = days + 719_468;
let era = days / 146_097;
let of_era = days % 146_097;
let year_of_era = (of_era - of_era / 1_460 + of_era / 36_524 - of_era / 146_096) / 365;
let year = year_of_era + era * 400;
let of_year = of_era - (365 * year_of_era + year_of_era / 4 - year_of_era / 100);
let month_of_year = (5 * of_year + 2) / 153;
let day = of_year - (153 * month_of_year + 2) / 5 + 1;
let month = if month_of_year < 10 {
month_of_year + 3
} else {
month_of_year - 9
};
(year + u64::from(month <= 2), month, day)
}
const ADJECTIVES: [&str; 32] = [
"amber", "brisk", "calm", "clear", "cool", "deep", "dry", "even", "fair", "firm", "flat",
"fresh", "glad", "keen", "level", "light", "loud", "mild", "near", "open", "plain", "quick",
"quiet", "round", "sharp", "short", "slow", "soft", "steady", "still", "warm", "wide",
];
const NOUNS: [&str; 32] = [
"amp", "band", "bay", "bell", "bus", "cable", "chord", "cue", "dial", "drum", "fader", "gate",
"horn", "jack", "knob", "lane", "meter", "mic", "note", "patch", "pedal", "pitch", "port",
"reed", "reel", "rig", "room", "stage", "strip", "take", "tone", "track",
];
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_name_sorts_by_when_the_run_started() {
let first = name_for(1_756_900_000);
let second = name_for(1_756_900_001);
assert!(first < second, "{first} did not sort before {second}");
}
#[test]
fn a_day_count_reads_as_a_date() {
assert_eq!(stamp(0).0, "19700101");
assert_eq!(stamp(86_399).1, "235959");
assert_eq!(stamp(951_782_400).0, "20000229", "a leap day");
assert_eq!(stamp(1_756_900_000).0, "20250903");
}
#[test]
fn a_session_hands_on_what_did_not_pass() {
let mut session = Session::new(["a", "b", "c", "d"].map(String::from));
session.record("a", Outcome::Passed, None, Some(1.0));
session.record(
"b",
Outcome::Failed,
Some("b said no".to_owned()),
Some(2.5),
);
session.record("c", Outcome::Passed, None, Some(0.5));
assert_eq!(session.unfinished(), ["b", "d"]);
assert_eq!(session.counts(), (2, 1, 1));
assert_eq!(
session.failures().collect::<Vec<_>>(),
[("b", "b said no", Some(2.5))]
);
}
#[test]
fn a_session_survives_the_round_trip() {
let mut session = Session::new(["one", "two"].map(String::from));
session.record(
"one",
Outcome::Failed,
Some("one said no".to_owned()),
Some(12.5),
);
session.whole = true;
let text = musli::json::to_string(&session).expect("a session encodes");
let back: Session = musli::json::from_slice(text.as_bytes()).expect("and decodes");
assert_eq!(back.name, session.name);
assert_eq!(back.started, session.started);
assert!(back.whole);
assert_eq!(back.unfinished(), ["one", "two"]);
assert_eq!(
back.failures().collect::<Vec<_>>(),
[("one", "one said no", Some(12.5))]
);
let two = back.tests.iter().find(|ran| ran.name == "two").unwrap();
assert_eq!(two.seconds, None);
}
#[test]
fn the_slowest_are_the_timed_ones_longest_first() {
let mut session =
Session::new(["quick", "slow", "middling", "never-ran"].map(String::from));
session.record("quick", Outcome::Passed, None, Some(1.5));
session.record("slow", Outcome::Passed, None, Some(30.25));
session.record(
"middling",
Outcome::Failed,
Some("no".to_owned()),
Some(9.0),
);
assert_eq!(
session.slowest(3),
[("slow", 30.25), ("middling", 9.0), ("quick", 1.5)]
);
assert_eq!(session.slowest(2), [("slow", 30.25), ("middling", 9.0)]);
assert_eq!(session.slowest(10).len(), 3);
let untimed = Session::new(["one".to_owned()]);
assert!(untimed.slowest(3).is_empty());
}
#[test]
fn a_session_without_messages_still_reads() {
let text = format!(
concat!(
r#"{{"version":{version},"name":"n","started":1,"whole":true,"#,
r#""tests":[{{"name":"one","outcome":"failed"}}]}}"#
),
version = VERSION
);
let session: Session = musli::json::from_slice(text.as_bytes()).expect("a session decodes");
assert_eq!(session.unfinished(), ["one"]);
assert_eq!(session.failures().count(), 0);
}
#[test]
fn a_session_without_durations_still_reads() {
let text = format!(
concat!(
r#"{{"version":{version},"name":"n","started":1,"whole":true,"#,
r#""tests":[{{"name":"one","outcome":"failed","message":"one said no"}},"#,
r#"{{"name":"two","outcome":"passed"}}]}}"#
),
version = VERSION
);
let session: Session = musli::json::from_slice(text.as_bytes()).expect("a session decodes");
assert_eq!(session.unfinished(), ["one"]);
assert_eq!(
session.failures().collect::<Vec<_>>(),
[("one", "one said no", None)],
"an older session reported a duration it never carried"
);
}
#[test]
fn a_passing_test_is_timed_as_well() {
let mut session = Session::new(["one"].map(String::from));
session.record("one", Outcome::Passed, None, Some(3.25));
let text = musli::json::to_string(&session).expect("a session encodes");
let back: Session = musli::json::from_slice(text.as_bytes()).expect("and decodes");
assert_eq!(back.tests[0].seconds, Some(3.25));
}
}