use std::path::{Path, PathBuf};
use std::sync::OnceLock;
use super::SnapshotError;
use crate::error::ConfigError;
const UPDATE: &str = "ICEDWRIGHT_UPDATE";
const OUT_DIR: &str = "ICEDWRIGHT_OUT_DIR";
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Runner {
ProcessPerTest,
Shared,
}
impl Runner {
#[must_use]
pub fn from_vars(get: impl Fn(&str) -> Option<String>) -> Runner {
let nextest = get("NEXTEST").as_deref() == Some("1");
let per_test = get("NEXTEST_EXECUTION_MODE").as_deref() == Some("process-per-test");
if nextest && per_test {
Runner::ProcessPerTest
} else {
Runner::Shared
}
}
#[must_use]
pub fn current() -> Runner {
static RUNNER: OnceLock<Runner> = OnceLock::new();
*RUNNER.get_or_init(|| Runner::from_vars(|name| std::env::var(name).ok()))
}
pub fn require(self, what: &str) -> Result<(), SnapshotError> {
match self {
Runner::ProcessPerTest => Ok(()),
Runner::Shared => Err(SnapshotError::NeedsProcessPerTest {
what: what.to_owned(),
}),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum UpdateMode {
#[default]
Review,
Always,
}
impl UpdateMode {
pub fn parse(value: Option<&str>) -> Result<UpdateMode, ConfigError> {
match value {
None | Some("" | "no") => Ok(UpdateMode::Review),
Some("always") => Ok(UpdateMode::Always),
Some(other) => Err(ConfigError::invalid(UPDATE, other, "always or no")),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SnapshotEnv {
pub runner: Runner,
pub update: UpdateMode,
pub ci: bool,
pub out_dir: PathBuf,
pub manifest_dir: Option<PathBuf>,
pub crate_name: String,
pub binary: String,
pub test: Option<String>,
}
impl SnapshotEnv {
pub fn from_vars(
get: impl Fn(&str) -> Option<String>,
exe: Option<&Path>,
thread: Option<&str>,
) -> Result<SnapshotEnv, ConfigError> {
let ci = get("CI").is_some_and(|value| !matches!(value.as_str(), "" | "0" | "false"));
let out = get(OUT_DIR)
.filter(|dir| !dir.is_empty())
.map_or_else(|| PathBuf::from("target/icedwright"), PathBuf::from);
Ok(SnapshotEnv {
runner: Runner::from_vars(&get),
update: UpdateMode::parse(get(UPDATE).as_deref())?,
ci,
out_dir: crate::trace::resolve_out_dir(&out, exe),
manifest_dir: get("CARGO_MANIFEST_DIR").map(PathBuf::from),
crate_name: get("CARGO_PKG_NAME").unwrap_or_else(|| "unknown".to_owned()),
binary: exe.map(binary_name).unwrap_or_else(|| "unknown".to_owned()),
test: thread
.filter(|name| *name != "main" && !name.is_empty())
.map(str::to_owned),
})
}
pub fn current() -> Result<SnapshotEnv, ConfigError> {
let exe = std::env::current_exe().ok();
let thread = std::thread::current();
let mut env = SnapshotEnv::from_vars(
|name| std::env::var(name).ok(),
exe.as_deref(),
thread.name(),
)?;
env.runner = Runner::current();
Ok(env)
}
pub(crate) fn test_path(&self) -> Result<&str, SnapshotError> {
self.test.as_deref().ok_or_else(|| {
SnapshotError::Location(
"could not tell which test is running: libtest names each test's thread after it, and this thread has no such name".to_owned(),
)
})
}
}
fn binary_name(exe: &Path) -> String {
let stem = exe
.file_stem()
.and_then(|stem| stem.to_str())
.unwrap_or("unknown");
match stem.rsplit_once('-') {
Some((name, hash)) if hash.len() == 16 && hash.chars().all(|c| c.is_ascii_hexdigit()) => {
name.to_owned()
}
_ => stem.to_owned(),
}
}
#[cfg(test)]
mod tests {
use super::*;
fn vars(pairs: &'static [(&'static str, &'static str)]) -> impl Fn(&str) -> Option<String> {
move |name| {
pairs
.iter()
.find(|(key, _)| *key == name)
.map(|(_, value)| (*value).to_owned())
}
}
#[test]
fn only_nextest_in_process_per_test_mode_is_a_process_per_test() {
let per_test = vars(&[
("NEXTEST", "1"),
("NEXTEST_EXECUTION_MODE", "process-per-test"),
]);
assert_eq!(Runner::from_vars(per_test), Runner::ProcessPerTest);
assert_eq!(Runner::from_vars(vars(&[])), Runner::Shared);
assert_eq!(Runner::from_vars(vars(&[("NEXTEST", "1")])), Runner::Shared);
let shared = vars(&[("NEXTEST", "1"), ("NEXTEST_EXECUTION_MODE", "test-group")]);
assert_eq!(Runner::from_vars(shared), Runner::Shared);
}
#[test]
fn a_shared_process_refuses_with_the_fixed_message() {
let Err(error) = Runner::Shared.require("to_match_image(\"reader\")") else {
panic!("a shared process should refuse");
};
assert_eq!(
error.to_string(),
"to_match_image(\"reader\") needs a process per test\n\n The font database is shared by every test in this process, and a font\n loaded by another test can change the glyphs this snapshot draws\n (cosmic-text falls back to any loaded face for missing glyphs).\n Run visual snapshot tests with `cargo nextest run`, which starts a\n process per test. Semantic snapshots and actions work under cargo test."
);
assert!(Runner::ProcessPerTest.require("anything").is_ok());
}
#[test]
fn the_update_mode_takes_always_or_nothing() {
assert_eq!(UpdateMode::parse(None).ok(), Some(UpdateMode::Review));
assert_eq!(UpdateMode::parse(Some("no")).ok(), Some(UpdateMode::Review));
assert_eq!(
UpdateMode::parse(Some("always")).ok(),
Some(UpdateMode::Always)
);
assert!(UpdateMode::parse(Some("yes")).is_err());
}
#[test]
fn the_environment_is_read_from_the_variables_given() {
let env = SnapshotEnv::from_vars(
vars(&[
("CI", "true"),
("ICEDWRIGHT_OUT_DIR", "/tmp/out"),
("CARGO_MANIFEST_DIR", "/src/app"),
("CARGO_PKG_NAME", "app"),
("ICEDWRIGHT_UPDATE", "always"),
]),
Some(Path::new("/target/debug/deps/looks-0123456789abcdef")),
Some("ui::reader"),
)
.unwrap();
assert!(env.ci);
assert_eq!(env.update, UpdateMode::Always);
assert_eq!(env.out_dir, PathBuf::from("/tmp/out"));
assert_eq!(env.manifest_dir, Some(PathBuf::from("/src/app")));
assert_eq!(env.binary, "looks");
assert_eq!(env.test.as_deref(), Some("ui::reader"));
let default = SnapshotEnv::from_vars(
vars(&[("CI", "false")]),
Some(Path::new("/work/target/debug/deps/looks-0123456789abcdef")),
Some("main"),
)
.unwrap();
assert!(!default.ci);
assert_eq!(
default.out_dir,
PathBuf::from("/work/target/icedwright"),
"the default follows the target directory"
);
assert!(default.test_path().is_err());
}
}