standout-test 8.0.2

In-process test harness for applications built with the standout CLI framework
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
//! Themed help on the `run()` path, on the same terms as `get_matches_from`.
//!
//! The motivating application for the `help` word enters through `run()`, so
//! every form of help has to work there: the word under the same install
//! policy, `--help` / `-h` through Clap's short-circuit, the word's own
//! arguments, and the pager request. Two entry points that disagree about what
//! `myapp help` means would be the reported defect one layer down — so the
//! tests that matter here assert *agreement*, not just that something was
//! rendered.
//!
//! `USAGE` is the discriminator throughout: standout's template renders the
//! section header uppercase, while Clap's own help says `Usage:`.

use clap::{Arg, ArgAction, ArgGroup, Command};
use serde_json::json;
use serial_test::serial;
use standout::cli::{App, ExitStatus, HelpResult, Output, RunErrorKind, SuccessKind};
use standout::topics::{Topic, TopicType};
use standout::Theme;
use standout_test::TestHarness;

/// The shape from the issue: one optional positional, one flag, and a required
/// group over the two — a root whose requirements fire before anything can
/// decide what a bare word meant.
fn flat_required_command() -> Command {
    Command::new("app")
        .about("Flat app")
        .arg(Arg::new("range").help("A revision range"))
        .arg(
            Arg::new("staged")
                .long("staged")
                .action(ArgAction::SetTrue)
                .help("Use the staged diff"),
        )
        .group(
            ArgGroup::new("target")
                .args(["range", "staged"])
                .required(true),
        )
}

/// A flat app whose only handler is the root's, as `command_with("", …)` apps
/// are shaped. `help_word` toggles the opt-in the install policy asks for.
fn flat_app(help_word: bool) -> App {
    App::builder()
        .help_handling(true)
        .help_word(help_word)
        .add_topic(Topic::new(
            "Ranges",
            "A range is two revisions separated by two dots.",
            TopicType::Text,
            Some("ranges".to_string()),
        ))
        .command(
            "",
            |m, _ctx| {
                Ok(Output::Render(json!({
                    "range": m.get_one::<String>("range").cloned().unwrap_or_default(),
                })))
            },
            "range={{ range }}",
        )
        .unwrap()
        .build()
        .unwrap()
}

fn subcommand_command() -> Command {
    Command::new("app")
        .about("Subcommand app")
        .arg(
            Arg::new("file")
                .short('f')
                .action(ArgAction::Set)
                .help("A file to read"),
        )
        .subcommand(Command::new("list").about("List the things"))
}

fn subcommand_app() -> App {
    App::builder()
        .help_handling(true)
        .command("list", |_m, _ctx| Ok(Output::Render(json!({}))), "listed")
        .unwrap()
        .build()
        .unwrap()
}

/// The text `get_matches_from` renders for the same line, for agreement checks.
fn configured_help(app: &App, cmd: Command, args: &[&str]) -> String {
    match app.get_matches_from(cmd, args) {
        HelpResult::Help(h) | HelpResult::PagedHelp(h) => h,
        other => panic!("expected rendered help, got {other:?}"),
    }
}

// --- the word and the flags ------------------------------------------------

#[test]
#[serial]
fn the_help_word_renders_themed_help_through_run() {
    let result = TestHarness::new().text_output().run(
        &flat_app(true),
        flat_required_command(),
        ["app", "help"],
    );

    result.assert_success();
    assert_eq!(result.success_kind(), Some(SuccessKind::ClapHelp));
    result.assert_stdout_contains("Flat app");
    result.assert_stdout_contains("USAGE");
}

#[test]
#[serial]
fn the_help_flags_render_themed_help_through_run() {
    for flag in ["--help", "-h"] {
        let result = TestHarness::new().text_output().run(
            &flat_app(false),
            flat_required_command(),
            ["app", flag],
        );

        result.assert_success();
        assert_eq!(result.success_kind(), Some(SuccessKind::ClapHelp));
        // Rendered by standout, not handed back as Clap's own text: the root's
        // required group did not fire either way, but the header did not come
        // from Clap.
        result.assert_stdout_contains("USAGE");
    }
}

#[test]
#[serial]
fn the_help_word_renders_a_topic_through_run() {
    let result = TestHarness::new().text_output().run(
        &flat_app(true),
        flat_required_command(),
        ["app", "help", "ranges"],
    );

    result.assert_success();
    result.assert_stdout_contains("two revisions separated by two dots");
}

