Skip to main content

icedwright_trace/
step.rs

1//! The records a trace holds: one [`Step`] per call the test made on the harness.
2
3use std::borrow::Cow;
4use std::time::Duration;
5
6use icedwright_types::{Point, VirtualDuration};
7use serde::{Deserialize, Serialize};
8
9use crate::blob::{BlobRef, Png, Yaml};
10use crate::ids::{StepIndex, SubscriptionOrdinal, TaskOrdinal, WindowOrdinal};
11
12/// One call the test made on the harness: an action, an `expect`, a clock advance, a task
13/// release or a window change. Times are measured from boot.
14#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
15pub struct Step {
16    /// Its position in the trace.
17    pub index: StepIndex,
18    /// What the test asked for.
19    pub kind: StepKind,
20    /// The line of the test that made the call.
21    pub location: SourceLocation,
22    /// When the step began.
23    pub virtual_start: VirtualDuration,
24    /// When it ended.
25    pub virtual_end: VirtualDuration,
26    /// The input events delivered during the step.
27    pub events: Vec<TraceEvent>,
28    /// The messages produced during the step.
29    pub messages: Vec<TraceMessage>,
30    /// Task lifecycle changes during the step.
31    pub tasks: Vec<TraceTask>,
32    /// A unified diff of the state's `Debug` text, when the test asked for state tracing.
33    pub state_diff: Option<String>,
34    /// Each evaluation of an `expect`.
35    pub attempts: Vec<Attempt>,
36    /// The tree before the step, which is the previous step's tree after.
37    pub tree_before: BlobRef<Yaml>,
38    /// The tree once the step settled.
39    pub tree_after: BlobRef<Yaml>,
40    /// The frame before the step, unless the frame policy or the size cap left it out.
41    pub frame_before: Option<BlobRef<Png>>,
42    /// The frame once the step settled, unless the frame policy or the size cap left it out.
43    pub frame_after: Option<BlobRef<Png>>,
44    /// How it ended.
45    pub outcome: StepOutcome,
46}
47
48/// What the test asked for in a step. Action, assertion, task control and window change kinds
49/// are stored by name.
50#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
51#[serde(rename_all = "snake_case")]
52#[non_exhaustive]
53pub enum StepKind {
54    /// An action on a widget, or on a point.
55    Action {
56        /// The action's name, such as `click`.
57        action: String,
58        /// The locator acted on.
59        locator: Option<SelectorText>,
60        /// The node it resolved to, printed.
61        resolved: Option<String>,
62        /// The point acted on, in logical pixels.
63        point: Option<Point>,
64    },
65    /// An `expect`, with every attempt in [`Step::attempts`].
66    Expect {
67        /// The locator under test.
68        subject: SelectorText,
69        /// The assertion's name, such as `to_be_visible`.
70        assertion: String,
71        /// Whether it was negated with `not()`.
72        negated: bool,
73    },
74    /// An explicit advance of the virtual clock.
75    Advance {
76        /// How far.
77        by: VirtualDuration,
78    },
79    /// Control of a named task.
80    Task {
81        /// The task's name.
82        name: String,
83        /// The control's name, such as `release`.
84        control: String,
85    },
86    /// A change to a window, such as a resize.
87    Window {
88        /// The window.
89        window: WindowOrdinal,
90        /// The change's name.
91        change: String,
92    },
93}
94
95impl StepKind {
96    /// Whether this is an action, which [`FramePolicy::ActionsOnly`](crate::FramePolicy) keeps
97    /// frames for.
98    #[must_use]
99    pub fn is_action(&self) -> bool {
100        matches!(self, StepKind::Action { .. })
101    }
102}
103
104/// Implemented by a locator, whose canonical printed form always parses back to it.
105pub trait CanonicalSelector {
106    /// The selector in its canonical printed form.
107    fn canonical(&self) -> String;
108}
109
110/// A selector in its canonical printed form. It is made only from a [`CanonicalSelector`],
111/// so it always parses.
112#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
113#[serde(transparent)]
114pub struct SelectorText(String);
115
116impl SelectorText {
117    /// The canonical text of `selector`.
118    #[must_use]
119    pub fn of(selector: &impl CanonicalSelector) -> Self {
120        Self(selector.canonical())
121    }
122
123    /// The text.
124    #[must_use]
125    pub fn as_str(&self) -> &str {
126        &self.0
127    }
128}
129
130/// A place in the test's source.
131#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
132pub struct SourceLocation {
133    /// The file, as `file!()` prints it.
134    pub file: String,
135    /// The one-based line.
136    pub line: u32,
137    /// The one-based column.
138    pub column: u32,
139}
140
141impl From<&std::panic::Location<'_>> for SourceLocation {
142    fn from(location: &std::panic::Location<'_>) -> Self {
143        Self {
144            file: location.file().to_owned(),
145            line: location.line(),
146            column: location.column(),
147        }
148    }
149}
150
151/// Whether a widget captured an input event, as iced's `event::Status` reports it.
152#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
153#[serde(rename_all = "snake_case")]
154pub enum Captured {
155    /// No widget handled the event.
156    Ignored,
157    /// A widget handled the event.
158    Captured,
159}
160
161/// An input event the harness delivered, with its window renumbered.
162#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
163pub struct TraceEvent {
164    /// When it was delivered.
165    pub at: VirtualDuration,
166    /// The window it went to.
167    pub window: WindowOrdinal,
168    /// The event in the remote protocol's structured form, as JSON text.
169    pub event: String,
170    /// Whether a widget captured it.
171    pub status: Captured,
172}
173
174/// A message, as its normalised `Debug` text.
175#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
176pub struct TraceMessage {
177    /// When it was produced.
178    pub at: VirtualDuration,
179    /// Its `Debug` text, with instants rewritten as offsets from boot and cut to 4 KiB.
180    pub debug: String,
181    /// The length of the `Debug` text before it was cut; set by the writer.
182    pub full_len: Option<u64>,
183    /// The variant name from `#[derive(Messages)]`, when the message type has it.
184    pub variant: Option<Cow<'static, str>>,
185    /// What produced it.
186    pub origin: TraceOrigin,
187}
188
189/// What produced a message.
190#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
191#[serde(rename_all = "snake_case")]
192pub enum TraceOrigin {
193    /// A widget, from the event at this position in the step's events.
194    Widget {
195        /// The event's position in [`Step::events`].
196        event: u32,
197    },
198    /// A task.
199    Task(TaskOrdinal),
200    /// A subscription.
201    Subscription(SubscriptionOrdinal),
202}
203
204/// A change in a task's life.
205#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
206pub struct TraceTask {
207    /// The task.
208    pub id: TaskOrdinal,
209    /// Its name, for named tasks.
210    pub name: Option<String>,
211    /// When the change happened.
212    pub at: VirtualDuration,
213    /// What changed.
214    pub change: TraceTaskChange,
215}
216
217/// What happened to a task.
218#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
219#[serde(rename_all = "snake_case")]
220#[non_exhaustive]
221pub enum TraceTaskChange {
222    /// It started, from the message at this position in the step's messages if any.
223    Spawned {
224        /// The message's position in [`Step::messages`].
225        by_message: Option<u32>,
226    },
227    /// The test held it.
228    Held,
229    /// The test released it.
230    Released,
231    /// The test resolved it with a value.
232    Resolved,
233    /// A newer task with the same name replaced it.
234    Replaced,
235    /// It finished.
236    Finished,
237    /// It failed.
238    Failed {
239        /// The error, printed.
240        error: String,
241    },
242    /// It was aborted.
243    Aborted,
244}
245
246/// One evaluation of an `expect`.
247#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
248pub struct Attempt {
249    /// When it was evaluated.
250    pub at: VirtualDuration,
251    /// How many nodes matched.
252    pub matched: u32,
253    /// The nearest-match text.
254    pub detail: String,
255}
256
257/// How a step ended.
258#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
259#[serde(rename_all = "snake_case")]
260pub enum StepOutcome {
261    /// It did what was asked.
262    Passed,
263    /// It returned an error.
264    Failed {
265        /// The error, printed.
266        message: String,
267    },
268    /// The app or the test panicked during it.
269    Panicked {
270        /// The panic message.
271        message: String,
272    },
273}
274
275impl StepOutcome {
276    /// Whether the step failed or panicked.
277    #[must_use]
278    pub fn is_failure(&self) -> bool {
279        !matches!(self, StepOutcome::Passed)
280    }
281}
282
283/// When a step ran on the real clock, measured from the start of the test.
284#[derive(Debug, Clone, Copy, PartialEq, Eq)]
285pub struct RealSpan {
286    /// When it began.
287    pub start: Duration,
288    /// When it ended.
289    pub end: Duration,
290}
291
292/// A step's real timing, kept in `real.json`, which comparisons skip.
293#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
294pub struct RealTiming {
295    /// The step.
296    pub step: StepIndex,
297    /// When it began, since the start of the test.
298    pub real_start: Duration,
299    /// When it ended, since the start of the test.
300    pub real_end: Duration,
301}
302
303/// Everything in `real.json`.
304#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
305pub struct RealTimings {
306    /// The wall-clock time the test started, since the Unix epoch.
307    pub wall_clock_start: Option<Duration>,
308    /// One per step, in step order.
309    pub steps: Vec<RealTiming>,
310}
311
312#[cfg(test)]
313mod tests {
314    use super::*;
315
316    struct Button;
317
318    impl CanonicalSelector for Button {
319        fn canonical(&self) -> String {
320            "role=button[name=\"Save\"]".to_owned()
321        }
322    }
323
324    #[test]
325    fn selector_text_comes_from_a_selector() {
326        assert_eq!(
327            SelectorText::of(&Button).as_str(),
328            "role=button[name=\"Save\"]"
329        );
330    }
331
332    #[test]
333    fn locations_come_from_the_caller() {
334        let location = SourceLocation::from(std::panic::Location::caller());
335        assert!(location.file.ends_with("step.rs"));
336        assert!(location.line > 0);
337    }
338
339    #[test]
340    fn only_passed_is_not_a_failure() {
341        assert!(!StepOutcome::Passed.is_failure());
342        let message = String::new();
343        assert!(
344            StepOutcome::Failed {
345                message: message.clone()
346            }
347            .is_failure()
348        );
349        assert!(StepOutcome::Panicked { message }.is_failure());
350    }
351}