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
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
//! [`HarnessConfig`], the typed configuration of one harness, and the few environment variables
//! that override it, parsed once per process.

use std::collections::BTreeMap;
use std::fmt;
use std::path::PathBuf;
use std::sync::{Arc, OnceLock};
use std::time::{Duration, Instant, SystemTime};

use iced_core::theme;
use icedwright_trace::{TraceConfig, TraceError, TraceMode};
use icedwright_types::units::{Logical, ScaleFactor};
use icedwright_types::{Size, VirtualDuration};

use crate::effects::{ExternalSource, TaskRules};
use crate::error::ConfigError;
use crate::fakes::FakeClipboard;
use crate::harness::{Harness, TestProgram};
use crate::headed::{Headed, HeadedLink};
use crate::observer::StepObserver;

/// How long nothing may progress, in real time, before a step fails as hung.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum HangAfter {
    /// After this long with no progress.
    After(Duration),
    /// Never; for debugger sessions.
    Off,
}

impl Default for HangAfter {
    fn default() -> Self {
        Self::After(Duration::from_secs(120))
    }
}

/// The real clock, injected so the hang detector can be tested. Nothing virtual reads it.
#[cfg_attr(test, mockall::automock)]
pub trait RealClock: Send + Sync {
    /// The current real instant.
    fn now(&self) -> Instant;
}

/// The process's monotonic clock.
#[derive(Debug, Clone, Copy, Default)]
pub struct SystemClock;

impl RealClock for SystemClock {
    #[expect(
        clippy::disallowed_methods,
        reason = "the hang detector is the one place that measures real time"
    )]
    fn now(&self) -> Instant {
        Instant::now()
    }
}

/// Platform quirks the fakes follow.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[non_exhaustive]
pub enum Platform {
    /// X11, where winit delivers file drops.
    #[default]
    X11,
    /// Wayland, where winit does not deliver file drops.
    Wayland,
}

/// When the harness draws.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[non_exhaustive]
pub enum Draw {
    /// Only when a render, a trace frame or a screenshot asks.
    #[default]
    OnDemand,
    /// After every frame, so a widget that panics in `draw` is caught at once.
    EveryFrame,
}

/// Everything a harness needs before `boot` runs. Built with one method per field, each taking
/// `self` and returning `Self`.
#[must_use]
pub struct HarnessConfig<P: TestProgram> {
    /// Overrides `Program::window().size` for the main window.
    pub size: Option<Logical<Size>>,
    /// The system scale factor, multiplied by `Program::scale_factor`.
    pub scale_factor: ScaleFactor,
    /// The largest scale factor a widget may float at, for click placement.
    pub max_widget_scale: ScaleFactor,
    /// The system theme at boot.
    pub system_theme: theme::Mode,
    /// What `window::monitor_size` answers.
    pub monitor_size: Logical<Size>,
    /// The wall-clock time at boot.
    pub wall_clock_start: SystemTime,
    /// The virtual time between frames.
    pub frame_interval: VirtualDuration,
    /// How long waits wait by default, in virtual time.
    pub default_timeout: VirtualDuration,
    /// The hang detector's window.
    pub hang_after: HangAfter,
    /// The real clock the hang detector reads.
    pub real_clock: Arc<dyn RealClock>,
    /// Platform quirks.
    pub platform: Platform,
    /// A `Program::presets()` entry to boot from instead of `boot`.
    pub preset: Option<&'static str>,
    /// When to draw.
    pub draw: Draw,
    /// Task rules in place before boot.
    pub tasks: TaskRules<P>,
    /// Declared external sources.
    pub external_sources: Vec<ExternalSource>,
    /// The clipboard at boot.
    pub clipboard: FakeClipboard,
    /// Tracing.
    pub trace: TraceConfig,
    /// Overrides the output directory, `target/icedwright` by default.
    pub out_dir: Option<PathBuf>,
    /// The theme, size and scale combination the test runs in, which snapshot names carry.
    pub variant: crate::snapshot::Variant,
    /// Keeps the machine's fonts instead of only the bundled set. Needs a process per test,
    /// and marks every visual snapshot in the process as unreliable.
    pub system_fonts: bool,
    /// Called as the harness runs, in the order given.
    pub observers: Vec<Box<dyn StepObserver<P>>>,
    /// Whether the test streams its steps to studio.
    pub headed: Headed,
    /// How long studio shows each headed frame before acknowledging it.
    pub slow_mo: Option<Duration>,
    /// Studio's headed socket, `$XDG_RUNTIME_DIR/icedwright/studio.sock` by default.
    pub headed_socket: Option<PathBuf>,
    /// A connection to studio to use instead of the socket.
    pub headed_link: Option<Box<dyn HeadedLink>>,
}

