termlens 0.8.0

Headless PTY test harness for CLI/TUI apps — spawn in a real PTY, assert on the rendered screen
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
//! The query responder: capability-probing apps get real answers instead
//! of hanging, and whatever stays unanswered is named in timeout errors.
//!
//! Each shell script here genuinely BLOCKS on the terminal's reply
//! (`head -c N` reads exactly the reply bytes), then prints a marker the
//! test waits for — the marker appearing proves the app was unblocked.

use std::time::Duration;

use termlens::{Error, Key, Terminal};

fn sh(script: &str) -> termlens::Result<Terminal> {
    Terminal::builder()
        .timeout(Duration::from_secs(10))
        .args(["-c", script])
        .spawn("/bin/sh")
}

#[test]
fn cursor_position_reports_the_position_at_the_query() -> termlens::Result<()> {
    // After printing "abc" the cursor sits at row 1, col 4 (1-based on the
    // wire); the CPR reply is exactly 6 bytes: ESC [ 1 ; 4 R.
    let mut t = sh(concat!(
        r"stty -icanon -echo; printf 'abc\033[6n'; ",
        r#"reply=$(head -c 6 | tr '\033' 'E'); "#,
        r#"printf '\nunblocked:%s' "$reply"; read guard"#
    ))?;
    t.wait_until(|s| s.contains("unblocked:E[1;4R"))?;
    t.send(Key::Enter)?;
    assert!(t.wait_exit()?.success());
    Ok(())
}

#[test]
fn device_attribute_probes_are_unblocked() -> termlens::Result<()> {
    // DA1 reply is ESC [ ? 6 2 ; 2 2 c = 9 bytes. This is also the exact
    // pattern kitty-protocol probes rely on: the DA1 answer arriving tells
    // the app "no kitty support", exactly like a real non-kitty terminal.
    let mut t = sh(concat!(
        r"stty -icanon -echo; printf '\033[c'; ",
        r#"reply=$(head -c 9 | tr '\033' 'E'); "#,
        r#"printf 'unblocked:%s' "$reply"; read guard"#
    ))?;
    t.wait_until(|s| s.contains("unblocked:E[?62;22c"))?;
    t.send(Key::Enter)?;
    assert!(t.wait_exit()?.success());
    Ok(())
}

#[test]
fn background_color_query_gets_the_configured_answer() -> termlens::Result<()> {
    // OSC 11 reply: ESC ] 1 1 ; rgb:1e1e/1e1e/2e2e BEL = 24 bytes.
    let mut t = Terminal::builder()
        .timeout(Duration::from_secs(10))
        .background_rgb(0x1e, 0x1e, 0x2e)
        .args([
            "-c",
            concat!(
                r"stty -icanon -echo; printf '\033]11;?\007'; ",
                r#"reply=$(head -c 24 | tr '\033\007' 'EG'); "#,
                r#"printf 'unblocked:%s' "$reply"; read guard"#
            ),
        ])
        .spawn("/bin/sh")?;
    t.wait_until(|s| s.contains("unblocked:E]11;rgb:1e1e/1e1e/2e2eG"))?;
    t.send(Key::Enter)?;
    assert!(t.wait_exit()?.success());
    Ok(())
}

#[test]
fn foreground_color_query_gets_the_configured_answer() -> termlens::Result<()> {
    // OSC 10 reply: ESC ] 1 0 ; rgb:cdcd/d6d6/f4f4 BEL = 24 bytes.
    let mut t = Terminal::builder()
        .timeout(Duration::from_secs(10))
        .foreground_rgb(0xcd, 0xd6, 0xf4)
        .args([
            "-c",
            concat!(
                r"stty -icanon -echo; printf '\033]10;?\007'; ",
                r#"reply=$(head -c 24 | tr '\033\007' 'EG'); "#,
                r#"printf 'unblocked:%s' "$reply"; read guard"#
            ),
        ])
        .spawn("/bin/sh")?;
    t.wait_until(|s| s.contains("unblocked:E]10;rgb:cdcd/d6d6/f4f4G"))?;
    t.send(Key::Enter)?;
    assert!(t.wait_exit()?.success());
    Ok(())
}