#[test]
#[serial]
fn the_help_word_renders_a_subcommands_help_through_run() {
    let app = subcommand_app();

    let word =
        TestHarness::new()
            .text_output()
            .run(&app, subcommand_command(), ["app", "help", "list"]);
    word.assert_success();
    word.assert_stdout_contains("List the things");
    drop(word);

    let flag =
        TestHarness::new()
            .text_output()
            .run(&app, subcommand_command(), ["app", "list", "--help"]);
    flag.assert_success();
    flag.assert_stdout_contains("List the things");
}

// --- the word's own arguments ----------------------------------------------

#[test]
#[serial]
fn the_help_word_honours_the_output_flag_through_run() {
    // The mode reaches the renderer: `term-debug` leaves style tags visible.
    let tagged = TestHarness::new().run(
        &flat_app(true),
        flat_required_command(),
        ["app", "help", "--output", "term-debug"],
    );
    tagged.assert_success();
    tagged.assert_stdout_contains("[header]USAGE[/header]");
    drop(tagged);

    // `json` is not a serialization of help — like every structured mode it
    // strips the style tags off the same rendered template.
    let json = TestHarness::new().run(
        &flat_app(true),
        flat_required_command(),
        ["app", "help", "--output", "json"],
    );
    json.assert_success();
    json.assert_stdout_contains("USAGE");
    assert!(
        !json.stdout().contains("[header]"),
        "structured modes strip style tags:\n{}",
        json.stdout()
    );
}

#[test]
#[serial]
fn the_output_flag_reaches_the_word_but_not_the_flags() {
    // A documented asymmetry (`docs/topics/standout-help.md`), pinned so the
    // doc cannot go stale quietly: the word is a subcommand, so clap parses its
    // line in full, globals included, while `--help` short-circuits before the
    // parse completes — so its render has no mode to honour and falls back to
    // `Auto`.
    let app = flat_app(true);

    let word = TestHarness::new().no_color().run(
        &app,
        flat_required_command(),
        ["app", "help", "--output", "term-debug"],
    );
    word.assert_stdout_contains("[header]USAGE[/header]");
    drop(word);

    let flag = TestHarness::new().no_color().run(
        &app,
        flat_required_command(),
        ["app", "--help", "--output", "term-debug"],
    );
    flag.assert_success();
    flag.assert_stdout_contains("USAGE");
    assert!(
        !flag.stdout().contains("[header]"),
        "`--help` renders in Auto, so the requested mode is not applied:\n{}",
        flag.stdout()
    );
}

#[test]
#[serial]
fn a_pager_request_rides_back_as_a_typed_success() {
    // `run()` is the only entry point that may spawn a pager, so the request
    // travels as a kind rather than as a side effect of capturing the text.
    let result = TestHarness::new().text_output().run(
        &flat_app(true),
        flat_required_command(),
        ["app", "help", "--page"],
    );

    result.assert_success();
    assert_eq!(result.success_kind(), Some(SuccessKind::PagedHelp));
    result.assert_stdout_contains("USAGE");
}

// --- which command the help request targets ---------------------------------

/// Root help carries the root's own `about`; a subcommand's help carries its
/// own, so this tells the two renderings apart.
fn assert_is_root_help(rendered: &str) {
    assert!(
        rendered.contains("Subcommand app"),
        "expected the root's help, got:\n{rendered}"
    );
}

#[test]
#[serial]
fn an_option_value_is_not_read_as_the_targeted_command() {
    // `--output-file-path` takes a value, so `list` is that value and the help
    // request is the root's. A walk that skipped every token starting with `-`
    // and took the next word would render `list`'s help here.
    let app = subcommand_app();
    let args = ["app", "--output-file-path", "list", "--help"];

    let dispatched = TestHarness::new().run(&app, subcommand_command(), args);
    dispatched.assert_success();
    assert_is_root_help(dispatched.stdout());
    drop(dispatched);

    // The two entry points share the walk, so they answer alike.
    assert_is_root_help(&configured_help(&app, subcommand_command(), &args));
}

#[test]
#[serial]
fn a_short_option_value_is_not_read_as_the_targeted_command() {
    let result = TestHarness::new().run(
        &subcommand_app(),
        subcommand_command(),
        ["app", "-f", "list", "--help"],
    );

    result.assert_success();
    assert_is_root_help(result.stdout());
}

