icedwright-trace 0.0.2

The icedwright trace format: a deterministic .iwtrace archive of every step a test took, with its writer, reader and comparison
Documentation
//! The records a trace holds: one [`Step`] per call the test made on the harness.

use std::borrow::Cow;
use std::time::Duration;

use icedwright_types::{Point, VirtualDuration};
use serde::{Deserialize, Serialize};

use crate::blob::{BlobRef, Png, Yaml};
use crate::ids::{StepIndex, SubscriptionOrdinal, TaskOrdinal, WindowOrdinal};

/// One call the test made on the harness: an action, an `expect`, a clock advance, a task
/// release or a window change. Times are measured from boot.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Step {
    /// Its position in the trace.
    pub index: StepIndex,
    /// What the test asked for.
    pub kind: StepKind,
    /// The line of the test that made the call.
    pub location: SourceLocation,
    /// When the step began.
    pub virtual_start: VirtualDuration,
    /// When it ended.
    pub virtual_end: VirtualDuration,
    /// The input events delivered during the step.
    pub events: Vec<TraceEvent>,
    /// The messages produced during the step.
    pub messages: Vec<TraceMessage>,
    /// Task lifecycle changes during the step.
    pub tasks: Vec<TraceTask>,
    /// A unified diff of the state's `Debug` text, when the test asked for state tracing.
    pub state_diff: Option<String>,
    /// Each evaluation of an `expect`.
    pub attempts: Vec<Attempt>,
    /// What the harness did on the way, such as waiting for a node to become actionable,
    /// scrolling it into view and where it clicked. Left out of the file when empty.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub log: Vec<LogLine>,
    /// The tree before the step, which is the previous step's tree after.
    pub tree_before: BlobRef<Yaml>,
    /// The tree once the step settled.
    pub tree_after: BlobRef<Yaml>,
    /// The frame before the step, unless the frame policy or the size cap left it out.
    pub frame_before: Option<BlobRef<Png>>,
    /// The frame once the step settled, unless the frame policy or the size cap left it out.
    pub frame_after: Option<BlobRef<Png>>,
    /// How it ended.
    pub outcome: StepOutcome,
}

/// What the test asked for in a step. Action, assertion, task control and window change kinds
/// are stored by name.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum StepKind {
    /// An action on a widget, or on a point.
    Action {
        /// The action's name, such as `click`.
        action: String,
        /// The locator acted on.
        locator: Option<SelectorText>,
        /// The node it resolved to, printed.
        resolved: Option<String>,
        /// The point acted on, in logical pixels.
        point: Option<Point>,
        /// What a keyboard action entered: the chord a `press` sent, such as `Enter`, or the
        /// text a `fill` or `press_sequentially` typed. Absent for pointer actions and in
        /// traces written before it was recorded.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        input: Option<String>,
    },
    /// An `expect`, with every attempt in [`Step::attempts`].
    Expect {
        /// The locator under test.
        subject: SelectorText,
        /// The assertion's name, such as `to_be_visible`.
        assertion: String,
        /// Whether it was negated with `not()`.
        negated: bool,
    },
    /// An explicit advance of the virtual clock.
    Advance {
        /// How far.
        by: VirtualDuration,
    },
    /// Control of a named task.
    Task {
        /// The task's name.
        name: String,
        /// The control's name, such as `release`.
        control: String,
    },
    /// A change to a window, such as a resize.
    Window {
        /// The window.
        window: WindowOrdinal,
        /// The change's name.
        change: String,
    },
}

impl StepKind {
    /// Whether this is an action, which [`FramePolicy::ActionsOnly`](crate::FramePolicy) keeps
    /// frames for.
    #[must_use]
    pub fn is_action(&self) -> bool {
        matches!(self, StepKind::Action { .. })
    }
}

/// Implemented by a locator, whose canonical printed form always parses back to it.
pub trait CanonicalSelector {
    /// The selector in its canonical printed form.
    fn canonical(&self) -> String;
}

/// A selector in its canonical printed form. It is made only from a [`CanonicalSelector`],
/// so it always parses.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(transparent)]
pub struct SelectorText(String);

impl SelectorText {
    /// The canonical text of `selector`.
    #[must_use]
    pub fn of(selector: &impl CanonicalSelector) -> Self {
        Self(selector.canonical())
    }

    /// The text.
    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

/// A place in the test's source.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
pub struct SourceLocation {
    /// The file, as `file!()` prints it.
    pub file: String,
    /// The one-based line.
    pub line: u32,
    /// The one-based column.
    pub column: u32,
}

impl From<&std::panic::Location<'_>> for SourceLocation {
    fn from(location: &std::panic::Location<'_>) -> Self {
        Self {
            file: location.file().to_owned(),
            line: location.line(),
            column: location.column(),
        }
    }
}

