icedwright 0.0.1

The icedwright test harness: run an iced 0.14 program headlessly on virtual time
Documentation
//! [`CoverageFile`]: which message variants a test produced and which nodes it saw, one JSON
//! file per test under `target/icedwright/coverage/`, written when `ICEDWRIGHT_COVERAGE` is
//! set.

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;

/// One test's coverage, as the CLI and the studio read it. Every map and list is sorted, so
/// two runs of one test write identical bytes.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct CoverageFile {
    /// [`CoverageFile::VERSION`].
    pub version: u32,
    /// The test's path, such as `ui::saves::phone_dark`.
    pub test: String,
    /// Message variants, present when the message derives `Messages`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub messages: Option<MessageCoverageFile>,
    /// Nodes by stable path.
    pub nodes: Vec<NodeCoverage>,
}

/// Every variant the message type has, and how often each was seen.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct MessageCoverageFile {
    /// Every variant, nested ones as `Editor::Bold`, sorted.
    pub known: Vec<String>,
    /// Variants seen at least once, with their counts.
    pub seen: BTreeMap<String, u64>,
}

/// One node and what the test did with it.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct NodeCoverage {
    /// The node's stable path.
    pub path: String,
    /// Whether the test saw it.
    pub seen: bool,
    /// The actions performed on it.
    pub acted: Vec<String>,
}

impl MessageCoverageFile {
    /// The file form of a harness's [`MessageCoverage`].
    #[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 {
    /// The format version this crate writes and reads.
    pub const VERSION: u32 = 1;

    /// The coverage of `harness` so far: the nodes of its current tree, and `messages` when
    /// the message type's variants are known.
    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(),
        }
    }

    /// [`collect`](Self::collect) with message coverage from `#[derive(Messages)]`.
    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))
    }

    /// The JSON, pretty-printed.
    pub fn to_json(&self) -> crate::Result<String> {
        Ok(serde_json::to_string_pretty(self)?)
    }

    /// Reads a file back, refusing a version this crate does not know.
    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)
    }

    /// Where the file for `test` in `package` goes under `coverage_dir`: one directory per
    /// module.
    #[must_use]
    pub fn path_in(coverage_dir: &Path, package: &str, test: &str) -> PathBuf {
        test_path(coverage_dir, package, test, ".json")
    }

    /// Writes the file under `coverage_dir` and returns its path.
    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)
    }
}

/// `ICEDWRIGHT_COVERAGE`, parsed once.
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",
        )),
    }
}

/// Writes the test's coverage file when `ICEDWRIGHT_COVERAGE` asks for it.
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());
    }
}