#[test]
fn text_area_size_reports_the_real_grid() -> termlens::Result<()> {
    // XTWINOPS 18 reply: ESC [ 8 ; 24 ; 80 t = 10 bytes.
    let mut t = sh(concat!(
        r"stty -icanon -echo; printf '\033[18t'; ",
        r#"reply=$(head -c 10 | tr '\033' 'E'); "#,
        r#"printf 'unblocked:%s' "$reply"; read guard"#
    ))?;
    t.wait_until(|s| s.contains("unblocked:E[8;24;80t"))?;
    t.send(Key::Enter)?;
    assert!(t.wait_exit()?.success());
    Ok(())
}

#[test]
fn unanswerable_queries_turn_timeouts_into_diagnoses() {
    // CSI 14 t (pixel size) is recognized as a question termlens cannot
    // answer; the app blocks, and the timeout error names the query.
    let mut t = Terminal::builder()
        .timeout(Duration::from_millis(500))
        .args(["-c", r"printf '\033[14t'; head -c 4 >/dev/null; echo never"])
        .spawn("/bin/sh")
        .unwrap();
    let err = t.wait_until(|s| s.contains("never")).unwrap_err();
    let msg = err.to_string();
    assert!(msg.contains("^[[14t"), "query not named in: {msg}");
    assert!(msg.contains("received no answer"), "no diagnosis in: {msg}");
    // Drop kills the blocked child.
}

#[test]
fn the_responder_can_be_disabled_and_says_what_went_unanswered() {
    let mut t = Terminal::builder()
        .timeout(Duration::from_millis(500))
        .answer_queries(false)
        .args(["-c", r"printf '\033[6n'; head -c 6 >/dev/null; echo never"])
        .spawn("/bin/sh")
        .unwrap();
    let err = t.wait_until(|s| s.contains("never")).unwrap_err();
    assert!(matches!(err, Error::Timeout { .. }));
    let msg = err.to_string();
    assert!(msg.contains("^[[6n"), "query not named in: {msg}");
}

/// The diagnosis must not outlive the situation it describes. An app
/// that probes, is answered nothing, and carries on producing output was
/// plainly not blocked on that probe — a later, unrelated timeout must
/// not blame it.
#[test]
fn a_query_the_app_moved_past_is_context_not_a_cause() {
    let mut t = Terminal::builder()
        .timeout(Duration::from_millis(400))
        // Probes kitty (deliberately unanswered), does NOT block on a
        // reply, prints, then sits in a normal read. The pause forces the
        // output into a *later read* than the probe — output batched into
        // the same write is deliberately not treated as progress, since
        // the emulator stops at the query byte and consumes the rest of
        // that same chunk regardless of what the application is doing.
        .args([
            "-c",
            r"printf '\033[?u'; sleep 0.2; printf 'ready\n'; read guard",
        ])
        .spawn("/bin/sh")
        .unwrap();
    t.wait_until(|s| s.contains("ready")).unwrap();

    let err = t.wait_until(|s| s.contains("never-appears")).unwrap_err();
    let msg = err.to_string();
    assert!(
        msg.contains("^[[?u"),
        "the query is still worth naming: {msg}"
    );
    assert!(
        !msg.contains("this is the cause"),
        "the app moved past the probe — no causal claim belongs here: {msg}"
    );
    assert!(
        msg.contains("produced output afterwards"),
        "the note should say why it is only context: {msg}"
    );
}

/// Every unanswered query is named, not just the most recent one.
#[test]
fn all_unanswered_queries_are_named() {
    let mut t = Terminal::builder()
        .timeout(Duration::from_millis(400))
        .args([
            "-c",
            r"printf '\033[?u\033[14t'; head -c 4 >/dev/null; echo never",
        ])
        .spawn("/bin/sh")
        .unwrap();
    let err = t.wait_until(|s| s.contains("never")).unwrap_err();
    let msg = err.to_string();
    assert!(msg.contains("^[[?u"), "first query missing from: {msg}");
    assert!(msg.contains("^[[14t"), "second query missing from: {msg}");
}

/// `wait_frame` used to build its message from its own strings and never
/// surface the note — the worst place to withhold it, since an app
/// blocked on a probe never reaches its first repaint and the message
/// then blames the app for not emitting frames.
#[test]
fn wait_frame_timeouts_carry_the_query_note() {
    let mut t = Terminal::builder()
        .timeout(Duration::from_millis(400))
        .args(["-c", r"printf '\033[14t'; head -c 4 >/dev/null; echo never"])
        .spawn("/bin/sh")
        .unwrap();
    let err = t.wait_frame(|s| s.contains("never")).unwrap_err();
    let msg = err.to_string();
    assert!(
        msg.contains("^[[14t") && msg.contains("received no answer"),
        "wait_frame withheld the diagnosis: {msg}"
    );
}