/// Whether a widget captured an input event, as iced's `event::Status` reports it.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Captured {
    /// No widget handled the event.
    Ignored,
    /// A widget handled the event.
    Captured,
}

/// An input event the harness delivered, with its window renumbered.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct TraceEvent {
    /// When it was delivered.
    pub at: VirtualDuration,
    /// The window it went to.
    pub window: WindowOrdinal,
    /// The event in the remote protocol's structured form, as JSON text.
    pub event: String,
    /// Whether a widget captured it.
    pub status: Captured,
}

/// A message, as its normalised `Debug` text.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct TraceMessage {
    /// When it was produced.
    pub at: VirtualDuration,
    /// Its `Debug` text, with instants rewritten as offsets from boot and cut to 4 KiB.
    pub debug: String,
    /// The length of the `Debug` text before it was cut; set by the writer.
    pub full_len: Option<u64>,
    /// The variant name from `#[derive(Messages)]`, when the message type has it.
    pub variant: Option<Cow<'static, str>>,
    /// What produced it.
    pub origin: TraceOrigin,
}

/// What produced a message.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum TraceOrigin {
    /// A widget, from the event at this position in the step's events.
    Widget {
        /// The event's position in [`Step::events`].
        event: u32,
    },
    /// A task.
    Task(TaskOrdinal),
    /// A subscription.
    Subscription(SubscriptionOrdinal),
}

/// A change in a task's life.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct TraceTask {
    /// The task.
    pub id: TaskOrdinal,
    /// Its name, for named tasks.
    pub name: Option<String>,
    /// When the change happened.
    pub at: VirtualDuration,
    /// What changed.
    pub change: TraceTaskChange,
}

/// What happened to a task.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum TraceTaskChange {
    /// It started, from the message at this position in the step's messages if any.
    Spawned {
        /// The message's position in [`Step::messages`].
        by_message: Option<u32>,
    },
    /// The test held it.
    Held,
    /// The test released it.
    Released,
    /// The test resolved it with a value.
    Resolved,
    /// A newer task with the same name replaced it.
    Replaced,
    /// It finished.
    Finished,
    /// It failed.
    Failed {
        /// The error, printed.
        error: String,
    },
    /// It was aborted.
    Aborted,
}

/// One line of a step's call log.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct LogLine {
    /// When it happened.
    pub at: VirtualDuration,
    /// What happened, in a short sentence.
    pub text: String,
}

/// One evaluation of an `expect`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Attempt {
    /// When it was evaluated.
    pub at: VirtualDuration,
    /// How many nodes matched.
    pub matched: u32,
    /// The nearest-match text.
    pub detail: String,
}

/// How a step ended.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum StepOutcome {
    /// It did what was asked.
    Passed,
    /// It returned an error.
    Failed {
        /// The error, printed.
        message: String,
    },
    /// The app or the test panicked during it.
    Panicked {
        /// The panic message.
        message: String,
    },
}

impl StepOutcome {
    /// Whether the step failed or panicked.
    #[must_use]
    pub fn is_failure(&self) -> bool {
        !matches!(self, StepOutcome::Passed)
    }
}

/// When a step ran on the real clock, measured from the start of the test.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct RealSpan {
    /// When it began.
    pub start: Duration,
    /// When it ended.
    pub end: Duration,
}

/// A step's real timing, kept in `real.json`, which comparisons skip.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct RealTiming {
    /// The step.
    pub step: StepIndex,
    /// When it began, since the start of the test.
    pub real_start: Duration,
    /// When it ended, since the start of the test.
    pub real_end: Duration,
}

/// Everything in `real.json`.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct RealTimings {
    /// The wall-clock time the test started, since the Unix epoch.
    pub wall_clock_start: Option<Duration>,
    /// One per step, in step order.
    pub steps: Vec<RealTiming>,
}

#[cfg(test)]
mod tests {
    use super::*;

    struct Button;

    impl CanonicalSelector for Button {
        fn canonical(&self) -> String {
            "role=button[name=\"Save\"]".to_owned()
        }
    }

    #[test]
    fn selector_text_comes_from_a_selector() {
        assert_eq!(
            SelectorText::of(&Button).as_str(),
            "role=button[name=\"Save\"]"
        );
    }

    #[test]
    fn locations_come_from_the_caller() {
        let location = SourceLocation::from(std::panic::Location::caller());
        assert!(location.file.ends_with("step.rs"));
        assert!(location.line > 0);
    }

    #[test]
    fn only_passed_is_not_a_failure() {
        assert!(!StepOutcome::Passed.is_failure());
        let message = String::new();
        assert!(
            StepOutcome::Failed {
                message: message.clone()
            }
            .is_failure()
        );
        assert!(StepOutcome::Panicked { message }.is_failure());
    }
}