/// 2026-01-01T00:00:00Z.
const WALL_CLOCK_START: Duration = Duration::from_secs(1_767_225_600);

impl<P: TestProgram> Default for HarnessConfig<P> {
    fn default() -> Self {
        Self {
            size: None,
            scale_factor: ScaleFactor::ONE,
            max_widget_scale: ScaleFactor::ONE,
            system_theme: theme::Mode::Light,
            monitor_size: Logical(Size::new(1920.0, 1080.0)),
            wall_clock_start: SystemTime::UNIX_EPOCH + WALL_CLOCK_START,
            frame_interval: VirtualDuration::from_micros(16_667),
            default_timeout: VirtualDuration::from_secs(5),
            hang_after: HangAfter::default(),
            real_clock: Arc::new(SystemClock),
            platform: Platform::default(),
            preset: None,
            draw: Draw::default(),
            tasks: TaskRules::default(),
            external_sources: Vec::new(),
            clipboard: FakeClipboard::default(),
            trace: TraceConfig::default(),
            out_dir: None,
            variant: crate::snapshot::Variant::new(),
            system_fonts: false,
            observers: Vec::new(),
            headed: Headed::Off,
            slow_mo: None,
            headed_socket: None,
            headed_link: None,
        }
    }
}

impl<P: TestProgram> fmt::Debug for HarnessConfig<P> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("HarnessConfig")
            .field("size", &self.size)
            .field("scale_factor", &self.scale_factor)
            .field("system_theme", &self.system_theme)
            .field("frame_interval", &self.frame_interval)
            .field("default_timeout", &self.default_timeout)
            .field("hang_after", &self.hang_after)
            .field("platform", &self.platform)
            .field("preset", &self.preset)
            .field("draw", &self.draw)
            .field("tasks", &self.tasks)
            .field("external_sources", &self.external_sources)
            .field("clipboard", &self.clipboard)
            .field("trace", &self.trace)
            .field("out_dir", &self.out_dir)
            .field("variant", &self.variant)
            .field("observers", &self.observers.len())
            .field("headed", &self.headed)
            .field("slow_mo", &self.slow_mo)
            .field("headed_socket", &self.headed_socket)
            .finish_non_exhaustive()
    }
}

