use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use std::sync::OnceLock;
use icedwright_types::Messages;
use serde::{Deserialize, Serialize};
use crate::error::ConfigError;
use crate::harness::{Harness, TestProgram};
use crate::messages::MessageCoverage;
use super::builtin::{out_dir, test_path};
use super::support::TestInfo;
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct CoverageFile {
pub version: u32,
pub test: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub messages: Option<MessageCoverageFile>,
pub nodes: Vec<NodeCoverage>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct MessageCoverageFile {
pub known: Vec<String>,
pub seen: BTreeMap<String, u64>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct NodeCoverage {
pub path: String,
pub seen: bool,
pub acted: Vec<String>,
}
impl MessageCoverageFile {
#[must_use]
pub fn of<M: Messages>(coverage: &MessageCoverage<M>) -> Self {
let mut known = Vec::new();
let mut seen = BTreeMap::new();
for (variant, count) in coverage.counts() {
known.push(variant.as_str().to_owned());
if count > 0 {
seen.insert(variant.as_str().to_owned(), count);
}
}
known.sort();
Self { known, seen }
}
}
impl CoverageFile {
pub const VERSION: u32 = 1;
pub fn collect<P: TestProgram>(
test: impl Into<String>,
harness: &mut Harness<P>,
messages: Option<MessageCoverageFile>,
) -> Self {
let mut nodes = BTreeMap::new();
if let Ok(tree) = harness.tree() {
for node in tree.iter() {
let path = node.path.to_string();
nodes.entry(path.clone()).or_insert(NodeCoverage {
path,
seen: true,
acted: Vec::new(),
});
}
}
Self {
version: Self::VERSION,
test: test.into(),
messages,
nodes: nodes.into_values().collect(),
}
}
pub fn of<P: TestProgram>(test: impl Into<String>, harness: &mut Harness<P>) -> Self
where
P::Message: Messages,
{
let messages = MessageCoverageFile::of(&harness.coverage());
Self::collect(test, harness, Some(messages))
}
pub fn to_json(&self) -> crate::Result<String> {
Ok(serde_json::to_string_pretty(self)?)
}
pub fn from_json(json: &str) -> crate::Result<Self> {
let file: Self = serde_json::from_str(json)?;
if file.version != Self::VERSION {
return Err(ConfigError::invalid(
"coverage file version",
file.version.to_string(),
"version 1",
)
.into());
}
Ok(file)
}
#[must_use]
pub fn path_in(coverage_dir: &Path, package: &str, test: &str) -> PathBuf {
test_path(coverage_dir, package, test, ".json")
}
pub fn write_to(&self, coverage_dir: &Path, package: &str) -> crate::Result<PathBuf> {
let path = Self::path_in(coverage_dir, package, &self.test);
if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent)?;
}
std::fs::write(&path, self.to_json()?)?;
Ok(path)
}
}
fn enabled() -> crate::Result<bool> {
static PARSED: OnceLock<Result<bool, ConfigError>> = OnceLock::new();
PARSED
.get_or_init(|| match std::env::var("ICEDWRIGHT_COVERAGE") {
Err(_) => Ok(false),
Ok(value) => parse_switch(&value),
})
.clone()
.map_err(crate::Error::from)
}
fn parse_switch(value: &str) -> Result<bool, ConfigError> {
match value {
"1" | "true" | "on" => Ok(true),
"" | "0" | "false" | "off" => Ok(false),
_ => Err(ConfigError::invalid(
"ICEDWRIGHT_COVERAGE",
value,
"1 to write coverage files, or 0",
)),
}
}
pub(crate) fn write_if_enabled<P: TestProgram>(
info: &TestInfo,
harness: &mut Harness<P>,
messages: Option<MessageCoverageFile>,
) -> crate::Result {
if !enabled()? {
return Ok(());
}
let file = CoverageFile::collect(info.path(), harness, messages);
file.write_to(&out_dir()?.join("coverage"), info.package)?;
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_switch_reads_on_and_off() {
assert_eq!(parse_switch("1"), Ok(true));
assert_eq!(parse_switch("0"), Ok(false));
assert_eq!(parse_switch(""), Ok(false));
assert!(parse_switch("yes please").is_err());
}
#[test]
fn the_json_is_sorted_and_round_trips() {
let file = CoverageFile {
version: 1,
test: "ui::saves::phone_dark".to_owned(),
messages: Some(MessageCoverageFile {
known: vec!["Editor::Bold".to_owned(), "Save".to_owned()],
seen: BTreeMap::from([("Save".to_owned(), 1)]),
}),
nodes: vec![NodeCoverage {
path: "window \"Notes\"".to_owned(),
seen: true,
acted: Vec::new(),
}],
};
let json = file.to_json().unwrap();
assert_eq!(json, file.to_json().unwrap());
assert!(json.find("\"version\"").unwrap() < json.find("\"test\"").unwrap());
assert_eq!(CoverageFile::from_json(&json).unwrap(), file);
let newer = json.replace("\"version\": 1", "\"version\": 2");
assert!(CoverageFile::from_json(&newer).is_err());
}
}