/// The payoff of answering DECRQM: an application that *probes* before
/// using synchronized output can turn it on against termlens — so
/// `wait_frame` works against a program nobody modified for us.
#[test]
fn an_app_that_probes_for_synchronized_output_gets_it() -> termlens::Result<()> {
    let mut t = sh(concat!(
        // Ask "is mode 2026 supported?" and read the DECRPM reply.
        r"stty -icanon -echo; printf '\033[?2026$p'; ",
        r#"reply=$(head -c 10 | tr '\033' 'E'); "#,
        // A terminal that does not recognize the mode answers `;0$y`.
        r#"case "$reply" in *';0$y') printf 'unsupported'; read guard; exit 0 ;; esac; "#,
        // Recognized: bracket the repaint, exactly as a real app would.
        r"printf '\033[?2026h\033[HPROBED FRAME\033[?2026l'; read guard"
    ))?;

    t.wait_frame(|s| s.contains("PROBED FRAME"))?;
    t.send(Key::Enter)?;
    assert!(t.wait_exit()?.success());
    Ok(())
}

/// The reply must be truthful, not merely present: a mode we do not
/// track exactly is reported as "not recognized" rather than guessed.
#[test]
fn mode_reports_are_truthful() -> termlens::Result<()> {
    let mut t = sh(concat!(
        r"stty -icanon -echo; printf '\033[?2004h'; ",
        // 2004 was just set -> `;1$y`; 1 (DECCKM) is untouched -> `;2$y`;
        // 12 (cursor blink) is not tracked at all -> `;0$y`.
        r"printf '\033[?2004$p\033[?1$p\033[?12$p'; ",
        // The three replies are 11 + 8 + 9 = 28 bytes:
        // ESC[?2004;1$y  ESC[?1;2$y  ESC[?12;0$y
        r#"reply=$(head -c 28 | tr '\033' 'E'); "#,
        r#"printf 'got:%s' "$reply"; read guard"#
    ))?;
    t.wait_until(|s| s.contains("got:"))?;
    let row = t.screen().row_text(0);
    assert!(row.contains("E[?2004;1$y"), "2004 should be set: {row}");
    assert!(row.contains("E[?1;2$y"), "DECCKM should be reset: {row}");
    assert!(row.contains("E[?12;0$y"), "12 is not tracked: {row}");

    t.send(Key::Enter)?;
    assert!(t.wait_exit()?.success());
    Ok(())
}

/// The families we recognize but cannot answer are now named in the
/// timeout instead of hanging silently.
#[test]
fn decrqss_and_palette_queries_are_named() {
    for (label, script, shape) in [
        (
            "DECRQSS",
            r#"printf '\033P$qm\033\\'; head -c 4 >/dev/null; echo never"#,
            "^[P$qm",
        ),
        (
            "OSC 4",
            r#"printf '\033]4;1;?\007'; head -c 4 >/dev/null; echo never"#,
            "^[]4;1;?",
        ),
    ] {
        let mut t = Terminal::builder()
            .timeout(Duration::from_millis(400))
            .args(["-c", script])
            .spawn("/bin/sh")
            .unwrap();
        let err = t.wait_until(|s| s.contains("never")).unwrap_err();
        let msg = err.to_string();
        assert!(msg.contains(shape), "{label} not named in: {msg}");
    }
}

#[test]
fn replies_are_not_echoed_into_the_screen() -> termlens::Result<()> {
    // The reply travels the input path; unless the app prints it, it must
    // never appear in the grid. `stty -echo` keeps the line discipline
    // from echoing what the "terminal" typed back.
    let mut t = sh(concat!(
        r"stty -icanon -echo; printf 'before\033[5n'; ",
        r"head -c 4 >/dev/null; ",
        r"printf ' after'; read guard"
    ))?;
    t.wait_until(|s| s.contains("before after"))?;
    assert!(
        !t.screen().text().contains("[0n"),
        "reply leaked into the grid:\n{}",
        t.screen()
    );
    t.send(Key::Enter)?;
    assert!(t.wait_exit()?.success());
    Ok(())
}