/// Generates the setters shared by [`HarnessConfig`] and [`HarnessBuilder`].
macro_rules! setters {
    ($target:ident . $($path:ident).*) => {
        /// The main window's logical size.
        pub fn size(mut self, size: impl Into<Logical<Size>>) -> Self {
            self.$($path.)*size = Some(size.into());
            self
        }

        /// The system scale factor.
        pub fn scale_factor(mut self, factor: ScaleFactor) -> Self {
            self.$($path.)*scale_factor = factor;
            self
        }

        /// The largest scale factor a widget may float at.
        pub fn max_widget_scale(mut self, factor: ScaleFactor) -> Self {
            self.$($path.)*max_widget_scale = factor;
            self
        }

        /// The system theme at boot.
        pub fn system_theme(mut self, mode: theme::Mode) -> Self {
            self.$($path.)*system_theme = mode;
            self
        }

        /// What `window::monitor_size` answers.
        pub fn monitor_size(mut self, size: impl Into<Logical<Size>>) -> Self {
            self.$($path.)*monitor_size = size.into();
            self
        }

        /// The wall-clock time at boot.
        pub fn wall_clock_start(mut self, start: SystemTime) -> Self {
            self.$($path.)*wall_clock_start = start;
            self
        }

        /// The virtual time between frames.
        pub fn frame_interval(mut self, interval: impl Into<VirtualDuration>) -> Self {
            self.$($path.)*frame_interval = interval.into();
            self
        }

        /// How long waits wait by default.
        pub fn default_timeout(mut self, timeout: impl Into<VirtualDuration>) -> Self {
            self.$($path.)*default_timeout = timeout.into();
            self
        }

        /// The hang detector's window.
        pub fn hang_after(mut self, after: HangAfter) -> Self {
            self.$($path.)*hang_after = after;
            self
        }

        /// The real clock the hang detector reads.
        pub fn real_clock(mut self, clock: Arc<dyn RealClock>) -> Self {
            self.$($path.)*real_clock = clock;
            self
        }

        /// Platform quirks.
        pub fn platform(mut self, platform: Platform) -> Self {
            self.$($path.)*platform = platform;
            self
        }

        /// Boots from the named preset.
        pub fn preset(mut self, name: &'static str) -> Self {
            self.$($path.)*preset = Some(name);
            self
        }

        /// When to draw.
        pub fn draw(mut self, draw: Draw) -> Self {
            self.$($path.)*draw = draw;
            self
        }

        /// Adds task rules that apply from boot.
        pub fn tasks(mut self, rules: impl FnOnce(&mut TaskRules<P>)) -> Self {
            rules(&mut self.$($path.)*tasks);
            self
        }

        /// Declares an external source.
        pub fn external_source(mut self, source: ExternalSource) -> Self {
            self.$($path.)*external_sources.push(source);
            self
        }

        /// The clipboard at boot.
        pub fn clipboard(mut self, clipboard: FakeClipboard) -> Self {
            self.$($path.)*clipboard = clipboard;
            self
        }

        /// Tracing.
        pub fn trace(mut self, trace: TraceConfig) -> Self {
            self.$($path.)*trace = trace;
            self
        }

        /// The output directory.
        pub fn out_dir(mut self, dir: impl Into<PathBuf>) -> Self {
            self.$($path.)*out_dir = Some(dir.into());
            self
        }

        /// Keeps the machine's fonts. Needs a process per test, and every visual snapshot's
        /// report then says it may differ between machines.
        pub fn system_fonts(mut self, on: bool) -> Self {
            self.$($path.)*system_fonts = on;
            self
        }

        /// Adds an observer, called after those added before it.
        pub fn observer(mut self, observer: impl StepObserver<P> + 'static) -> Self {
            self.$($path.)*observers.push(Box::new(observer));
            self
        }

        /// Streams the test's steps to studio as it runs.
        pub fn headed(mut self, headed: Headed) -> Self {
            self.$($path.)*headed = headed;
            self
        }

        /// How long studio shows each headed frame. Virtual time is unaffected.
        pub fn slow_mo(mut self, each: Duration) -> Self {
            self.$($path.)*slow_mo = Some(each);
            self
        }

        /// Studio's headed socket.
        pub fn headed_socket(mut self, path: impl Into<PathBuf>) -> Self {
            self.$($path.)*headed_socket = Some(path.into());
            self
        }

        /// Talks to studio over `link` instead of the socket.
        pub fn headed_link(mut self, link: impl HeadedLink + 'static) -> Self {
            self.$($path.)*headed_link = Some(Box::new(link));
            self
        }

        /// Runs in a theme, size and scale combination, applying each axis it varies.
        pub fn variant(mut self, variant: crate::snapshot::Variant) -> Self {
            variant.configure(
                &mut self.$($path.)*system_theme,
                &mut self.$($path.)*size,
                &mut self.$($path.)*scale_factor,
            );
            self.$($path.)*variant = variant;
            self
        }
    };
}

impl<P: TestProgram> HarnessConfig<P> {
    setters!(self.);
}

/// A program and its [`HarnessConfig`], with the same setters and [`build`](Self::build).
#[must_use]
pub struct HarnessBuilder<P: TestProgram> {
    program: P,
    config: HarnessConfig<P>,
}

impl<P: TestProgram> fmt::Debug for HarnessBuilder<P> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("HarnessBuilder")
            .field("config", &self.config)
            .finish_non_exhaustive()
    }
}

impl<P: TestProgram> HarnessBuilder<P> {
    pub(crate) fn new(program: P) -> Self {
        Self {
            program,
            config: HarnessConfig::default(),
        }
    }

    setters!(self.config);

    /// Boots the harness.
    pub fn build(self) -> crate::Result<Harness<P>> {
        Harness::with_config(self.program, self.config)
    }
}

/// The environment variables icedwright documents. Others owned by later parts are accepted
/// here so they do not warn.
const KNOWN: &[&str] = &[
    OUT_DIR,
    WATCHDOG,
    TRACE,
    TRACE_DIR,
    TRACE_MAX_MB,
    HEADED,
    SLOW_MO,
    "ICEDWRIGHT_STUDIO",
    "ICEDWRIGHT_SCREENSHOTS",
    "ICEDWRIGHT_UPDATE",
    "ICEDWRIGHT_SEED",
    "ICEDWRIGHT_COVERAGE",
    "ICEDWRIGHT_REMOTE",
];

