tui-test-rs 0.1.0-beta.2

In-process terminal automation, inspection, assertions, and recording
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
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
//! Terminal profiles: the settings a session runs with.
//!
//! A profile is chosen when a session opens and fixed for its lifetime. It is
//! read from a TOML file so a project can commit the terminal its tests expect,
//! rather than depending on whatever the machine happens to default to.
//!
//! # Colors are resolved here, not by the emulator
//!
//! A terminal grid stores color *indices*, not colors: a cell painted with
//! `SGR 31` records palette slot 1, and what that looks like is the viewer's
//! choice. Nothing in the emulator needs a palette — xterm.js's `theme` option
//! is inert in a headless terminal, and alacritty has no palette at all.
//!
//! tui-test has to make that choice twice: once to draw a screenshot, and once
//! to answer `expect --fg "#rrggbb"`. Those answers have to agree. They used to
//! come from two separate hardcoded tables that disagreed on all sixteen ANSI
//! slots, so `expect --fg "#800000"` passed on a cell the screenshot painted
//! `#e88388`. [`Colors`] is the single table both now read.

use std::collections::BTreeMap;
use std::path::{Path, PathBuf};

use serde::{Deserialize, Deserializer, Serialize, Serializer};

use crate::terminal::cell::NamedColor;

/// Rows of scrollback a profile retains when it does not say otherwise.
///
/// The emulators do not agree on their own defaults (alacritty 10,000,
/// xterm.js 1,000), so this is always set explicitly rather than inherited.
pub const DEFAULT_SCROLLBACK: usize = 10_000;

/// The file a profile is read from, under the config directory.
pub const CONFIG_FILE: &str = "tui-test.toml";

/// The profile used when none is named.
pub const DEFAULT_PROFILE: &str = "default";

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Rgb {
    pub r: u8,
    pub g: u8,
    pub b: u8,
}

impl Rgb {
    pub const fn new(r: u8, g: u8, b: u8) -> Self {
        Rgb { r, g, b }
    }

    pub fn to_hex(self) -> String {
        format!("#{:02x}{:02x}{:02x}", self.r, self.g, self.b)
    }

    /// Parse `#rgb` or `#rrggbb`. The leading `#` is optional so a TOML value
    /// that lost it to a stray quote still reads sensibly.
    pub fn parse(s: &str) -> Result<Self, String> {
        let trimmed = s.trim();
        let hex = trimmed.strip_prefix('#').unwrap_or(trimmed);
        let digit = |byte: u8| -> Option<u8> {
            match byte {
                b'0'..=b'9' => Some(byte - b'0'),
                b'a'..=b'f' => Some(byte - b'a' + 10),
                b'A'..=b'F' => Some(byte - b'A' + 10),
                _ => None,
            }
        };
        let digits = hex
            .bytes()
            .map(digit)
            .collect::<Option<Vec<_>>>()
            .ok_or_else(|| format!("invalid hex color {s:?}"))?;
        match digits.as_slice() {
            [r, g, b] => Ok(Rgb::new(r * 17, g * 17, b * 17)),
            [r1, r2, g1, g2, b1, b2] => Ok(Rgb::new(r1 * 16 + r2, g1 * 16 + g2, b1 * 16 + b2)),
            _ => Err(format!("color must be #rgb or #rrggbb (got {s:?})")),
        }
    }
}

impl Serialize for Rgb {
    fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
        s.serialize_str(&self.to_hex())
    }
}

impl<'de> Deserialize<'de> for Rgb {
    fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
        let raw = String::deserialize(d)?;
        Rgb::parse(&raw).map_err(serde::de::Error::custom)
    }
}

