icedwright 0.0.1

The icedwright test harness: run an iced 0.14 program headlessly on virtual time
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
//! Headed mode, the harness's side: the test keeps running headlessly on virtual time and
//! streams each step and its frame to studio's headed socket. Pacing comes from studio's
//! answers, never from a delay: after every step the harness waits for studio's `ack`, which
//! studio holds back for the slow-motion time, and in step mode it waits for `continue` or
//! `run` before every step.
//!
//! Every wait on studio for a step is bounded by the hang window: studio that stays connected
//! but answers nothing for that long fails the step with `Hung`. Only a step-mode pause waits
//! without a bound, because a person may hold it.

use std::fmt;
use std::io::ErrorKind;
use std::path::{Path, PathBuf};
use std::time::Duration;

use icedwright_protocol::{FrameKind, HEADER_LEN, WireFrame};
use icedwright_trace::Step;
use serde::{Deserialize, Serialize};

/// Whether a test shows itself in studio as it runs.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[non_exhaustive]
pub enum Headed {
    /// Headless only.
    #[default]
    Off,
    /// Streams every step to studio.
    Watch,
    /// Streams every step and waits for studio's Continue before each one.
    Step,
}

impl Headed {
    /// Reads `ICEDWRIGHT_HEADED`: `1`, `on` or `true` to watch, `step` to pause before every
    /// step, `0`, `off` or `false` for neither.
    pub(crate) fn parse(value: &str) -> Option<Self> {
        match value {
            "1" | "on" | "true" => Some(Self::Watch),
            "step" => Some(Self::Step),
            "0" | "off" | "false" => Some(Self::Off),
            _ => None,
        }
    }
}

/// The connection to studio, behind a trait so the pacing can be tested without a socket.
#[cfg_attr(test, mockall::automock)]
pub trait HeadedLink {
    /// Sends encoded frames. A send that cannot finish within the link's bound is an
    /// `ErrorKind::TimedOut` error.
    fn send(&mut self, bytes: &[u8]) -> std::io::Result<()>;
    /// Blocks until studio's next answer arrives, for at most `within` when given, and returns
    /// its JSON. Running out of time is an `ErrorKind::TimedOut` error.
    fn receive(&mut self, within: Option<Duration>) -> std::io::Result<Vec<u8>>;
}

/// Studio stayed connected but did not take or acknowledge a step within the bound.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct Stalled {
    pub(crate) after: Duration,
}

/// What the harness sends, in studio's `HeadedMessage` shape.
#[derive(Debug, Serialize)]
#[serde(tag = "type", rename_all = "snake_case")]
enum Outgoing<'a> {
    Hello {
        test: &'a str,
        step_mode: bool,
        slow_mo_ms: Option<u64>,
        scale: f32,
    },
    Paused {
        next: Option<&'a str>,
    },
    Step {
        step: &'a Step,
        frame: bool,
    },
    Finished {
        failure: Option<&'a str>,
    },
}

/// What studio answers.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
enum Reply {
    Continue,
    Run,
    Ack,
}

fn encode(message: &Outgoing<'_>, png: Option<&[u8]>) -> std::io::Result<Vec<u8>> {
    let json = serde_json::to_vec(message).map_err(std::io::Error::other)?;
    let mut bytes = WireFrame::json(json)
        .encode()
        .map_err(std::io::Error::other)?;
    if let Some(png) = png {
        let frame = WireFrame::binary(png.to_vec())
            .encode()
            .map_err(std::io::Error::other)?;
        bytes.extend(frame);
    }
    Ok(bytes)
}

/// A test's headed connection. Any failure on the link closes it with one line on stderr,
/// and the test carries on headless.
pub(crate) struct HeadedSession {
    link: Option<Box<dyn HeadedLink>>,
    step_mode: bool,
    answer_within: Option<Duration>,
}

impl fmt::Debug for HeadedSession {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("HeadedSession")
            .field("connected", &self.link.is_some())
            .field("step_mode", &self.step_mode)
            .field("answer_within", &self.answer_within)
            .finish()
    }
}

/// How a session starts.
#[derive(Debug, Clone, Copy)]
pub(crate) struct Hello<'a> {
    pub(crate) test: &'a str,
    pub(crate) mode: Headed,
    pub(crate) slow_mo: Option<Duration>,
    pub(crate) scale: f32,
    /// How long studio may take to acknowledge a step; `None` waits without a bound.
    pub(crate) answer_within: Option<Duration>,
}