const OUT_DIR: &str = "ICEDWRIGHT_OUT_DIR";
const WATCHDOG: &str = "ICEDWRIGHT_WATCHDOG";
const TRACE: &str = "ICEDWRIGHT_TRACE";
const TRACE_DIR: &str = "ICEDWRIGHT_TRACE_DIR";
const TRACE_MAX_MB: &str = "ICEDWRIGHT_TRACE_MAX_MB";
const HEADED: &str = "ICEDWRIGHT_HEADED";
const SLOW_MO: &str = "ICEDWRIGHT_SLOW_MO";

/// The environment's overrides, parsed once into the configuration's own types.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct EnvOverrides {
    /// `ICEDWRIGHT_OUT_DIR`.
    pub out_dir: Option<PathBuf>,
    /// `ICEDWRIGHT_WATCHDOG`.
    pub hang_after: Option<HangAfter>,
    /// `ICEDWRIGHT_TRACE`.
    pub trace: Option<TraceMode>,
    /// `ICEDWRIGHT_TRACE_DIR`.
    pub trace_dir: Option<PathBuf>,
    /// `ICEDWRIGHT_TRACE_MAX_MB`, in MiB.
    pub trace_max_mb: Option<u64>,
    /// `ICEDWRIGHT_HEADED`.
    pub headed: Option<Headed>,
    /// `ICEDWRIGHT_SLOW_MO`.
    pub slow_mo: Option<Duration>,
    /// Whether `CI` is set, which turns headed mode off.
    pub ci: bool,
    /// `XDG_RUNTIME_DIR`, where studio's headed socket lives.
    pub runtime_dir: Option<PathBuf>,
    /// `ICEDWRIGHT_` variables that icedwright does not know, which are ignored.
    pub unknown: Vec<String>,
}

impl EnvOverrides {
    /// Parses the process environment, once per process.
    pub fn from_env() -> Result<&'static EnvOverrides, ConfigError> {
        static PARSED: OnceLock<Result<EnvOverrides, ConfigError>> = OnceLock::new();
        PARSED
            .get_or_init(|| Self::from_vars(std::env::vars()))
            .as_ref()
            .map_err(Clone::clone)
    }

    /// Parses the `ICEDWRIGHT_` variables among `vars`, and `CI` and `XDG_RUNTIME_DIR`.
    pub fn from_vars(
        vars: impl IntoIterator<Item = (String, String)>,
    ) -> Result<Self, ConfigError> {
        let mut ci = false;
        let mut runtime_dir = None;
        let vars: BTreeMap<String, String> = vars
            .into_iter()
            .filter(|(name, value)| match name.as_str() {
                "CI" => {
                    ci = !value.is_empty();
                    false
                }
                "XDG_RUNTIME_DIR" => {
                    runtime_dir = (!value.is_empty()).then(|| PathBuf::from(value));
                    false
                }
                name => name.starts_with("ICEDWRIGHT_"),
            })
            .collect();
        let get = |name: &str| vars.get(name).cloned();
        let mut overrides = EnvOverrides {
            unknown: vars
                .keys()
                .filter(|name| !KNOWN.contains(&name.as_str()))
                .cloned()
                .collect(),
            ci,
            runtime_dir,
            ..EnvOverrides::default()
        };
        if let Some(value) = get(HEADED) {
            overrides.headed = Some(Headed::parse(&value).ok_or_else(|| {
                ConfigError::invalid(HEADED, value, "1 or on to watch, step to pause, or off")
            })?);
        }
        if let Some(value) = get(SLOW_MO) {
            overrides.slow_mo =
                Some(parse_duration(&value).ok_or_else(|| {
                    ConfigError::invalid(SLOW_MO, value, "a duration such as 250ms")
                })?);
        }
        let trace = TraceConfig::new()
            .from_env(&|name: &str| get(name))
            .map_err(|error| match error {
                TraceError::BadEnv {
                    var,
                    value,
                    expected,
                } => ConfigError::invalid(var, value, expected),
                other => ConfigError::invalid(TRACE, other.to_string(), "a valid trace setting"),
            })?;
        if get(TRACE).is_some() {
            overrides.trace = Some(trace.trace_mode());
        }
        if get(OUT_DIR).is_some() {
            overrides.out_dir = Some(trace.output_dir().to_path_buf());
        }
        if get(TRACE_MAX_MB).is_some() {
            overrides.trace_max_mb = Some(trace.size_cap().get() / (1024 * 1024));
        }
        if let Some(value) = get(TRACE_DIR) {
            if value.is_empty() {
                return Err(ConfigError::invalid(TRACE_DIR, value, "a directory path"));
            }
            overrides.trace_dir = Some(PathBuf::from(value));
        }
        if let Some(value) = get(WATCHDOG) {
            overrides.hang_after = Some(parse_hang_after(&value)?);
        }
        Ok(overrides)
    }

    /// Applies the overrides to a configuration.
    pub(crate) fn apply<P: TestProgram>(&self, config: &mut HarnessConfig<P>) {
        if let Some(after) = self.hang_after {
            config.hang_after = after;
        }
        if let Some(dir) = &self.out_dir {
            config.out_dir = Some(dir.clone());
        }
        let mut trace = config.trace.clone();
        if let Some(mode) = self.trace {
            trace = trace.mode(mode);
        }
        if let Some(mb) = self.trace_max_mb {
            trace = trace.max_size(icedwright_trace::ByteSize::mib(mb));
        }
        if let Some(dir) = &config.out_dir {
            trace = trace.out_dir(dir.clone());
        }
        config.trace = trace;
        if let Some(headed) = self.headed {
            config.headed = headed;
        }
        if let Some(each) = self.slow_mo {
            config.slow_mo = Some(each);
        }
        // A socket or link named in code is the test's own peer, so CI keeps it.
        let named_peer = config.headed_socket.is_some() || config.headed_link.is_some();
        if config.headed_socket.is_none() {
            config.headed_socket = self.runtime_dir.as_deref().map(crate::headed::socket_in);
        }
        if self.ci && config.headed != Headed::Off && !named_peer {
            static WARNED: std::sync::Once = std::sync::Once::new();
            WARNED.call_once(|| {
                eprintln!("icedwright: CI is set, so headed mode is off; nobody is watching");
            });
            config.headed = Headed::Off;
        }
    }
}