/// The colors a session paints with.
///
/// Only the sixteen ANSI slots are configurable. Indices 16-255 are the xterm
/// color cube and gray ramp, which are defined by the spec rather than by a
/// theme, so [`Colors::rgb`] computes them instead of storing them. A config
/// that could override them would let two sessions disagree about what
/// `--fg 196` means.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct Colors {
    /// The color text takes when a cell set none of its own.
    pub foreground: Rgb,
    /// The color an unpainted cell takes.
    pub background: Rgb,
    /// The color used to draw the cursor.
    pub cursor: Rgb,

    pub black: Rgb,
    pub red: Rgb,
    pub green: Rgb,
    pub yellow: Rgb,
    pub blue: Rgb,
    pub magenta: Rgb,
    pub cyan: Rgb,
    pub white: Rgb,
    pub bright_black: Rgb,
    pub bright_red: Rgb,
    pub bright_green: Rgb,
    pub bright_yellow: Rgb,
    pub bright_blue: Rgb,
    pub bright_magenta: Rgb,
    pub bright_cyan: Rgb,
    pub bright_white: Rgb,
}

impl Default for Colors {
    /// The classic VGA/xterm palette, which is what `TERM=xterm-256color`
    /// promises and what the assertion layer already compared against.
    fn default() -> Self {
        Colors {
            foreground: Rgb::new(192, 192, 192),
            background: Rgb::new(0, 0, 0),
            cursor: Rgb::new(192, 192, 192),

            black: Rgb::new(0, 0, 0),
            red: Rgb::new(128, 0, 0),
            green: Rgb::new(0, 128, 0),
            yellow: Rgb::new(128, 128, 0),
            blue: Rgb::new(0, 0, 128),
            magenta: Rgb::new(128, 0, 128),
            cyan: Rgb::new(0, 128, 128),
            white: Rgb::new(192, 192, 192),
            bright_black: Rgb::new(128, 128, 128),
            bright_red: Rgb::new(255, 0, 0),
            bright_green: Rgb::new(0, 255, 0),
            bright_yellow: Rgb::new(255, 255, 0),
            bright_blue: Rgb::new(0, 0, 255),
            bright_magenta: Rgb::new(255, 0, 255),
            bright_cyan: Rgb::new(0, 255, 255),
            bright_white: Rgb::new(255, 255, 255),
        }
    }
}

impl Colors {
    /// The sixteen ANSI slots, in palette order.
    pub fn ansi(&self) -> [Rgb; 16] {
        [
            self.black,
            self.red,
            self.green,
            self.yellow,
            self.blue,
            self.magenta,
            self.cyan,
            self.white,
            self.bright_black,
            self.bright_red,
            self.bright_green,
            self.bright_yellow,
            self.bright_blue,
            self.bright_magenta,
            self.bright_cyan,
            self.bright_white,
        ]
    }

    /// The name a slot goes by in the config file.
    pub fn slot_name(index: u8) -> Option<&'static str> {
        Some(match NamedColor::from_index(index)? {
            NamedColor::Black => "black",
            NamedColor::Red => "red",
            NamedColor::Green => "green",
            NamedColor::Yellow => "yellow",
            NamedColor::Blue => "blue",
            NamedColor::Magenta => "magenta",
            NamedColor::Cyan => "cyan",
            NamedColor::White => "white",
            NamedColor::BrightBlack => "bright_black",
            NamedColor::BrightRed => "bright_red",
            NamedColor::BrightGreen => "bright_green",
            NamedColor::BrightYellow => "bright_yellow",
            NamedColor::BrightBlue => "bright_blue",
            NamedColor::BrightMagenta => "bright_magenta",
            NamedColor::BrightCyan => "bright_cyan",
            NamedColor::BrightWhite => "bright_white",
        })
    }

    /// Set one color by the name used in config files and language bindings.
    pub fn set_named(&mut self, name: &str, value: Rgb) -> bool {
        let target = match name {
            "foreground" => &mut self.foreground,
            "background" => &mut self.background,
            "cursor" => &mut self.cursor,
            "black" => &mut self.black,
            "red" => &mut self.red,
            "green" => &mut self.green,
            "yellow" => &mut self.yellow,
            "blue" => &mut self.blue,
            "magenta" => &mut self.magenta,
            "cyan" => &mut self.cyan,
            "white" => &mut self.white,
            "bright_black" => &mut self.bright_black,
            "bright_red" => &mut self.bright_red,
            "bright_green" => &mut self.bright_green,
            "bright_yellow" => &mut self.bright_yellow,
            "bright_blue" => &mut self.bright_blue,
            "bright_magenta" => &mut self.bright_magenta,
            "bright_cyan" => &mut self.bright_cyan,
            "bright_white" => &mut self.bright_white,
            _ => return false,
        };
        *target = value;
        true
    }

    /// Resolve any 256-color index.
    ///
    /// Slots 0-15 come from the profile; everything above comes from the
    /// xterm table, which no profile can move.
    pub fn rgb(&self, index: u8) -> Rgb {
        match index {
            0..=15 => self.ansi()[index as usize],
            _ => xterm_color(index),
        }
    }
}