/// How long studio may take to answer: the hang window, plus the slow-motion time studio
/// holds each acknowledgement back for. `None` when the hang detector is off.
pub(crate) fn answer_within(
    window: Option<Duration>,
    slow_mo: Option<Duration>,
) -> Option<Duration> {
    window.map(|window| window.saturating_add(slow_mo.unwrap_or_default()))
}

impl HeadedSession {
    /// Greets studio over `link`; `None` if the greeting fails or the mode is off.
    pub(crate) fn start(link: Box<dyn HeadedLink>, hello: Hello<'_>) -> Option<Self> {
        if hello.mode == Headed::Off {
            return None;
        }
        let mut session = Self {
            link: Some(link),
            step_mode: hello.mode == Headed::Step,
            answer_within: hello.answer_within,
        };
        let slow_mo_ms = hello
            .slow_mo
            .map(|d| u64::try_from(d.as_millis()).unwrap_or(u64::MAX));
        session.send(
            &Outgoing::Hello {
                test: hello.test,
                step_mode: session.step_mode,
                slow_mo_ms,
                scale: hello.scale,
            },
            None,
        );
        session.link.is_some().then_some(session)
    }

    pub(crate) fn connected(&self) -> bool {
        self.link.is_some()
    }

    fn close(&mut self, error: &std::io::Error) {
        if self.link.take().is_some() {
            eprintln!("icedwright: the headed link to studio closed ({error}); running headless");
        }
    }

    fn send(&mut self, message: &Outgoing<'_>, png: Option<&[u8]>) {
        let Some(link) = self.link.as_mut() else {
            return;
        };
        if let Err(error) = encode(message, png).and_then(|bytes| link.send(&bytes)) {
            self.close(&error);
        }
    }

    /// Waits for one of `wanted`, for at most `within` per answer, ignoring any other answer.
    /// `Ok(None)` when the link is already closed.
    fn wait_for(
        &mut self,
        wanted: &[Reply],
        within: Option<Duration>,
    ) -> std::io::Result<Option<Reply>> {
        loop {
            let Some(link) = self.link.as_mut() else {
                return Ok(None);
            };
            let reply = link.receive(within).and_then(|json| {
                serde_json::from_slice::<Reply>(&json).map_err(std::io::Error::other)
            })?;
            if wanted.contains(&reply) {
                return Ok(Some(reply));
            }
        }
    }

    /// In step mode, tells studio the test is paused and waits for Continue or Run. Returns
    /// whether it waited, since a person may have held the test for any length of time.
    pub(crate) fn pause(&mut self, next: Option<&str>) -> bool {
        if !self.step_mode || self.link.is_none() {
            return false;
        }
        self.send(&Outgoing::Paused { next }, None);
        match self.wait_for(&[Reply::Continue, Reply::Run], None) {
            Ok(Some(Reply::Run)) => self.step_mode = false,
            Ok(_) => {}
            Err(error) => self.close(&error),
        }
        true
    }

    /// Sends a step and its frame, then waits for studio to acknowledge it. Studio that
    /// stays connected without taking the step or answering within the bound has stalled,
    /// which closes the link and fails the step; studio going away only closes the link.
    pub(crate) fn step(&mut self, step: &Step, png: Option<&[u8]>) -> Result<(), Stalled> {
        let Some(link) = self.link.as_mut() else {
            return Ok(());
        };
        let message = Outgoing::Step {
            step,
            frame: png.is_some(),
        };
        let sent = encode(&message, png).and_then(|bytes| link.send(&bytes));
        let answered = sent.and_then(|()| self.wait_for(&[Reply::Ack], self.answer_within));
        let Err(error) = answered else {
            return Ok(());
        };
        if error.kind() != ErrorKind::TimedOut {
            self.close(&error);
            return Ok(());
        }
        self.link = None;
        Err(Stalled {
            after: self.answer_within.unwrap_or_default(),
        })
    }

    /// Tells studio the test ended.
    pub(crate) fn finish(mut self, failure: Option<&str>) {
        self.send(&Outgoing::Finished { failure }, None);
    }
}