fn parse_hang_after(value: &str) -> Result<HangAfter, ConfigError> {
    const EXPECTED: &str = "a duration such as 120s or 500ms, or off";
    if value == "off" {
        return Ok(HangAfter::Off);
    }
    parse_duration(value)
        .filter(|duration| !duration.is_zero())
        .map(HangAfter::After)
        .ok_or_else(|| ConfigError::invalid(WATCHDOG, value, EXPECTED))
}

/// Reads `250ms`, `120s` or `2m`.
pub(crate) fn parse_duration(value: &str) -> Option<Duration> {
    let value = value.trim();
    let split = value.find(|c: char| !c.is_ascii_digit())?;
    let (number, unit) = value.split_at(split);
    let number: u64 = number.parse().ok()?;
    match unit {
        "ms" => Some(Duration::from_millis(number)),
        "s" => Some(Duration::from_secs(number)),
        "m" => Some(Duration::from_secs(number.checked_mul(60)?)),
        _ => None,
    }
}

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

    fn vars(pairs: &[(&str, &str)]) -> Vec<(String, String)> {
        pairs
            .iter()
            .map(|(k, v)| ((*k).to_owned(), (*v).to_owned()))
            .collect()
    }

    #[test]
    fn every_documented_variable_parses_into_its_type() {
        let parsed = EnvOverrides::from_vars(vars(&[
            ("ICEDWRIGHT_OUT_DIR", "/tmp/out"),
            ("ICEDWRIGHT_WATCHDOG", "1s"),
            ("ICEDWRIGHT_TRACE", "always"),
            ("ICEDWRIGHT_TRACE_DIR", "/tmp/traces"),
            ("ICEDWRIGHT_TRACE_MAX_MB", "8"),
            ("PATH", "/usr/bin"),
        ]))
        .unwrap();
        assert_eq!(parsed.out_dir, Some(PathBuf::from("/tmp/out")));
        assert_eq!(
            parsed.hang_after,
            Some(HangAfter::After(Duration::from_secs(1)))
        );
        assert_eq!(parsed.trace, Some(TraceMode::Always));
        assert_eq!(parsed.trace_dir, Some(PathBuf::from("/tmp/traces")));
        assert_eq!(parsed.trace_max_mb, Some(8));
        assert!(parsed.unknown.is_empty());
    }

    #[test]
    fn headed_mode_comes_from_the_environment_and_ci_turns_it_off() {
        let parsed = EnvOverrides::from_vars(vars(&[
            ("ICEDWRIGHT_HEADED", "step"),
            ("ICEDWRIGHT_SLOW_MO", "250ms"),
            ("XDG_RUNTIME_DIR", "/run/user/1000"),
        ]))
        .unwrap();
        assert_eq!(parsed.headed, Some(Headed::Step));
        assert_eq!(parsed.slow_mo, Some(Duration::from_millis(250)));
        assert!(parsed.unknown.is_empty());
        let config = applied(&probe(), &parsed);
        assert_eq!(config.headed, Headed::Step);
        assert_eq!(config.slow_mo, Some(Duration::from_millis(250)));
        assert_eq!(
            config.headed_socket,
            Some(PathBuf::from("/run/user/1000/icedwright/studio.sock"))
        );

        let on_ci =
            EnvOverrides::from_vars(vars(&[("ICEDWRIGHT_HEADED", "1"), ("CI", "true")])).unwrap();
        assert!(on_ci.ci);
        assert_eq!(applied(&probe(), &on_ci).headed, Headed::Off);
        let on_ci_with_runtime_dir = EnvOverrides::from_vars(vars(&[
            ("ICEDWRIGHT_HEADED", "1"),
            ("CI", "true"),
            ("XDG_RUNTIME_DIR", "/run/user/1000"),
        ]))
        .unwrap();
        assert_eq!(
            applied(&probe(), &on_ci_with_runtime_dir).headed,
            Headed::Off,
            "CI turns off headed mode that would reach for studio's default socket"
        );

        let mut named = applied(&probe(), &EnvOverrides::default());
        named.headed = Headed::Step;
        named.headed_socket = Some(PathBuf::from("/tmp/stand-in.sock"));
        on_ci.apply(&mut named);
        assert_eq!(
            named.headed,
            Headed::Watch,
            "a socket the test names is its own peer, so CI keeps it"
        );

        for (var, value) in [
            ("ICEDWRIGHT_HEADED", "maybe"),
            ("ICEDWRIGHT_SLOW_MO", "slow"),
        ] {
            let error = EnvOverrides::from_vars(vars(&[(var, value)])).unwrap_err();
            assert!(error.to_string().contains(var), "{error}");
        }
    }

    fn view(_: &u8) -> iced::Element<'_, ()> {
        iced::widget::text("probe").into()
    }

    fn probe() -> impl TestProgram {
        iced::application(u8::default, |_: &mut u8, (): ()| {}, view)
    }

    fn applied<P: TestProgram>(_: &P, env: &EnvOverrides) -> HarnessConfig<P> {
        let mut config = HarnessConfig::default();
        env.apply(&mut config);
        config
    }

    #[test]
    fn nothing_set_overrides_nothing() {
        assert_eq!(
            EnvOverrides::from_vars(Vec::new()).unwrap(),
            EnvOverrides::default()
        );
    }

    #[test]
    fn the_watchdog_takes_off_and_durations() {
        assert_eq!(parse_hang_after("off").unwrap(), HangAfter::Off);
        assert_eq!(
            parse_hang_after("250ms").unwrap(),
            HangAfter::After(Duration::from_millis(250))
        );
        assert_eq!(
            parse_hang_after("2m").unwrap(),
            HangAfter::After(Duration::from_secs(120))
        );
    }

    #[test]
    fn an_unparseable_value_names_the_variable_and_the_forms() {
        for (var, value) in [
            ("ICEDWRIGHT_WATCHDOG", "soon"),
            ("ICEDWRIGHT_WATCHDOG", "0s"),
            ("ICEDWRIGHT_TRACE", "sometimes"),
            ("ICEDWRIGHT_TRACE_MAX_MB", "lots"),
            ("ICEDWRIGHT_TRACE_DIR", ""),
        ] {
            let error = EnvOverrides::from_vars(vars(&[(var, value)])).unwrap_err();
            let ConfigError::Invalid {
                var: named,
                value: held,
                ..
            } = &error;
            assert_eq!(*named, var);
            assert_eq!(held, value);
            assert!(error.to_string().contains("expected"), "{error}");
        }
    }

    #[test]
    fn an_undocumented_variable_is_listed_not_applied() {
        let parsed = EnvOverrides::from_vars(vars(&[("ICEDWRIGHT_TRACES", "always")])).unwrap();
        assert_eq!(parsed.unknown, vec!["ICEDWRIGHT_TRACES".to_owned()]);
        assert_eq!(parsed.trace, None);
    }

    #[test]
    fn durations_read_three_units() {
        assert_eq!(parse_duration("15ms"), Some(Duration::from_millis(15)));
        assert_eq!(parse_duration("3s"), Some(Duration::from_secs(3)));
        assert_eq!(parse_duration("3"), None);
        assert_eq!(parse_duration("s"), None);
        assert_eq!(parse_duration("3h"), None);
    }
}