Skip to content

Commit cffeede

Browse files
committed
CI: tighten scan test review findings
- Drop the moved mode_fold tests: cli_parse_scan.rs already runs resolve_mode_flags on --mode hosted/vendored --sync, and they mutated process env inside the shared scan binary. cli_parse_scan.rs now also requires the error to name the mode. - The vendored-skip JSON test requires the one skipped event coded vendored, and the human retained-wiring check reads the warning line. - The global-scope usage error checks the envelope invariants. - Reuse vlt_hosted_common::warning_detail, share the mock-API flags between the subprocess and PTY runners, and drop the PTY runner's unused typeahead path. Assisted-by: Claude Code:claude-opus-5-5
1 parent ecca6c1 commit cffeede

5 files changed

Lines changed: 42 additions & 147 deletions

File tree

‎crates/socket-patch-cli/tests/cli_parse_scan.rs‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -622,7 +622,10 @@ fn mode_hosted_with_sync_errors() {
622622
for mode in ["hosted", "vendored"] {
623623
let mut args = parse_scan(&["--mode", mode, "--sync"]);
624624
let err = resolve_mode_flags(&mut args).expect_err("cross-mode --sync");
625-
assert!(err.contains("cannot be used with --sync"), "{err}");
625+
assert!(
626+
err.contains(&format!("--mode {mode} cannot be used with --sync")),
627+
"the error names the mode through cli_name(): {err}"
628+
);
626629
}
627630
}
628631

‎crates/socket-patch-cli/tests/scan/scan_failure_paths.rs‎