/// Studio's headed socket under a runtime directory.
pub(crate) fn socket_in(runtime_dir: &Path) -> PathBuf {
    runtime_dir.join("icedwright").join("studio.sock")
}

/// Studio's headed socket, over a Unix stream.
#[cfg(unix)]
struct UnixLink {
    stream: std::os::unix::net::UnixStream,
}

/// A socket timeout reads as `WouldBlock` on Unix; the link reports it as `TimedOut`.
#[cfg(unix)]
fn timed_out(error: std::io::Error) -> std::io::Error {
    if error.kind() == ErrorKind::WouldBlock {
        return std::io::Error::new(ErrorKind::TimedOut, error);
    }
    error
}

#[cfg(unix)]
impl HeadedLink for UnixLink {
    fn send(&mut self, bytes: &[u8]) -> std::io::Result<()> {
        use std::io::Write as _;
        self.stream.write_all(bytes).map_err(timed_out)
    }

    fn receive(&mut self, within: Option<Duration>) -> std::io::Result<Vec<u8>> {
        use std::io::Read as _;
        self.stream.set_read_timeout(within)?;
        let mut header = [0; HEADER_LEN];
        self.stream.read_exact(&mut header).map_err(timed_out)?;
        let (kind, length) = WireFrame::decode_header(header).map_err(std::io::Error::other)?;
        let mut payload = vec![0; length];
        self.stream.read_exact(&mut payload).map_err(timed_out)?;
        if kind != FrameKind::Json {
            return Err(std::io::Error::other("studio sent a binary frame"));
        }
        Ok(payload)
    }
}