#[test]
fn a_probe_then_enable_application_gets_its_mouse() -> termlens::Result<()> {
    // The loop this closes on itself: the application probes `?1000$p`, is
    // told "not recognized", concludes the terminal has no mouse and never
    // sends `CSI ?1000h` — and `click` then refuses, blaming the
    // application for a decision termlens caused.
    //
    // The script is written to *prove* the decision: if the reply says the
    // mode is unrecognized it prints REFUSED and never enables tracking,
    // so a regression fails on the wait below rather than passing quietly.
    let mut t = sh(concat!(
        r"stty -icanon -echo; ",
        r#"printf '\033[?1000$p'; "#,
        r#"reply=$(head -c 11 | tr '\033' 'E'); "#,
        r#"case "$reply" in *';0$y') printf 'REFUSED:%s' "$reply"; read g; exit 0;; esac; "#,
        r#"printf '\033[?1000h\033[?1006h'; printf 'MOUSE-ON:%s|' "$reply"; "#,
        r#"click=$(head -c 20 | tr '\033' 'E'); printf 'CLICK:%s' "$click"; read g"#
    ))?;
    // `;2$y` = implemented and currently reset. The application proceeds.
    t.wait_until(|s| s.contains("MOUSE-ON:E[?1000;2$y|"))?;

    t.click(9, 4)?;
    // Press and release, SGR-encoded, 1-based on the wire.
    t.wait_until(|s| s.contains("CLICK:E[<0;10;5ME[<0;10;5m"))?;

    t.send(Key::Enter)?;
    assert!(t.wait_exit()?.success());
    Ok(())
}

/// Mode 1004 is now answerable, because termlens tracks it exactly — the
/// honesty rule's precondition. Before, an application probing for focus
/// support was told "not recognized" even right after enabling it.
#[test]
fn decrqm_answers_for_focus_reporting() -> termlens::Result<()> {
    // Reply values: 1 = set, 2 = reset, 0 = not recognized.
    for (script, expect, label) in [
        (
            r"printf '\033[?1004$p'",
            ";2$y",
            "reset before the app enables it",
        ),
        (
            r"printf '\033[?1004h\033[?1004$p'",
            ";1$y",
            "set after enabling",
        ),
        (
            r"printf '\033[?1004h\033[?1004l\033[?1004$p'",
            ";2$y",
            "reset again after disabling",
        ),
    ] {
        let mut t = Terminal::builder()
            .size(80, 6)
            .timeout(Duration::from_secs(10))
            .args([
                "-c",
                &format!(
                    "stty -icanon -echo; {script}; \
                     head -c 11 | tr -d '\\033'; printf ' DONE'; read guard"
                ),
            ])
            .spawn("/bin/sh")?;
        t.wait_until(|s| s.contains("DONE"))?;
        let row = t.screen().row_text(0);
        assert!(row.contains(expect), "{label}: got {row:?}");
        assert!(
            !row.contains(";0$y"),
            "{label}: must not report unrecognized"
        );
        t.send(Key::Enter)?;
        assert!(t.wait_exit()?.success());
    }
    Ok(())
}

/// Pixel geometry: unset it stays unanswered and named, set it makes the
/// two escape replies and `TIOCGWINSZ` agree instead of contradicting.
#[test]
fn cell_size_answers_the_pixel_reports_and_the_ioctl() -> termlens::Result<()> {
    // Unset: no reply, and the query is named in the next timeout.
    let mut mute = Terminal::builder()
        .size(80, 6)
        .timeout(Duration::from_millis(700))
        .args([
            "-c",
            r"stty -icanon -echo; printf '\033[16t'; printf MARK; read g",
        ])
        .spawn("/bin/sh")?;
    let err = mute
        .wait_until(|s| s.contains("NEVER"))
        .expect_err("must time out");
    assert!(err.to_string().contains("^[[16t"), "named: {err}");
    mute.send(Key::Enter)?;

    // Declared: both reports answer from it.
    let mut t = Terminal::builder()
        .size(80, 24)
        .cell_size(10, 20)
        .timeout(Duration::from_secs(10))
        .args([
            "-c",
            concat!(
                // `min 0 time 20` so a read returns on a 2s timer instead of
                // blocking on a byte count guessed wrong.
                r"stty -icanon -echo min 0 time 20; ",
                r"printf '\033[16t'; a=$(dd bs=1 count=32 2>/dev/null | tr -d '\033'); ",
                r"printf '\033[14t'; b=$(dd bs=1 count=32 2>/dev/null | tr -d '\033'); ",
                r#"printf 'cell[%s] win[%s] DONE' "$a" "$b"; read g"#
            ),
        ])
        .spawn("/bin/sh")?;
    t.wait_until(|s| s.contains("DONE"))?;
    let row = t.screen().row_text(0);
    // CSI 6 ; height ; width t   and   CSI 4 ; rows*h ; cols*w t
    assert!(row.contains("cell[[6;20;10t]"), "{row:?}");
    assert!(row.contains("win[[4;480;800t]"), "{row:?}");
    t.send(Key::Enter)?;
    assert!(t.wait_exit()?.success());
    Ok(())
}