Lines changed: 18 additions & 88 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
//! purl, a file). The human output of the same paths is pinned in
66
//! `scan_render.rs`.
77
//!
8-
//! 1. `resolve_mode_flags`' cross-mode conflicts and the early errors;
8+
//! 1. the early errors (`--offline`, usage errors);
99
//! 2. hosted `--prune` and the paid-tier counters;
1010
//! 3. detail-fetch failures (total and partial) and empty detail answers;
1111
//! 4. vendor-owned purls, report-only runs and the `--sync` GC;
@@ -25,19 +25,6 @@ use crate::common::envelope::{
2525
use crate::scan_fixture::*;
2626
use crate::{vlt_hosted_common as hosted, vlt_vendored};
2727

28-
/// The first `warnings[]` entry with `code`; panics with the envelope when
29-
/// there is none.
30-
fn warning<'a>(v: &'a serde_json::Value, code: &str) -> &'a serde_json::Value {
31-
v["warnings"]
32-
.as_array()
33-
.and_then(|ws| ws.iter().find(|w| w["code"] == code))
34-
.unwrap_or_else(|| panic!("warnings[] must carry {code}: {v:#}"))
35-
}
36-
37-
fn warning_detail<'a>(v: &'a serde_json::Value, code: &str) -> &'a str {
38-
warning(v, code)["detail"].as_str().unwrap_or_default()
39-
}
40-
4128
/// `scan --json` against the mock API; returns the exit code and the parsed
4229
/// envelope (after checking the shared envelope invariants).
4330
fn run_json(cwd: &Path, api_url: &str, extra: &[&str]) -> (i32, serde_json::Value) {
@@ -53,67 +40,6 @@ fn run_json(cwd: &Path, api_url: &str, extra: &[&str]) -> (i32, serde_json::Valu
5340
(code, v)
5441
}
5542

56-
// ---------------------------------------------------------------------------
57-
// resolve_mode_flags: the `--sync` cross-mode conflict
58-
// ---------------------------------------------------------------------------
59-
// `--sync` means `--mode agent --prune`, so it contradicts any other
60-
// `--mode`. Clap parses each combination fine (no value-dependent conflict
61-
// is expressible); the fold is what rejects them, naming both flags.
62-
63-
mod mode_fold {
64-
use clap::Parser;
65-
use socket_patch_cli::commands::scan::{resolve_mode_flags, ScanArgs};
66-
use socket_patch_cli::{Cli, Commands};
67-
68-
/// Every env var that could reroute the parse or the fold (superset:
69-
/// the shared scrub lists from `args.rs`).
70-
fn with_clean_env<T>(f: impl FnOnce() -> T) -> T {
71-
let vars: Vec<&str> = socket_patch_cli::args::GLOBAL_ARG_ENV_VARS
72-
.iter()
73-
.chain(socket_patch_cli::args::LOCAL_ARG_ENV_VARS.iter())
74-
.copied()
75-
.collect();
76-
let saved: Vec<(&str, Option<String>)> =
77-
vars.iter().map(|k| (*k, std::env::var(k).ok())).collect();
78-
for k in &vars {
79-
std::env::remove_var(k);
80-
}
81-
let result = f();
82-
for (k, orig) in saved {
83-
match orig {
84-
Some(v) => std::env::set_var(k, v),
85-
None => std::env::remove_var(k),
86-
}
87-
}
88-
result
89-
}
90-
91-
fn fold_err(extra: &[&str]) -> String {
92-
let mut argv = vec!["socket-patch", "scan"];
93-
argv.extend_from_slice(extra);
94-
let cli = with_clean_env(|| Cli::try_parse_from(&argv)).expect("parse");
95-
let mut args: ScanArgs = match cli.command {
96-
Commands::Scan(a) => a,
97-
_ => panic!("expected Scan"),
98-
};
99-
resolve_mode_flags(&mut args).expect_err("cross-mode contradiction must error")
100-
}
101-
102-
/// Each `--mode` against `--sync` errors, naming the mode through
103-
/// `cli_name()` and the conflicting boolean.
104-
#[test]
105-
#[serial_test::serial]
106-
fn mode_with_sync_boolean_errors_naming_both_flags() {
107-
for mode in ["hosted", "vendored"] {
108-
let err = fold_err(&["--mode", mode, "--sync"]);
109-
assert!(
110-
err.contains(&format!("--mode {mode}")) && err.contains("--sync"),
111-
"the error must name --mode {mode} and --sync: {err}"
112-
);
113-
}
114-
}
115-
}
116-
11743
/// `--offline` and usage errors print the full envelope too.
11844
#[test]
11945
fn scan_json_early_errors_print_full_envelopes() {
@@ -145,6 +71,7 @@ fn scan_hosted_global_json_is_global_scope_unsupported() {
14571
let (code, stdout, _) = run_scan(tmp.path(), &["--mode", "hosted", "--global", "--json"]);
14672
assert_eq!(code, 2, "{stdout}");
14773
let v = parse_json_envelope(&stdout);
74+
assert_envelope_invariants(&v, "scan");
14875
assert_eq!(v["status"], "error", "{v}");
14976
assert_eq!(
15077
envelope_error_code(&v),
@@ -179,7 +106,7 @@ async fn scan_hosted_prune_zero_package_json_carries_the_warning() {
179106
assert_eq!(v["redirect"]["mode"], "hosted");
180107
assert_eq!(v["summary"]["applied"], 0, "nothing pinned: {v}");
181108
assert!(
182-
warning_detail(&v, "redirect_prune_ignored").contains("--prune"),
109+
hosted::warning_detail(&v, "redirect_prune_ignored").contains("--prune"),
183110
"the warning must name the ignored flag: {v:#}"
184111
);
185112
assert!(
@@ -372,7 +299,7 @@ async fn scan_partial_failure_with_empty_results_exits_alike() {
372299
let tmp = project();
373300
let (json, v) = run_json(tmp.path(), &mock.uri(), &extra);
374301
assert!(
375-
warning_detail(&v, "patch_details_failed").contains(bad),
302+
hosted::warning_detail(&v, "patch_details_failed").contains(bad),
376303
"{v:#}"
377304
);
378305
assert_eq!(human, json, "human and --json exit alike: {stderr}\n{v:#}");
@@ -382,8 +309,8 @@ async fn scan_partial_failure_with_empty_results_exits_alike() {
382309
// Vendor-owned purls, report-only runs and the GC
383310
// ---------------------------------------------------------------------------
384311

385-
/// A purl the vendored ledger owns is skipped by an agent-mode scan: no
386-
/// download, no manifest, and no apply event for it.
312+
/// A purl the vendored ledger owns is skipped by an agent-mode scan: one
313+
/// `skipped` event coded `vendored`, no download and no manifest.
387314
#[tokio::test]
388315
async fn scan_agent_json_skips_vendored_purls_without_downloading() {
389316
let mock = MockServer::start().await;
@@ -394,11 +321,14 @@ async fn scan_agent_json_skips_vendored_purls_without_downloading() {
394321

395322
let (code, v) = run_json(tmp.path(), &mock.uri(), &["--mode", "agent", "--yes"]);
396323
assert_eq!(code, 0, "{v:#}");
397-
assert!(
398-
!event_triples(&v)
399-
.iter()
400-
.any(|(purl, action, _)| purl == MINIMIST && action != "skipped"),
401-
"a vendor-owned purl is only ever skipped: {v:#}"
324+
assert_eq!(
325+
event_triples(&v)
326+
.into_iter()
327+
.filter(|(purl, _, _)| purl == MINIMIST)
328+
.map(|(_, action, code)| (action, code))
329+
.collect::<Vec<_>>(),
330+
[("skipped".to_string(), "vendored".to_string())],
331+
"a vendor-owned purl is only skipped, with the `vendored` code: {v:#}"
402332
);
403333
assert_eq!(v["summary"]["applied"], 0, "{v:#}");
404334
assert_eq!(view_gets(&recorded(&mock).await), 0, "{v:#}");
@@ -646,7 +576,7 @@ async fn scan_agent_json_mismatch_overwrite_reaches_the_apply_block() {
646576
let (code, v) = run_json(tmp.path(), &mock.uri(), &["--mode", "agent"]);
647577
assert_eq!(code, 0, "{v:#}");
648578
assert_eq!(v["summary"]["applied"], 1, "{v}");
649-
let detail = warning_detail(&v, "content_mismatch_overwritten");
579+
let detail = hosted::warning_detail(&v, "content_mismatch_overwritten");
650580
assert!(
651581
detail.contains(purl) && detail.contains("package/index.js"),
652582
"the overwrite must name the purl and the file: {v:#}"
@@ -674,7 +604,7 @@ async fn scan_agent_json_over_live_hosted_wiring_warns_retained() {
674604
let (code, v) = run_json(tmp.path(), &mock.uri(), &["--mode", "agent", "--yes"]);
675605
assert_eq!(code, 0, "{v:#}");
676606
assert!(
677-
warning_detail(&v, "hosted_wiring_retained").contains(SILENT_TARGET),
607+
hosted::warning_detail(&v, "hosted_wiring_retained").contains(SILENT_TARGET),
678608
"the warning names the package: {v:#}"
679609
);
680610
assert_eq!(event_purls(&v, "applied"), [SILENT_TARGET], "{v:#}");
@@ -756,7 +686,7 @@ fn scan_invalid_bun_lockb_warns_instead_of_silent_success() {
756686
assert_eq!(v["scannedPackages"], 0, "mode={mode:?}: {v}");
757687
assert_eq!(v["lockfileOnlyPackages"], 0, "mode={mode:?}: {v}");
758688
assert!(
759-
warning_detail(&v, "bun_lockb_invalid").contains("bun.lockb"),
689+
hosted::warning_detail(&v, "bun_lockb_invalid").contains("bun.lockb"),
760690
"mode={mode:?}: the format error must name its file: {v:#}"
761691
);
762692
assert!(
@@ -786,7 +716,7 @@ async fn scan_nonempty_keeps_the_bun_lockb_discovery_warning_in_every_mode() {
786716
assert_eq!(v["scannedPackages"], 1, "mode={mode:?}: {v}");
787717
assert_eq!(v["status"], "success", "mode={mode:?}: {v}");
788718
assert!(
789-
warning_detail(&v, "bun_lockb_invalid").contains("bun.lockb"),
719+
hosted::warning_detail(&v, "bun_lockb_invalid").contains("bun.lockb"),
790720
"mode={mode:?}: {v:#}"
791721
);
792722
}

‎crates/socket-patch-cli/tests/scan/scan_fixture.rs‎

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -68,16 +68,21 @@ pub fn run_scan(cwd: &Path, args: &[&str]) -> (i32, String, String) {
6868
/// [`run_scan`] against a mock API (human output unless `extra` has
6969
/// `--json`).
7070
pub fn run_scan_api(cwd: &Path, api_url: &str, extra: &[&str]) -> (i32, String, String) {
71-
let mut args = vec![
71+
let mut args = api_args(api_url);
72+
args.extend_from_slice(extra);
73+
run_scan(cwd, &args)
74+
}
75+
76+
/// The flags pointing a run at the mock API with a fake token and org.
77+
pub fn api_args(api_url: &str) -> Vec<&str> {
78+
vec![
7279
"--api-url",
7380
api_url,
7481
"--api-token",
7582
"fake-token-for-test",
7683
"--org",
7784
ORG_SLUG,
78-
];
79-
args.extend_from_slice(extra);
80-
run_scan(cwd, &args)
85+
]
8186
}
8287

8388
/// [`run_scan_api`] in agent mode: v5's bare scan is hosted, and these

‎crates/socket-patch-cli/tests/scan/scan_render.rs‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -985,8 +985,8 @@ async fn scan_human_apply_over_live_hosted_wiring_warns_retained() {
985985
.find(|l| l.starts_with("Warning: agent-mode scan left the hosted wiring live"))
986986
.unwrap_or_else(|| panic!("the retained-wiring warning must reach stderr; got {stderr:?}"));
987987
assert!(
988-
stderr.contains(SILENT_TARGET),
989-
"the warning must name the package; got {warning:?}\n{stderr:?}"
988+
warning.contains(SILENT_TARGET),
989+
"the warning must name the package; got {warning:?}"
990990
);
991991
assert_eq!(
992992
std::fs::read(tmp.path().join("node_modules/silent-target/index.js")).unwrap(),

‎crates/socket-patch-cli/tests/scan/scan_tty.rs‎

Lines changed: 9 additions & 52 deletions
Original file line numberDiff line numberDiff line change
@@ -16,17 +16,14 @@ use crate::scan_fixture::*;
1616
/// until exit (the `interactive_prompts_e2e.rs` harness pattern:
1717
/// reader thread + kill-after-timeout watchdog, no polling).
1818
fn run_in_pty(args: &[&str], cwd: &Path, input: &str, timeout: Duration) -> (i32, String) {
19-
run_in_pty_with(args, cwd, &[], "", input, timeout)
19+
run_in_pty_with(args, cwd, &[], input, timeout)
2020
}
2121

22-
/// [`run_in_pty`] with extra child `env`, first writing `typeahead`
23-
/// straight after spawn — keystrokes a user types while the scan is
24-
/// still running, before any prompt is on screen.
22+
/// [`run_in_pty`] with extra child `env`.
2523
fn run_in_pty_with(
2624
args: &[&str],
2725
cwd: &Path,
2826
env: &[(&str, &str)],
29-
typeahead: &str,
3027
input: &str,
3128
timeout: Duration,
3229
) -> (i32, String) {
@@ -67,11 +64,6 @@ fn run_in_pty_with(
6764
});
6865

6966
let mut writer = pair.master.take_writer().expect("take writer");
70-
if !typeahead.is_empty() {
71-
use std::io::Write as _;
72-
let _ = writer.write_all(typeahead.as_bytes());
73-
let _ = writer.flush();
74-
}
7567
crate::pty_io::send_when_prompted(&reader_handle, &mut writer, input.as_bytes());
7668
drop(writer);
7769

@@ -102,17 +94,7 @@ async fn scan_on_a_tty_applies_without_prompting() {
10294
let cwd = tmp.path().to_path_buf();
10395
let (code, output) = tokio::task::spawn_blocking(move || {
10496
run_in_pty(
105-
&[
106-
"scan",
107-
"--mode",
108-
"agent",
109-
"--api-url",
110-
&uri,
111-
"--api-token",
112-
"fake-token-for-test",
113-
"--org",
114-
ORG_SLUG,
115-
],
97+
&[&["scan", "--mode", "agent"][..], &api_args(&uri)].concat(),
11698
&cwd,
11799
"",
118100
Duration::from_secs(60),
@@ -171,18 +153,10 @@ async fn scan_json_on_a_tty_never_opens_the_select_menu() {
171153
let (code, output) = tokio::task::spawn_blocking(move || {
172154
run_in_pty(
173155
&[
174-
"scan",
175-
"--json",
176-
"--mode",
177-
"agent",
178-
"--dry-run",
179-
"--api-url",
180-
&uri,
181-
"--api-token",
182-
"fake-token-for-test",
183-
"--org",
184-
ORG_SLUG,
185-
],
156+
&["scan", "--json", "--mode", "agent", "--dry-run"][..],
157+
&api_args(&uri),
158+
]
159+
.concat(),
186160
&cwd,
187161
"",
188162
Duration::from_secs(30),
@@ -230,15 +204,7 @@ async fn scan_progress_on_a_tty_renders_without_stale_tail() {
230204
let cwd = tmp.path().to_path_buf();
231205
let (code, output) = tokio::task::spawn_blocking(move || {
232206
run_in_pty(
233-
&[
234-
"scan",
235-
"--api-url",
236-
&uri,
237-
"--api-token",
238-
"fake-token-for-test",
239-
"--org",
240-
ORG_SLUG,
241-
],
207+
&[&["scan"][..], &api_args(&uri)].concat(),
242208
&cwd,
243209
"n\n",
244210
Duration::from_secs(60),
@@ -295,18 +261,9 @@ async fn scan_debug_mode_on_a_tty_keeps_debug_lines_off_the_status() {
295261
let cwd = tmp.path().to_path_buf();
296262
let (code, output) = tokio::task::spawn_blocking(move || {
297263
run_in_pty_with(
298-
&[
299-
"scan",
300-
"--api-url",
301-
&uri,
302-
"--api-token",
303-
"fake-token-for-test",
304-
"--org",
305-
ORG_SLUG,
306-
],
264+
&[&["scan"][..], &api_args(&uri)].concat(),
307265
&cwd,
308266
&[("SOCKET_DEBUG", "1")],
309-
"",
310267
"n\n",
311268
Duration::from_secs(60),
312269
)

0 commit comments

Comments
 (0)