/// Connects to the socket at `path`, saying in one line why not when nothing listens. Each
/// send may take at most `send_within`.
pub(crate) fn connect(path: &Path, send_within: Option<Duration>) -> Option<Box<dyn HeadedLink>> {
    #[cfg(unix)]
    {
        let connected = std::os::unix::net::UnixStream::connect(path).and_then(|stream| {
            stream.set_write_timeout(send_within)?;
            Ok(stream)
        });
        match connected {
            Ok(stream) => Some(Box::new(UnixLink { stream })),
            Err(error) => {
                eprintln!(
                    "icedwright: headed mode found no studio on {} ({error}); start `icedwright-studio headed` first. Running headless",
                    path.display()
                );
                None
            }
        }
    }
    #[cfg(not(unix))]
    {
        let _ = send_within;
        eprintln!(
            "icedwright: headed mode needs a Unix socket, which {} is not on this platform; running headless",
            path.display()
        );
        None
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use icedwright_trace::{
        RealSpan, SourceLocation, StepKind, StepOutcome, TraceConfig, TraceMeta, TraceStart,
        TraceWriter,
    };
    use icedwright_types::{ScaleFactor, VirtualDuration};
    use mockall::Sequence;

    fn json(reply: &str) -> std::io::Result<Vec<u8>> {
        Ok(format!("{{\"type\":\"{reply}\"}}").into_bytes())
    }

    fn step() -> Step {
        let meta = TraceMeta {
            test: "t".to_owned(),
            crate_name: "c".to_owned(),
            iced_version: "0.14".to_owned(),
            windows: Vec::new(),
            theme: None,
            scale_factor: ScaleFactor::ONE,
            failure: None,
        };
        let start = TraceStart {
            boot: None,
            tree: String::new(),
            frame: None,
        };
        let mut writer = TraceWriter::new(meta, &TraceConfig::new(), start);
        let location = SourceLocation {
            file: "tests/ui.rs".to_owned(),
            line: 3,
            column: 5,
        };
        let kind = StepKind::Advance {
            by: VirtualDuration::from_secs(1),
        };
        let _ = writer
            .begin_step(kind, location, VirtualDuration::ZERO)
            .end(
                StepOutcome::Passed,
                VirtualDuration::from_secs(1),
                RealSpan {
                    start: Duration::ZERO,
                    end: Duration::ZERO,
                },
            );
        writer.last_step().cloned().unwrap()
    }

    fn hello(mode: Headed) -> Hello<'static> {
        Hello {
            test: "ui::adds",
            mode,
            slow_mo: Some(Duration::from_millis(250)),
            scale: 1.0,
            answer_within: Some(BOUND),
        }
    }

    const BOUND: Duration = Duration::from_secs(120);

    /// The JSON frames in `bytes`, decoded.
    fn messages(bytes: &[u8]) -> Vec<serde_json::Value> {
        let mut rest = bytes;
        let mut out = Vec::new();
        while let Some((frame, used)) = WireFrame::decode(rest).unwrap() {
            if frame.kind == FrameKind::Json {
                out.push(serde_json::from_slice(&frame.payload).unwrap());
            }
            rest = rest.get(used..).unwrap();
        }
        out
    }

    #[test]
    fn hello_carries_step_mode_and_slow_motion() {
        let mut link = MockHeadedLink::new();
        link.expect_send()
            .withf(|bytes| {
                let sent = messages(bytes);
                sent.len() == 1
                    && sent[0]["type"] == "hello"
                    && sent[0]["test"] == "ui::adds"
                    && sent[0]["step_mode"] == true
                    && sent[0]["slow_mo_ms"] == 250
            })
            .times(1)
            .returning(|_| Ok(()));
        let session = HeadedSession::start(Box::new(link), hello(Headed::Step));
        assert!(session.is_some_and(|s| s.connected()));
    }

    #[test]
    fn off_never_touches_the_link() {
        let link = MockHeadedLink::new();
        assert!(HeadedSession::start(Box::new(link), hello(Headed::Off)).is_none());
    }

    #[test]
    fn step_mode_waits_for_continue_and_run_ends_the_pauses() {
        let mut link = MockHeadedLink::new();
        let mut order = Sequence::new();
        link.expect_send()
            .times(1)
            .in_sequence(&mut order)
            .returning(|_| Ok(()));
        link.expect_send()
            .withf(|bytes| messages(bytes)[0]["type"] == "paused")
            .times(1)
            .in_sequence(&mut order)
            .returning(|_| Ok(()));
        link.expect_receive()
            .withf(Option::is_none)
            .times(1)
            .in_sequence(&mut order)
            .returning(|_| json("ack"));
        link.expect_receive()
            .withf(Option::is_none)
            .times(1)
            .in_sequence(&mut order)
            .returning(|_| json("continue"));
        link.expect_send()
            .withf(|bytes| messages(bytes)[0]["type"] == "paused")
            .times(1)
            .in_sequence(&mut order)
            .returning(|_| Ok(()));
        link.expect_receive()
            .withf(Option::is_none)
            .times(1)
            .in_sequence(&mut order)
            .returning(|_| json("run"));
        let mut session = HeadedSession::start(Box::new(link), hello(Headed::Step)).unwrap();
        assert!(
            session.pause(Some("tests/ui.rs:3")),
            "the first pause waits"
        );
        assert!(session.pause(None), "the second pause waits for run");
        assert!(!session.pause(None), "after run nothing pauses");
    }

    #[test]
    fn watch_mode_never_pauses() {
        let mut link = MockHeadedLink::new();
        link.expect_send().times(1).returning(|_| Ok(()));
        let mut session = HeadedSession::start(Box::new(link), hello(Headed::Watch)).unwrap();
        assert!(!session.pause(None));
    }

    #[test]
    fn a_step_and_its_frame_wait_for_the_acknowledgement() {
        let step = step();
        let mut link = MockHeadedLink::new();
        let mut order = Sequence::new();
        link.expect_send()
            .times(1)
            .in_sequence(&mut order)
            .returning(|_| Ok(()));
        link.expect_send()
            .withf(|bytes| {
                let mut kinds = Vec::new();
                let mut rest = bytes;
                while let Some((frame, used)) = WireFrame::decode(rest).unwrap() {
                    kinds.push((frame.kind, frame.payload));
                    rest = rest.get(used..).unwrap();
                }
                let [(FrameKind::Json, json), (FrameKind::Binary, png)] = kinds.as_slice() else {
                    return false;
                };
                let message: serde_json::Value = serde_json::from_slice(json).unwrap();
                message["type"] == "step" && message["frame"] == true && png == b"png"
            })
            .times(1)
            .in_sequence(&mut order)
            .returning(|_| Ok(()));
        link.expect_receive()
            .withf(|within| *within == Some(BOUND))
            .times(1)
            .in_sequence(&mut order)
            .returning(|_| json("ack"));
        let mut session = HeadedSession::start(Box::new(link), hello(Headed::Watch)).unwrap();
        assert_eq!(session.step(&step, Some(b"png")), Ok(()));
        assert!(session.connected());
    }

    #[test]
    fn studio_that_never_acknowledges_a_step_fails_it_instead_of_blocking() {
        let step = step();
        let mut link = MockHeadedLink::new();
        link.expect_send().times(2).returning(|_| Ok(()));
        link.expect_receive()
            .withf(|within| *within == Some(BOUND))
            .times(1)
            .returning(|_| Err(std::io::Error::from(ErrorKind::TimedOut)));
        let mut session = HeadedSession::start(Box::new(link), hello(Headed::Watch)).unwrap();
        assert_eq!(
            session.step(&step, None),
            Err(Stalled { after: BOUND }),
            "a stalled studio fails the step"
        );
        assert!(!session.connected(), "and nothing waits on it again");
        assert_eq!(session.step(&step, None), Ok(()));
    }

    #[test]
    fn studio_that_cannot_take_a_step_fails_it_instead_of_blocking() {
        let step = step();
        let mut link = MockHeadedLink::new();
        let mut order = Sequence::new();
        link.expect_send()
            .times(1)
            .in_sequence(&mut order)
            .returning(|_| Ok(()));
        link.expect_send()
            .times(1)
            .in_sequence(&mut order)
            .returning(|_| Err(std::io::Error::from(ErrorKind::TimedOut)));
        let mut session = HeadedSession::start(Box::new(link), hello(Headed::Watch)).unwrap();
        assert_eq!(session.step(&step, None), Err(Stalled { after: BOUND }));
        assert!(!session.connected());
    }

    #[test]
    fn the_bound_is_the_hang_window_plus_the_slow_motion_hold() {
        let window = Some(Duration::from_secs(120));
        assert_eq!(
            answer_within(window, Some(Duration::from_millis(250))),
            Some(Duration::from_millis(120_250))
        );
        assert_eq!(answer_within(window, None), window);
        assert_eq!(answer_within(None, Some(Duration::from_secs(1))), None);
    }

    #[test]
    fn a_closed_link_falls_back_to_headless() {
        let step = step();
        let mut link = MockHeadedLink::new();
        link.expect_send().times(1).returning(|_| Ok(()));
        link.expect_send()
            .times(1)
            .returning(|_| Err(std::io::Error::from(std::io::ErrorKind::BrokenPipe)));
        let mut session = HeadedSession::start(Box::new(link), hello(Headed::Step)).unwrap();
        assert_eq!(
            session.step(&step, None),
            Ok(()),
            "studio going away is not a failure"
        );
        assert!(!session.connected());
        assert!(!session.pause(None), "a closed link never pauses");
        assert_eq!(session.step(&step, None), Ok(()));
        session.finish(None);
    }

    #[test]
    fn a_failed_greeting_runs_headless() {
        let mut link = MockHeadedLink::new();
        link.expect_send()
            .returning(|_| Err(std::io::Error::from(std::io::ErrorKind::ConnectionRefused)));
        assert!(HeadedSession::start(Box::new(link), hello(Headed::Watch)).is_none());
    }

    #[test]
    fn studio_going_away_while_paused_carries_on() {
        let mut link = MockHeadedLink::new();
        link.expect_send().returning(|_| Ok(()));
        link.expect_receive()
            .times(1)
            .returning(|_| Err(std::io::Error::from(std::io::ErrorKind::UnexpectedEof)));
        let mut session = HeadedSession::start(Box::new(link), hello(Headed::Step)).unwrap();
        assert!(session.pause(None));
        assert!(!session.connected());
    }

    #[test]
    fn the_environment_names_three_modes() {
        assert_eq!(Headed::parse("1"), Some(Headed::Watch));
        assert_eq!(Headed::parse("step"), Some(Headed::Step));
        assert_eq!(Headed::parse("off"), Some(Headed::Off));
        assert_eq!(Headed::parse("sometimes"), None);
    }

    #[test]
    fn the_socket_lives_under_the_runtime_directory() {
        assert_eq!(
            socket_in(Path::new("/run/user/1000")),
            PathBuf::from("/run/user/1000/icedwright/studio.sock")
        );
    }
}