standout-test 7.10.1

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
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
//! Integration tests for invocation-aware default-command resolution.
//!
//! The fixture app models the motivating policy: a naked invocation selects a
//! piped entry point (`add`, which reads stdin) when stdin is redirected, and
//! an interactive entry point (`list`) at a terminal. Everything else — explicit
//! commands, nested commands, help, version, invalid syntax — must be untouched
//! by that policy.
//!
//! All tests are `#[serial]` because the harness mutates process-global state
//! (the default stdin reader among them).

use clap::{Arg, ArgAction, Command};
use serde_json::json;
use serial_test::serial;
use standout::cli::{App, ExitStatus, HelpResult, Output, RunErrorKind, SuccessKind};
use standout_input::env::MockStdin;
use standout_input::{reset_default_stdin_reader, set_default_stdin_reader};
use standout_test::TestHarness;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::Arc;

/// The clap surface: a root with a global flag, two leaf commands, one nested
/// group, and one command clap knows but standout has no handler for.
fn app_command() -> Command {
    Command::new("app")
        .version("1.2.3")
        .arg(
            Arg::new("loud")
                .long("loud")
                .global(true)
                .action(ArgAction::SetTrue),
        )
        .subcommand(Command::new("list").alias("ls"))
        .subcommand(Command::new("add"))
        .subcommand(Command::new("db").subcommand(Command::new("migrate")))
        .subcommand(Command::new("unhandled"))
}

/// Registers handlers for every command except `unhandled`, which exercises the
/// partial-adoption `NoMatch` path.
fn register(builder: App) -> App {
    builder
        .command(
            "list",
            |m, _ctx| {
                Ok(Output::Render(json!({
                    "cmd": "list",
                    "loud": m.get_flag("loud"),
                })))
            },
            "{{ cmd }} loud={{ loud }}",
        )
        .unwrap()
        .command(
            "add",
            |m, _ctx| {
                // The resolver never reads stdin; the handler still can.
                use standout_input::env::{DefaultStdin, StdinReader};
                let piped = DefaultStdin.read_to_string().unwrap_or_default();
                Ok(Output::Render(json!({
                    "cmd": "add",
                    "stdin": piped.trim(),
                    "loud": m.get_flag("loud"),
                })))
            },
            "{{ cmd }} stdin={{ stdin }} loud={{ loud }}",
        )
        .unwrap()
        .command(
            "db.migrate",
            |_m, _ctx| Ok(Output::Render(json!({ "cmd": "db.migrate" }))),
            "{{ cmd }}",
        )
        .unwrap()
}

/// The app under test: piped stdin means `add`, a terminal means `list`.
fn piped_aware_app() -> App {
    register(App::builder().default_command_with(|ctx| {
        Some(if ctx.stdin_is_piped() { "add" } else { "list" }.to_string())
    }))
    .build()
    .unwrap()
}

/// Like [`piped_aware_app`], but the resolver records how many times it ran so
/// tests can assert it stayed out of paths it must not touch.
fn counting_app(calls: Arc<AtomicUsize>) -> App {
    register(App::builder().default_command_with(move |ctx| {
        calls.fetch_add(1, Ordering::SeqCst);
        Some(if ctx.stdin_is_piped() { "add" } else { "list" }.to_string())
    }))
    .build()
    .unwrap()
}

// --- the invocation facts -------------------------------------------------

#[test]
#[serial]
fn terminal_stdin_selects_the_interactive_command() {
    let result =
        TestHarness::new()
            .interactive_stdin()
            .run(&piped_aware_app(), app_command(), ["app"]);

    result.assert_success();
    result.assert_stdout_eq("list loud=false");
}

#[test]
#[serial]
fn piped_stdin_with_data_selects_the_piped_command() {
    let result = TestHarness::new().piped_stdin("ship the docs\n").run(
        &piped_aware_app(),
        app_command(),
        ["app"],
    );

    result.assert_success();
    result.assert_stdout_eq("add stdin=ship the docs loud=false");
}

#[test]
#[serial]
fn piped_but_empty_stdin_still_selects_the_piped_command() {
    // The distinguishing fact is "stdin is not a terminal", which is knowable
    // without reading. Emptiness is the handler's business, not the resolver's.
    let result = TestHarness::new()
        .piped_stdin("")
        .run(&piped_aware_app(), app_command(), ["app"]);

    result.assert_success();
    result.assert_stdout_eq("add stdin= loud=false");
}

#[test]
#[serial]
fn globals_survive_the_resolved_default() {
    let result = TestHarness::new().interactive_stdin().run(
        &piped_aware_app(),
        app_command(),
        ["app", "--loud"],
    );

    result.assert_success();
    result.assert_stdout_eq("list loud=true");
}