/// The ioctl must agree with the escape replies, and a resize must move
/// both — otherwise an application gets two different answers to the same
/// question depending on how it asks.
#[test]
fn tiocgwinsz_agrees_with_the_declared_cell_size() -> termlens::Result<()> {
    let read_winsize = r#"python3 -c 'import fcntl,struct,sys,termios; b=fcntl.ioctl(0,termios.TIOCGWINSZ,b"\0"*8); r,c,xp,yp=struct.unpack("HHHH",b); print(f"{c}x{r} px {xp}x{yp}", flush=True)'"#;
    let script = format!("{read_winsize}; read a; {read_winsize}; printf DONE; read b");

    let mut t = Terminal::builder()
        .size(80, 24)
        .cell_size(10, 20)
        .timeout(Duration::from_secs(20))
        .args(["-c", &script])
        .spawn("/bin/sh")?;
    t.wait_until(|s| s.contains("px"))?;
    assert!(
        t.screen().contains("80x24 px 800x480"),
        "the ioctl must carry the declared geometry:\n{}",
        t.screen()
    );

    t.resize(40, 12)?;
    t.send(Key::Enter)?;
    t.wait_until(|s| s.contains("DONE"))?;
    assert!(
        t.screen().contains("40x12 px 400x240"),
        "a resize must recompute it:\n{}",
        t.screen()
    );

    t.send(Key::Enter)?;
    assert!(t.wait_exit()?.success());
    Ok(())
}

/// Declaring graphics support is how an application that probes first can
/// reach its pixel path at all. The default claims nothing, which is what
/// makes the declaration meaningful.
#[test]
fn declared_graphics_support_reaches_the_probe() -> termlens::Result<()> {
    // Default: DA1 has no `4`, and the kitty probe goes unanswered.
    let mut plain = Terminal::builder()
        .size(80, 6)
        .timeout(Duration::from_secs(10))
        .args([
            "-c",
            r"stty -icanon -echo; printf '\033[c'; head -c 9 | tr -d '\033'; printf ' DONE'; read g",
        ])
        .spawn("/bin/sh")?;
    plain.wait_until(|s| s.contains("DONE"))?;
    let row = plain.screen().row_text(0);
    assert!(
        row.contains("[?62;22c"),
        "nothing claimed by default: {row:?}"
    );
    assert!(!row.contains(";4;"), "no sixel by default: {row:?}");
    plain.send(Key::Enter)?;

    // Sixel declared: DA1 gains `4`, so a probing application sees it.
    let mut sixel = Terminal::builder()
        .size(80, 6)
        .graphics(termlens::Graphics::Sixel)
        .timeout(Duration::from_secs(10))
        .args([
            "-c",
            r"stty -icanon -echo; printf '\033[c'; head -c 11 | tr -d '\033'; printf ' DONE'; read g",
        ])
        .spawn("/bin/sh")?;
    sixel.wait_until(|s| s.contains("DONE"))?;
    assert!(
        sixel.screen().row_text(0).contains("[?62;4;22c"),
        "{:?}",
        sixel.screen().row_text(0)
    );
    sixel.send(Key::Enter)?;

    // Kitty declared: the a=q probe is answered OK, echoing the id.
    let mut kitty = Terminal::builder()
        .size(80, 6)
        .graphics(termlens::Graphics::Kitty)
        .timeout(Duration::from_secs(10))
        .args([
            "-c",
            r"stty -icanon -echo; printf '\033_Gi=7,a=q;\033\\'; head -c 9 | tr -d '\033'; printf ' DONE'; read g",
        ])
        .spawn("/bin/sh")?;
    kitty.wait_until(|s| s.contains("DONE"))?;
    assert!(
        kitty.screen().row_text(0).contains("_Gi=7;OK"),
        "the reply echoes the id the probe named: {:?}",
        kitty.screen().row_text(0)
    );
    kitty.send(Key::Enter)?;
    Ok(())
}