#[test]
#[serial]
fn the_walk_stops_where_the_help_request_is() {
    // Help was asked for before any command was named, so it is the root's; a
    // walk that strode past the flag would answer `list`.
    for flag in ["--help", "-h"] {
        let result = TestHarness::new().run(
            &subcommand_app(),
            subcommand_command(),
            ["app", flag, "list"],
        );

        result.assert_success();
        assert_is_root_help(result.stdout());
    }
}

// --- a help that cannot be rendered is the app's bug, not the user's --------

/// A theme whose alias names a style that does not exist: rendering fails
/// validation. This is the shape a downstream app hits when it loads an
/// override stylesheet from a directory at runtime and the file is malformed.
fn broken_theme() -> Theme {
    Theme::new().add("header", "no-such-style")
}

fn app_with_a_broken_theme() -> App {
    App::builder()
        .help_handling(true)
        .theme(broken_theme())
        .command("list", |_m, _ctx| Ok(Output::Render(json!({}))), "listed")
        .unwrap()
        .build()
        .unwrap()
}

#[test]
#[serial]
fn a_help_that_cannot_be_rendered_is_not_a_usage_error() {
    // The user's line was fine; the application's theme was not. Reporting it
    // as `ClapUsage` would blame the line and exit with the usage status.
    for args in [
        &["app", "help"][..],
        &["app", "--help"][..],
        &["app", "-h"][..],
    ] {
        let result = TestHarness::new().run(&app_with_a_broken_theme(), subcommand_command(), args);

        result.assert_error();
        result.assert_error_kind(RunErrorKind::Render);
        result.assert_exit_status(ExitStatus::FAILURE);
        result.assert_error_contains("failed to render help");
    }
}

#[test]
#[serial]
fn a_render_failure_is_not_disguised_as_an_unrecognized_topic() {
    // `list` is a real command. A render failure used to be swallowed by the
    // `if let Ok` around each rendering step, so the request fell through to
    // "the subcommand or topic 'list' wasn't recognized" — a usage error, and
    // an untrue one.
    let result = TestHarness::new().run(
        &app_with_a_broken_theme(),
        subcommand_command(),
        ["app", "help", "list"],
    );

    result.assert_error();
    result.assert_error_kind(RunErrorKind::Render);
    result.assert_error_contains("failed to render help");
    assert!(
        !result
            .error()
            .unwrap_or_default()
            .contains("wasn't recognized"),
        "a broken theme is not an unknown topic: {:?}",
        result.error()
    );
}

// --- agreement between the two entry points --------------------------------

#[test]
#[serial]
fn both_entry_points_render_the_same_help() {
    let app = flat_app(true);

    for args in [
        ["app", "help", "--output", "text"],
        ["app", "--help", "--output", "text"],
    ] {
        let dispatched = TestHarness::new().run(&app, flat_required_command(), args);
        dispatched.assert_success();
        let configured = configured_help(&app, flat_required_command(), &args);
        assert_eq!(
            dispatched.stdout(),
            configured,
            "entry points disagree for {args:?}"
        );
    }
}

// --- the install policy is the command's shape, not the entry point ---------

#[test]
#[serial]
fn a_flat_command_keeps_the_word_as_data_through_run_without_the_opt_in() {
    // No opt-in, so nothing is installed and `help` is what it looks like on a
    // root whose positional is free text: data, reaching the handler.
    let result = TestHarness::new().text_output().run(
        &flat_app(false),
        flat_required_command(),
        ["app", "help"],
    );

    result.assert_success();
    result.assert_stdout_eq("range=help");
}

#[test]
#[serial]
fn the_escape_delivers_the_literal_word_through_run() {
    // No forced output mode here: the harness appends its `--output` flag to
    // the end of the line, and everything after `--` is a positional.
    let result = TestHarness::new().run(
        &flat_app(true),
        flat_required_command(),
        ["app", "--", "help"],
    );

    result.assert_success();
    result.assert_stdout_eq("range=help");
}

#[test]
#[serial]
fn a_normal_invocation_is_untouched_through_run() {
    let result = TestHarness::new().text_output().run(
        &flat_app(true),
        flat_required_command(),
        ["app", "main..HEAD"],
    );

    result.assert_success();
    result.assert_stdout_eq("range=main..HEAD");
}