/// A color a program can address.
///
/// `OSC 4` names a palette entry and `OSC 10/11/12` name the three defaults.
/// Emulators number these however they like internally, so each backend
/// translates its own layout and that numbering never reaches here.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ColorSlot {
    Indexed(u8),
    Foreground,
    Background,
    Cursor,
}

/// The xterm 256-color table, which is the same in every terminal.
///
/// Slots 0-15 here are the classic VGA colors, and a profile overrides them.
/// The rest is the 6x6x6 color cube and the 24-step gray ramp, which the
/// specification fixes and no profile can move: `--fg 196` has to mean the
/// same thing in every session.
static XTERM_256: [Rgb; 256] = build_xterm_256();

const fn build_xterm_256() -> [Rgb; 256] {
    let mut table = [Rgb::new(0, 0, 0); 256];

    // 0-15: VGA.
    let vga = [
        (0, 0, 0),
        (128, 0, 0),
        (0, 128, 0),
        (128, 128, 0),
        (0, 0, 128),
        (128, 0, 128),
        (0, 128, 128),
        (192, 192, 192),
        (128, 128, 128),
        (255, 0, 0),
        (0, 255, 0),
        (255, 255, 0),
        (0, 0, 255),
        (255, 0, 255),
        (0, 255, 255),
        (255, 255, 255),
    ];
    let mut i = 0;
    while i < 16 {
        table[i] = Rgb::new(vga[i].0, vga[i].1, vga[i].2);
        i += 1;
    }

    // 16-231: a 6x6x6 cube whose levels step 0, 95, 135, 175, 215, 255.
    let levels = [0u8, 95, 135, 175, 215, 255];
    while i < 232 {
        let n = i - 16;
        table[i] = Rgb::new(levels[(n / 36) % 6], levels[(n / 6) % 6], levels[n % 6]);
        i += 1;
    }

    // 232-255: a gray ramp from 8 to 238 in steps of 10.
    while i < 256 {
        let v = (i - 232) as u8 * 10 + 8;
        table[i] = Rgb::new(v, v, v);
        i += 1;
    }
    table
}

/// The color a slot has when nothing has overridden it.
pub fn xterm_color(index: u8) -> Rgb {
    XTERM_256[index as usize]
}

/// The settings a session runs with.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct Profile {
    /// Rows retained beyond the visible screen.
    pub scrollback: usize,
    pub colors: Colors,
}

impl Default for Profile {
    fn default() -> Self {
        Profile {
            scrollback: DEFAULT_SCROLLBACK,
            colors: Colors::default(),
        }
    }
}

/// A profile as represented in `tui-test.toml`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct ConfigProfile {
    pub scrollback: usize,
    pub colors: Colors,
    pub timeouts: crate::api::Timeouts,
}

impl Default for ConfigProfile {
    fn default() -> Self {
        Self {
            scrollback: DEFAULT_SCROLLBACK,
            colors: Colors::default(),
            timeouts: crate::api::Timeouts::default(),
        }
    }
}

/// Concrete session settings resolved from a config profile.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct Settings {
    pub profile: Profile,
    pub timeouts: crate::api::Timeouts,
}

impl From<ConfigProfile> for Settings {
    fn from(value: ConfigProfile) -> Self {
        Self {
            profile: Profile {
                scrollback: value.scrollback,
                colors: value.colors,
            },
            timeouts: value.timeouts,
        }
    }
}