#[test]
#[serial]
fn resolver_reads_root_matches_and_app_state() {
    struct Fallback(&'static str);

    let app = register(
        App::builder()
            .app_state(Fallback("add"))
            .default_command_with(|ctx| {
                if ctx.matches().get_flag("loud") {
                    return Some("list".to_string());
                }
                ctx.app_state::<Fallback>().map(|f| f.0.to_string())
            }),
    )
    .build()
    .unwrap();

    let from_flag =
        TestHarness::new()
            .interactive_stdin()
            .run(&app, app_command(), ["app", "--loud"]);
    from_flag.assert_stdout_eq("list loud=true");
    drop(from_flag);

    let from_state = TestHarness::new()
        .interactive_stdin()
        .run(&app, app_command(), ["app"]);
    from_state.assert_stdout_eq("add stdin= loud=false");
}

// --- what resolution must never touch -------------------------------------

#[test]
#[serial]
fn a_naked_invocation_runs_the_resolver_once() {
    // The positive control for every `calls == 0` assertion below: the counting
    // fixture does increment when resolution is supposed to happen.
    let calls = Arc::new(AtomicUsize::new(0));
    let result = TestHarness::new().interactive_stdin().run(
        &counting_app(calls.clone()),
        app_command(),
        ["app"],
    );

    result.assert_stdout_eq("list loud=false");
    assert_eq!(calls.load(Ordering::SeqCst), 1);
}

#[test]
#[serial]
fn an_explicit_command_takes_precedence() {
    let calls = Arc::new(AtomicUsize::new(0));
    let result = TestHarness::new().piped_stdin("would have meant add").run(
        &counting_app(calls.clone()),
        app_command(),
        ["app", "list"],
    );

    result.assert_success();
    result.assert_stdout_eq("list loud=false");
    assert_eq!(calls.load(Ordering::SeqCst), 0, "resolver must not run");
}

#[test]
#[serial]
fn a_nested_command_takes_precedence() {
    let calls = Arc::new(AtomicUsize::new(0));
    let result = TestHarness::new().piped_stdin("data").run(
        &counting_app(calls.clone()),
        app_command(),
        ["app", "db", "migrate"],
    );

    result.assert_success();
    result.assert_stdout_eq("db.migrate");
    assert_eq!(calls.load(Ordering::SeqCst), 0, "resolver must not run");
}

#[test]
#[serial]
fn help_is_unchanged() {
    let calls = Arc::new(AtomicUsize::new(0));
    let result = TestHarness::new().piped_stdin("data").run(
        &counting_app(calls.clone()),
        app_command(),
        ["app", "--help"],
    );

    assert_eq!(result.success_kind(), Some(SuccessKind::ClapHelp));
    result.assert_stdout_contains("Usage:");
    assert_eq!(calls.load(Ordering::SeqCst), 0, "resolver must not run");
}

#[test]
#[serial]
fn version_is_unchanged() {
    let calls = Arc::new(AtomicUsize::new(0));
    let result = TestHarness::new().piped_stdin("data").run(
        &counting_app(calls.clone()),
        app_command(),
        ["app", "--version"],
    );

    assert_eq!(result.success_kind(), Some(SuccessKind::ClapVersion));
    result.assert_stdout_contains("1.2.3");
    assert_eq!(calls.load(Ordering::SeqCst), 0, "resolver must not run");
}

#[test]
#[serial]
fn invalid_syntax_stays_a_clap_usage_error() {
    let calls = Arc::new(AtomicUsize::new(0));
    let result = TestHarness::new().piped_stdin("data").run(
        &counting_app(calls.clone()),
        app_command(),
        ["app", "--nonexistent"],
    );

    result.assert_error();
    result.assert_error_kind(RunErrorKind::ClapUsage);
    assert_eq!(
        calls.load(Ordering::SeqCst),
        0,
        "resolution runs only after a successful naked parse"
    );
}

// --- interaction with the static default ----------------------------------

#[test]
#[serial]
fn a_static_default_still_applies_on_its_own() {
    let app = register(App::builder().default_command("list"))
        .build()
        .unwrap();

    let result = TestHarness::new()
        .piped_stdin("ignored — no resolver configured")
        .run(&app, app_command(), ["app"]);

    result.assert_success();
    result.assert_stdout_eq("list loud=false");
}

#[test]
#[serial]
fn a_declining_resolver_falls_back_to_the_static_default() {
    let app = register(
        App::builder()
            .default_command("list")
            .default_command_with(|ctx| ctx.stdin_is_piped().then(|| "add".to_string())),
    )
    .build()
    .unwrap();

    let piped = TestHarness::new()
        .piped_stdin("payload")
        .run(&app, app_command(), ["app"]);
    piped.assert_stdout_eq("add stdin=payload loud=false");
    drop(piped);

    // Resolver declines at a terminal, so the static default takes over.
    let terminal = TestHarness::new()
        .interactive_stdin()
        .run(&app, app_command(), ["app"]);
    terminal.assert_stdout_eq("list loud=false");
}

#[test]
#[serial]
fn no_default_configured_leaves_a_naked_invocation_alone() {
    let app = register(App::builder()).build().unwrap();

    let result = TestHarness::new()
        .interactive_stdin()
        .run(&app, app_command(), ["app"]);

    result.assert_no_match();
}

// --- partial adoption -----------------------------------------------------

#[test]
#[serial]
fn resolving_to_a_command_standout_does_not_handle_reports_no_match() {
    // `unhandled` is a real clap command with no standout handler: resolution
    // succeeds and dispatch hands back cleanly for the app to handle.
    let app = register(App::builder().default_command_with(|_ctx| Some("unhandled".to_string())))
        .build()
        .unwrap();

    let result = TestHarness::new()
        .interactive_stdin()
        .run(&app, app_command(), ["app"]);

    result.assert_no_match();
}

#[test]
#[serial]
fn resolving_to_an_unknown_command_is_a_typed_error_not_a_panic() {
    let app = register(App::builder().default_command_with(|_ctx| Some("nope".to_string())))
        .build()
        .unwrap();

    let result = TestHarness::new()
        .interactive_stdin()
        .run(&app, app_command(), ["app"]);

    result.assert_error();
    result.assert_error_kind(RunErrorKind::DefaultCommand);
    // The diagnostic blames the resolver, not the user's command line.
    result.assert_error_contains("default command resolver returned `nope`");
    result.assert_exit_status(ExitStatus::FAILURE);
}

#[test]
#[serial]
fn get_matches_from_reports_an_unknown_command_as_a_clap_error() {
    let app = register(App::builder().default_command_with(|_ctx| Some("nope".to_string())))
        .build()
        .unwrap();

    with_stdin(MockStdin::terminal(), || {
        match app.get_matches_from(app_command(), ["app"]) {
            HelpResult::Error(e) => assert!(
                e.to_string()
                    .contains("default command resolver returned `nope`"),
                "{e}"
            ),
            other => panic!("expected a clap error, got {other:?}"),
        }
    });
}

// --- the configured parsing path ------------------------------------------

/// Runs `body` with the process-global stdin reader mocked, then restores it.
///
/// The `TestHarness` owns this seam for `run()`; `get_matches_from` is a
/// parse-only path with no harness entry point, so these tests drive the same
/// override directly.
struct StdinGuard;

impl StdinGuard {
    fn install(reader: MockStdin) -> Self {
        set_default_stdin_reader(Arc::new(reader));
        Self
    }
}

impl Drop for StdinGuard {
    fn drop(&mut self) {
        reset_default_stdin_reader();
    }
}

fn with_stdin<R>(reader: MockStdin, body: impl FnOnce() -> R) -> R {
    let _guard = StdinGuard::install(reader);
    body()
}

#[test]
#[serial]
fn get_matches_from_resolves_the_same_default_as_dispatch() {
    // Consumers that parse first and build dispatch state afterwards must see
    // the command a naked `run()` would have selected.
    let app = piped_aware_app();

    with_stdin(MockStdin::terminal(), || {
        match app.get_matches_from(app_command(), ["app"]) {
            HelpResult::Matches(m) => assert_eq!(m.subcommand_name(), Some("list")),
            other => panic!("expected matches, got {other:?}"),
        }
    });

    with_stdin(MockStdin::piped("payload"), || {
        match app.get_matches_from(app_command(), ["app"]) {
            HelpResult::Matches(m) => assert_eq!(m.subcommand_name(), Some("add")),
            other => panic!("expected matches, got {other:?}"),
        }
    });

    // Piped-but-empty is a pipe here too — same answer, no read.
    with_stdin(MockStdin::piped_empty(), || {
        match app.get_matches_from(app_command(), ["app"]) {
            HelpResult::Matches(m) => assert_eq!(m.subcommand_name(), Some("add")),
            other => panic!("expected matches, got {other:?}"),
        }
    });
}

#[test]
#[serial]
fn get_matches_from_leaves_invalid_syntax_a_clap_error() {
    let app = piped_aware_app();

    with_stdin(MockStdin::piped("data"), || {
        match app.get_matches_from(app_command(), ["app", "--nonexistent"]) {
            HelpResult::Error(_) => {}
            other => panic!("expected a clap error, got {other:?}"),
        }
    });
}

#[test]
#[serial]
fn get_matches_from_applies_a_static_default() {
    let app = register(App::builder().default_command("list"))
        .build()
        .unwrap();

    match app.get_matches_from(app_command(), ["app", "--loud"]) {
        HelpResult::Matches(m) => {
            assert_eq!(m.subcommand_name(), Some("list"));
            assert!(m.get_flag("loud"));
        }
        other => panic!("expected matches, got {other:?}"),
    }
}

#[test]
#[serial]
fn get_matches_from_leaves_explicit_and_nested_commands_alone() {
    let app = piped_aware_app();

    match app.get_matches_from(app_command(), ["app", "db", "migrate"]) {
        HelpResult::Matches(m) => {
            let (name, sub) = m.subcommand().expect("db");
            assert_eq!(name, "db");
            assert_eq!(sub.subcommand_name(), Some("migrate"));
        }
        other => panic!("expected matches, got {other:?}"),
    }
}