/// XTGETTCAP was the last of the common startup probes with no reply. Both
/// halves matter: a known capability is answered truthfully, and an unknown
/// one is *explicitly* declined — which is what turns a hang into a decision.
#[test]
fn xtgettcap_answers_what_it_knows_and_declines_the_rest() -> termlens::Result<()> {
    // TN=544e, colors=636f6c6f7273, and a made-up name that must be refused.
    let mut t = Terminal::builder()
        .size(120, 6)
        .timeout(Duration::from_secs(10))
        .args([
            "-c",
            concat!(
                r"stty -icanon -echo min 0 time 20; ",
                r"printf '\033P+q544e;636f6c6f7273;7a7a7a7a\033\\'; ",
                r"dd bs=1 count=200 2>/dev/null | tr -d '\033' | tr -s '\\' '|'; ",
                r"printf ' DONE'; read g"
            ),
        ])
        .spawn("/bin/sh")?;
    t.wait_until(|s| s.contains("DONE"))?;
    let text = t.screen().text();

    // TN -> "xterm-256color", hex 787465726d2d323536636f6c6f72
    assert!(
        text.contains("P1+r544e=787465726d2d323536636f6c6f72"),
        "TN must report the TERM the child was given:\n{text}"
    );
    // colors -> "256", hex 323536
    assert!(
        text.contains("P1+r636f6c6f7273=323536"),
        "colors must be answered:\n{text}"
    );
    // An unknown capability is declined with status 0, not ignored.
    assert!(
        text.contains("P0+r7a7a7a7a"),
        "an unknown capability must be explicitly refused:\n{text}"
    );

    t.send(Key::Enter)?;
    assert!(t.wait_exit()?.success());
    Ok(())
}

/// `TN` reports whatever `TERM` the child was actually given, so an
/// application cannot get two different answers to "which terminal is this?".
#[test]
fn xtgettcap_tn_follows_the_configured_term() -> termlens::Result<()> {
    let mut t = Terminal::builder()
        .size(120, 6)
        .env("TERM", "xterm")
        .timeout(Duration::from_secs(10))
        .args([
            "-c",
            concat!(
                r"stty -icanon -echo min 0 time 20; ",
                r"printf '\033P+q544e\033\\'; ",
                r"dd bs=1 count=80 2>/dev/null | tr -d '\033' | tr -s '\\' '|'; ",
                r#"printf ' term=%s DONE' "$TERM"; read g"#
            ),
        ])
        .spawn("/bin/sh")?;
    t.wait_until(|s| s.contains("DONE"))?;
    let text = t.screen().text();
    // "xterm" is hex 787465726d
    assert!(text.contains("P1+r544e=787465726d"), "{text}");
    assert!(text.contains("term=xterm"), "{text}");
    t.send(Key::Enter)?;
    assert!(t.wait_exit()?.success());
    Ok(())
}

/// A key capability must be the bytes termlens actually sends, or an
/// application that reads it and then matches input against it will not
/// match what arrives.
#[test]
fn xtgettcap_key_capabilities_match_what_send_emits() -> termlens::Result<()> {
    // kcuu1 = 6b63757531; the value must be ESC [ A = 1b5b41.
    let mut t = Terminal::builder()
        .size(120, 6)
        .timeout(Duration::from_secs(10))
        .args([
            "-c",
            concat!(
                r"stty -icanon -echo min 0 time 20; ",
                r"printf '\033P+q6b63757531\033\\'; ",
                r"dd bs=1 count=80 2>/dev/null | tr -d '\033' | tr -s '\\' '|'; ",
                r"printf ' DONE'; read g"
            ),
        ])
        .spawn("/bin/sh")?;
    t.wait_until(|s| s.contains("DONE"))?;
    let text = t.screen().text();
    assert!(text.contains("P1+r6b63757531=1b5b41"), "{text}");
    // And that is exactly what Key::Up encodes to in default mode.
    assert_eq!(termlens::Key::Up.encode(), b"\x1b[A");
    t.send(Key::Enter)?;
    assert!(t.wait_exit()?.success());
    Ok(())
}