/// A parsed config file: named profiles, and nothing else.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct ConfigFile {
    pub profiles: BTreeMap<String, ConfigProfile>,
}

impl ConfigFile {
    pub fn parse(toml_text: &str) -> anyhow::Result<Self> {
        Ok(toml::from_str(toml_text)?)
    }

    pub fn load(path: &Path) -> anyhow::Result<Self> {
        let text = std::fs::read_to_string(path)
            .map_err(|e| anyhow::anyhow!("could not read {}: {e}", path.display()))?;
        Self::parse(&text).map_err(|e| anyhow::anyhow!("{}: {e}", path.display()))
    }

    /// The named profile, or the built-in defaults when nothing is named and
    /// the file defines no `default`.
    pub fn profile(&self, name: Option<&str>) -> anyhow::Result<Profile> {
        Ok(self.settings(name)?.profile)
    }

    /// The named profile and its session timeout defaults.
    pub fn settings(&self, name: Option<&str>) -> anyhow::Result<Settings> {
        let profile = match name {
            Some(name) => self.profiles.get(name).copied().ok_or_else(|| {
                let known: Vec<&str> = self.profiles.keys().map(String::as_str).collect();
                if known.is_empty() {
                    anyhow::anyhow!("no profile {name:?}; the config file defines none")
                } else {
                    anyhow::anyhow!("no profile {name:?}; found: {}", known.join(", "))
                }
            }),
            None => Ok(self
                .profiles
                .get(DEFAULT_PROFILE)
                .copied()
                .unwrap_or_default()),
        }?;
        Ok(profile.into())
    }
}

/// Where a config file is looked for, nearest first.
///
/// A project-local file wins so a repository can pin the terminal its tests
/// expect. `TUI_TEST_CONFIG` replaces discovery, which is also how a test
/// suite pins a config without depending on the working directory.
pub fn search_paths(cwd: &Path) -> Vec<PathBuf> {
    if let Some(explicit) = std::env::var_os("TUI_TEST_CONFIG") {
        return vec![PathBuf::from(explicit)];
    }
    default_search_paths(cwd)
}

fn default_search_paths(cwd: &Path) -> Vec<PathBuf> {
    let config_home = if std::env::var_os("TUI_TEST_HOME").is_none() {
        dirs::config_dir()
    } else {
        None
    };
    config_search_paths(cwd, config_home.as_deref(), &crate::config::home_dir())
}

fn config_search_paths(
    cwd: &Path,
    platform_config_home: Option<&Path>,
    tui_test_home: &Path,
) -> Vec<PathBuf> {
    let mut paths = vec![cwd.join(CONFIG_FILE)];
    if let Some(config_home) = platform_config_home {
        paths.push(config_home.join("tui-test").join(CONFIG_FILE));
    }
    let home_config = tui_test_home.join(CONFIG_FILE);
    if !paths.contains(&home_config) {
        paths.push(home_config);
    }
    paths
}

/// Resolve a profile: an explicit file if given, else the first file found on
/// the search path, else the built-in defaults.
///
/// Missing discovered files are normal — tui-test runs without one. A path
/// explicitly named by `--config` or `TUI_TEST_CONFIG` must exist, because
/// silently ignoring it would run the session with settings the user did not
/// ask for.
pub fn resolve(
    explicit_config: Option<&Path>,
    profile_name: Option<&str>,
    cwd: &Path,
) -> anyhow::Result<Profile> {
    Ok(resolve_settings(explicit_config, profile_name, cwd)?.profile)
}

