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