/// Resolve terminal settings and session timeout defaults together.
pub fn resolve_settings(
    explicit_config: Option<&Path>,
    profile_name: Option<&str>,
    cwd: &Path,
) -> anyhow::Result<Settings> {
    if let Some(path) = explicit_config {
        return ConfigFile::load(path)?.settings(profile_name);
    }
    if let Some(path) = std::env::var_os("TUI_TEST_CONFIG").map(PathBuf::from) {
        return ConfigFile::load(&path)?.settings(profile_name);
    }
    for path in default_search_paths(cwd) {
        if path.is_file() {
            return ConfigFile::load(&path)?.settings(profile_name);
        }
    }
    match profile_name {
        Some(name) => anyhow::bail!("no profile {name:?}: no config file found"),
        None => Ok(Settings::default()),
    }
}

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

    static ENV_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());

    #[test]
    fn hex_colors_round_trip() {
        for raw in ["#000000", "#ffffff", "#800000", "#c0c0c0"] {
            assert_eq!(Rgb::parse(raw).unwrap().to_hex(), raw);
        }
        assert_eq!(Rgb::parse("#f00").unwrap(), Rgb::new(255, 0, 0));
        assert_eq!(Rgb::parse("800000").unwrap(), Rgb::new(128, 0, 0));
    }

    #[test]
    fn a_bad_color_says_what_it_wanted() {
        for raw in ["", "#12", "#1234567", "nope", "#gggggg", "éa", "##fff"] {
            let err = Rgb::parse(raw).unwrap_err();
            assert!(
                err.contains("color") || err.contains("hex"),
                "{raw:?}: {err}"
            );
        }
    }

    /// A profile that says nothing is the built-in default, so a config file is
    /// never required.
    #[test]
    fn an_empty_config_yields_the_defaults() {
        let cfg = ConfigFile::parse("").unwrap();
        assert_eq!(cfg.profile(None).unwrap(), Profile::default());
        assert_eq!(Profile::default().scrollback, 10_000);
    }

    /// Every field is individually optional, so a profile can set one color
    /// without restating the palette.
    #[test]
    fn a_partial_profile_keeps_the_other_defaults() {
        let cfg = ConfigFile::parse(
            r##"
            [profiles.ci]
            scrollback = 50

            [profiles.ci.colors]
            red = "#ff0000"
            "##,
        )
        .unwrap();
        let p = cfg.profile(Some("ci")).unwrap();
        assert_eq!(p.scrollback, 50);
        assert_eq!(p.colors.red, Rgb::new(255, 0, 0), "the override applies");
        assert_eq!(
            p.colors.green,
            Colors::default().green,
            "an unset slot keeps its default"
        );
        assert_eq!(
            p.colors.background,
            Colors::default().background,
            "an unset default color is untouched"
        );
    }

    #[test]
    fn profile_timeouts_are_loaded_and_accept_cli_overrides() {
        let cfg = ConfigFile::parse(
            r#"
            [profiles.ci.timeouts]
            text = 1000
            command = 30000
            "#,
        )
        .unwrap();
        let settings = cfg.settings(Some("ci")).unwrap();
        assert_eq!(settings.timeouts.text, Some(1_000));
        assert_eq!(settings.timeouts.command, Some(30_000));
        assert_eq!(settings.timeouts.ready, None);

        let merged = settings.timeouts.with_overrides(crate::api::Timeouts {
            text: Some(2_000),
            ready: Some(5_000),
            ..Default::default()
        });
        assert_eq!(merged.text, Some(2_000));
        assert_eq!(merged.command, Some(30_000));
        assert_eq!(merged.ready, Some(5_000));
    }

    #[test]
    fn an_unknown_timeout_class_is_rejected() {
        let err = ConfigFile::parse("[profiles.ci.timeouts]\ncommands = 10\n")
            .unwrap_err()
            .to_string();
        assert!(err.contains("commands"), "{err}");
    }

    #[test]
    fn an_unknown_profile_names_the_ones_that_exist() {
        let cfg = ConfigFile::parse("[profiles.ci]\n[profiles.demo]\n").unwrap();
        let err = cfg.profile(Some("nope")).unwrap_err().to_string();
        assert!(err.contains("ci") && err.contains("demo"), "{err}");
    }

    /// A typo in a key is an error rather than a setting that silently does
    /// nothing.
    #[test]
    fn an_unknown_key_is_rejected() {
        let err = ConfigFile::parse("[profiles.ci]\nscrollbacks = 10\n")
            .unwrap_err()
            .to_string();
        assert!(err.contains("scrollbacks"), "{err}");
    }

    /// Above the sixteen configurable slots the palette is spec, not
    /// preference, so profiles cannot disagree about what `--fg 196` means.
    #[test]
    fn the_color_cube_ignores_the_profile() {
        let recolored = Colors {
            red: Rgb::new(1, 2, 3),
            ..Default::default()
        };
        for n in 16u8..=255 {
            assert_eq!(recolored.rgb(n), Colors::default().rgb(n), "index {n}");
        }
        assert_eq!(Colors::default().rgb(196), Rgb::new(255, 0, 0));
        assert_eq!(Colors::default().rgb(232), Rgb::new(8, 8, 8));
        assert_eq!(recolored.rgb(1), Rgb::new(1, 2, 3), "but slot 1 follows it");
    }

    /// Every configurable slot is reachable by the name the file uses, so the
    /// documented key set and the resolver cannot drift apart.
    #[test]
    fn every_ansi_slot_has_a_config_key() {
        for i in 0u8..16 {
            let name = Colors::slot_name(i).unwrap_or_else(|| panic!("slot {i} unnamed"));
            let toml = format!("[profiles.p.colors]\n{name} = \"#010203\"\n");
            let p = ConfigFile::parse(&toml)
                .unwrap()
                .profile(Some("p"))
                .unwrap();
            assert_eq!(
                p.colors.rgb(i),
                Rgb::new(1, 2, 3),
                "setting {name:?} must move slot {i}"
            );
        }
        assert_eq!(Colors::slot_name(16), None, "only 0-15 are configurable");
    }

    #[test]
    fn every_binding_color_name_is_settable() {
        let mut colors = Colors::default();
        let replacement = Rgb::new(1, 2, 3);
        for name in [
            "foreground",
            "background",
            "cursor",
            "black",
            "red",
            "green",
            "yellow",
            "blue",
            "magenta",
            "cyan",
            "white",
            "bright_black",
            "bright_red",
            "bright_green",
            "bright_yellow",
            "bright_blue",
            "bright_magenta",
            "bright_cyan",
            "bright_white",
        ] {
            assert!(colors.set_named(name, replacement), "{name}");
        }
        assert!(!colors.set_named("chartreuse", replacement));
        assert!([
            colors.foreground,
            colors.background,
            colors.cursor,
            colors.black,
            colors.red,
            colors.green,
            colors.yellow,
            colors.blue,
            colors.magenta,
            colors.cyan,
            colors.white,
            colors.bright_black,
            colors.bright_red,
            colors.bright_green,
            colors.bright_yellow,
            colors.bright_blue,
            colors.bright_magenta,
            colors.bright_cyan,
            colors.bright_white,
        ]
        .into_iter()
        .all(|color| color == replacement));
    }

    /// The 16 configurable slots come from the profile; the rest come from the
    /// xterm table, which is the same in every terminal.
    #[test]
    fn only_the_ansi_slots_follow_the_profile() {
        let recolored = Colors {
            red: Rgb::new(1, 2, 3),
            ..Default::default()
        };
        assert_eq!(recolored.rgb(1), Rgb::new(1, 2, 3), "slot 1 follows it");
        for index in 16u8..=255 {
            assert_eq!(
                recolored.rgb(index),
                xterm_color(index),
                "slot {index} is fixed by the specification"
            );
        }
    }

    /// Spot-check the static table against the values the specification
    /// defines, so a typo in 256 entries cannot pass unnoticed.
    #[test]
    fn the_xterm_table_matches_the_specification() {
        assert_eq!(xterm_color(0), Rgb::new(0, 0, 0), "VGA black");
        assert_eq!(xterm_color(1), Rgb::new(128, 0, 0), "VGA red");
        assert_eq!(xterm_color(15), Rgb::new(255, 255, 255), "VGA bright white");
        assert_eq!(
            xterm_color(16),
            Rgb::new(0, 0, 0),
            "the cube starts at black"
        );
        assert_eq!(xterm_color(196), Rgb::new(255, 0, 0), "cube red");
        assert_eq!(
            xterm_color(231),
            Rgb::new(255, 255, 255),
            "the cube ends white"
        );
        assert_eq!(xterm_color(232), Rgb::new(8, 8, 8), "the ramp starts at 8");
        assert_eq!(
            xterm_color(255),
            Rgb::new(238, 238, 238),
            "the ramp ends at 238"
        );
    }

    /// A project-local file wins over the user's, so a repository can pin the
    /// terminal its tests expect. `TUI_TEST_CONFIG` replaces discovery.
    #[test]
    fn the_search_order_puts_the_project_first() {
        let _guard = ENV_LOCK.lock().unwrap();

        let old = std::env::var_os("TUI_TEST_CONFIG");
        std::env::remove_var("TUI_TEST_CONFIG");
        let cwd = std::env::temp_dir().join("some-project");
        let pinned_path = std::env::temp_dir().join("pinned.toml");
        let result = std::panic::catch_unwind(|| {
            let paths = search_paths(&cwd);
            assert!(paths.len() >= 2);
            assert_eq!(paths[0], cwd.join(CONFIG_FILE), "the project file is first");
            assert!(
                paths[1..].iter().all(|path| path.ends_with(CONFIG_FILE)),
                "every user candidate names the config file: {paths:?}"
            );

            std::env::set_var("TUI_TEST_CONFIG", &pinned_path);
            let pinned = search_paths(&cwd);
            assert_eq!(
                pinned,
                vec![pinned_path.clone()],
                "an explicit config replaces the search entirely"
            );
        });
        std::env::remove_var("TUI_TEST_CONFIG");
        if let Some(value) = old {
            std::env::set_var("TUI_TEST_CONFIG", value);
        }
        result.unwrap();
    }

    #[test]
    fn the_platform_config_directory_precedes_tui_test_home() {
        let cwd = Path::new("project");
        let config_home = Path::new("xdg-config");
        let tui_test_home = Path::new("tui-test-home");
        assert_eq!(
            config_search_paths(cwd, Some(config_home), tui_test_home),
            vec![
                cwd.join(CONFIG_FILE),
                config_home.join("tui-test").join(CONFIG_FILE),
                tui_test_home.join(CONFIG_FILE),
            ]
        );
    }

    /// An environment override is an explicit request, just like `--config`,
    /// so a typo must not silently fall back to the built-in profile.
    #[test]
    fn a_missing_environment_override_is_an_error() {
        let _guard = ENV_LOCK.lock().unwrap();
        let old = std::env::var_os("TUI_TEST_CONFIG");
        let dir = std::env::temp_dir().join(format!("su-profile-env-{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        let missing = dir.join("missing.toml");

        std::env::set_var("TUI_TEST_CONFIG", &missing);
        let result = std::panic::catch_unwind(|| {
            let err = resolve(None, None, &dir).unwrap_err().to_string();
            assert!(
                err.contains("missing.toml"),
                "the explicit missing path is named: {err}"
            );
        });

        std::env::remove_var("TUI_TEST_CONFIG");
        if let Some(value) = old {
            std::env::set_var("TUI_TEST_CONFIG", value);
        }
        std::fs::remove_dir_all(&dir).ok();
        result.unwrap();
    }

    /// Running without a config file is normal, so a missing one is not an
    /// error. A file that exists but does not parse is, because ignoring it
    /// would silently run with settings nobody asked for.
    #[test]
    fn a_missing_config_defaults_but_a_broken_one_fails() {
        let dir = std::env::temp_dir().join(format!("su-profile-{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();

        let missing = dir.join("absent.toml");
        assert!(
            resolve(Some(&missing), None, &dir).is_err(),
            "named-but-absent is an error"
        );

        let broken = dir.join("broken.toml");
        std::fs::write(&broken, "[profiles.ci]\nscrollback = \"lots\"\n").unwrap();
        let err = resolve(Some(&broken), None, &dir).unwrap_err().to_string();
        assert!(
            err.contains("broken.toml"),
            "the error names the file: {err}"
        );

        std::fs::remove_dir_all(&dir).ok();
    }
}