1use crate::emsg;
15use bynk_project::env_protocol;
16use std::path::{Path, PathBuf};
17use std::process::{Command as ProcCommand, ExitCode, Stdio};
18
19use crate::project::{BuildTarget, ImportExt, ProjectOutput};
20use clap::ValueEnum;
21
22use crate::npm_install::PackageManager;
23use crate::test_json::{Case, Location, Suite, TestRun};
24
25#[derive(Copy, Clone, Debug, PartialEq, Eq, Default, ValueEnum)]
29pub enum TestFormat {
30 #[default]
32 Rich,
33 Json,
35 Ndjson,
38}
39
40#[derive(clap::Args, Debug, Clone)]
45pub struct TestArgs {
46 #[arg(default_value = ".")]
48 pub input: PathBuf,
49 #[arg(long)]
58 pub each: bool,
59 #[arg(short, long)]
62 pub output: Option<PathBuf>,
63 #[arg(long)]
69 pub no_run: bool,
70 #[arg(long)]
74 pub require_tests: bool,
75 #[arg(long, value_enum, default_value_t = TestFormat::Rich)]
81 pub format: TestFormat,
82 #[arg(long)]
89 pub inspect: bool,
90 #[arg(long)]
95 pub seed: Option<String>,
96 #[arg(long, value_name = "NAME")]
104 pub case: Vec<String>,
105 #[arg(long, value_name = "NAME")]
111 pub suite: Vec<String>,
112 #[arg(long, hide = true)]
117 pub partial_selection: bool,
118 #[arg(long)]
123 pub coverage: bool,
124 #[arg(long, value_name = "TARGET")]
133 pub against: Option<String>,
134 #[arg(long, requires = "against")]
137 pub skip_unsupported: bool,
138 #[arg(
144 long,
145 value_name = "DURATION",
146 requires = "against",
147 default_value = "5s"
148 )]
149 pub settle: Option<String>,
150 #[arg(long)]
158 pub smoke: bool,
159 #[arg(long, requires = "smoke")]
162 pub print: bool,
163 #[arg(long, requires = "smoke")]
168 pub smoke_unsafe: bool,
169 #[arg(long)]
174 pub no_install: bool,
175 #[arg(long)]
183 pub update_snapshots: bool,
184 #[arg(skip)]
189 pub declared_statuses: Option<PathBuf>,
190 #[arg(skip)]
195 pub dev_command: Option<PathBuf>,
196 #[arg(long)]
205 pub mutate: bool,
206 #[arg(long, value_name = "DECL", requires = "mutate")]
209 pub only: Option<String>,
210 #[arg(long, value_name = "N", requires = "mutate")]
212 pub max_mutants: Option<usize>,
213 #[arg(long, value_name = "SECONDS", requires = "mutate")]
217 pub mutate_timeout: Option<u64>,
218 #[arg(long, requires = "mutate")]
221 pub mutate_all_suites: bool,
222 #[arg(long, value_name = "PERCENT", requires = "mutate")]
226 pub mutate_fail_under: Option<u32>,
227 #[arg(long, value_name = "GIT_REF", requires = "mutate")]
232 pub changed: Option<String>,
233 #[arg(
237 long,
238 value_name = "N",
239 requires = "mutate",
240 value_parser = clap::value_parser!(u64).range(1..=256)
241 )]
242 pub mutate_jobs: Option<u64>,
243 #[arg(skip)]
247 pub mutant_overlay: Option<(PathBuf, String)>,
248 #[arg(skip)]
250 pub run_timeout: Option<std::time::Duration>,
251 #[arg(skip)]
256 pub overlay: Option<std::collections::HashMap<PathBuf, String>>,
257}
258
259impl TestArgs {
260 pub(crate) fn discovery(input: PathBuf) -> Self {
262 TestArgs {
263 input,
264 each: false,
265 output: None,
266 no_run: true,
267 require_tests: false,
268 format: TestFormat::Json,
269 inspect: false,
270 seed: None,
271 case: Vec::new(),
272 suite: Vec::new(),
273 partial_selection: false,
274 coverage: false,
275 against: None,
276 skip_unsupported: false,
277 settle: None,
278 smoke: false,
279 print: false,
280 smoke_unsafe: false,
281 no_install: false,
282 update_snapshots: false,
283 declared_statuses: None,
284 dev_command: None,
285 mutate: false,
286 only: None,
287 max_mutants: None,
288 mutate_timeout: None,
289 mutate_all_suites: false,
290 mutate_fail_under: None,
291 changed: None,
292 mutate_jobs: None,
293 mutant_overlay: None,
294 run_timeout: None,
295 overlay: None,
296 }
297 }
298}
299
300pub fn discover_cases(program: &str, members: &[PathBuf]) -> Option<Vec<(String, String)>> {
305 let mut available = Vec::new();
306 for member in members {
307 let (_, text) =
308 crate::test_stream::capture(|| run_test(program, TestArgs::discovery(member.clone())));
309 let doc: serde_json::Value = serde_json::from_str(&text).ok()?;
310 if doc.get("error").is_some() {
311 return None;
312 }
313 for suite in doc.get("suites")?.as_array()? {
314 let name = suite.get("name")?.as_str()?;
315 for case in suite.get("cases")?.as_array()? {
316 available.push((name.to_string(), case.get("name")?.as_str()?.to_string()));
317 }
318 }
319 }
320 Some(available)
321}
322
323fn output_root_for(input: &Path, output: Option<&Path>) -> PathBuf {
325 output.map_or_else(|| input.join("out"), Path::to_path_buf)
326}
327
328fn normalise_seed(raw: &str) -> Option<String> {
333 let hex = raw
334 .strip_prefix("0x")
335 .or_else(|| raw.strip_prefix("0X"))
336 .unwrap_or(raw);
337 if hex.is_empty() || !hex.chars().all(|c| c.is_ascii_hexdigit()) {
338 return None;
339 }
340 Some(hex.to_string())
341}
342
343pub fn run_test(program: &str, args: TestArgs) -> ExitCode {
348 let TestArgs {
349 input,
350 output,
351 no_run,
352 require_tests,
353 format,
354 inspect,
355 seed,
356 case,
357 suite,
358 partial_selection,
359 coverage,
360 against,
361 skip_unsupported,
362 settle,
363 smoke,
364 print,
365 smoke_unsafe,
366 no_install,
367 update_snapshots,
368 declared_statuses,
369 dev_command,
370 mutate,
371 only,
372 max_mutants,
373 mutate_timeout,
374 mutate_all_suites,
375 mutate_fail_under,
376 changed,
377 mutate_jobs,
378 mutant_overlay,
379 run_timeout,
380 overlay,
381 each: _,
383 } = args;
384 let stream = format == TestFormat::Ndjson;
387 let json = format == TestFormat::Json || stream;
388 if stream && (coverage || no_run) {
391 let message = if coverage {
392 "`--format ndjson` cannot be combined with `--coverage`: coverage is a whole-run report, so use `--format json`."
393 } else {
394 "`--format ndjson` cannot be combined with `--no-run`: discovery is a document, so use `--format json`."
395 };
396 crate::test_stream::print_run(true, &TestRun::runtime_error(message, None));
397 return ExitCode::FAILURE;
398 }
399 if mutate {
402 let with = [
403 (inspect, "--inspect"),
404 (no_run, "--no-run"),
405 (coverage, "--coverage"),
406 (against.is_some(), "--against"),
407 (smoke, "--smoke"),
408 (update_snapshots, "--update-snapshots"),
409 (!case.is_empty(), "--case"),
410 (stream, "--format ndjson"),
411 ]
412 .into_iter()
413 .find_map(|(set, flag)| set.then_some(flag));
414 if let Some(flag) = with {
415 let message = format!(
416 "`--mutate` cannot be combined with `{flag}`: it re-runs the project's own suites in process, against mutants."
417 );
418 if json {
419 crate::test_stream::print_run(stream, &TestRun::runtime_error(message, None));
420 } else {
421 emsg!("{program} test: error: {message}");
422 }
423 return ExitCode::FAILURE;
424 }
425 return crate::mutate::run(
426 program,
427 crate::mutate::MutateArgs {
428 input,
429 json,
430 seed,
431 suite,
432 only,
433 max_mutants,
434 timeout: mutate_timeout.map(std::time::Duration::from_secs),
435 all_suites: mutate_all_suites,
436 fail_under: mutate_fail_under,
437 changed,
438 jobs: mutate_jobs.map_or(1, |n| n as usize),
439 },
440 );
441 }
442 if update_snapshots {
445 let with = [
446 (against.is_some(), "--against"),
447 (smoke, "--smoke"),
448 (coverage, "--coverage"),
449 (inspect, "--inspect"),
450 (no_run, "--no-run"),
451 ]
452 .into_iter()
453 .find_map(|(set, flag)| set.then_some(flag));
454 if let Some(flag) = with {
455 let message = format!(
456 "`--update-snapshots` cannot be combined with `{flag}`: snapshots are recorded from an in-process run of the project's own suites."
457 );
458 if json {
459 crate::test_stream::print_run(stream, &TestRun::runtime_error(message, None));
460 } else {
461 emsg!("{program} test: error: {message}");
462 }
463 return ExitCode::FAILURE;
464 }
465 }
466 let mut remote = match against.as_deref() {
471 None => None,
472 Some(value) => {
473 let refused = |message: String| {
474 if json {
475 crate::test_stream::print_run(stream, &TestRun::runtime_error(message, None));
476 } else {
477 emsg!("{program} test: error: {message}");
478 }
479 ExitCode::FAILURE
480 };
481 let settle_ms = match settle.as_deref().map(crate::remote::parse_settle) {
482 None => crate::remote::DEFAULT_SETTLE_MS,
483 Some(Ok(ms)) => ms,
484 Some(Err(e)) => return refused(e),
485 };
486 if inspect || coverage {
487 return refused(
488 "`--against` cannot be combined with `--inspect` or `--coverage`, which observe the in-process run".to_string(),
489 );
490 }
491 match crate::remote::resolve(
492 value,
493 &input,
494 |name| match &dev_command {
495 Some(bynk) if name == crate::remote::DEV_COMMAND_ENV => {
496 Some(bynk.to_string_lossy().into_owned())
497 }
498 _ => std::env::var(name).ok(),
499 },
500 "starts a local `bynk dev`, and no `bynk` binary was given to start it with (set `BYNK_DEV_COMMAND`, or run `bynk test --against dev`, which supplies one)",
501 ) {
502 Ok(crate::remote::Against::Run(run)) => {
503 Some(crate::remote::RemoteRun { settle_ms, ..run })
504 }
505 Ok(crate::remote::Against::StartDev(bynk)) => {
506 return crate::dev_run::run(
507 program,
508 &crate::dev_run::DevRunArgs {
509 input: input.clone(),
510 output: output_root_for(&input, output.as_deref()),
511 json,
512 stream,
513 seed: seed.clone(),
514 filter: crate::test_filter::TestFilter::new(&suite, &case),
515 skip_unsupported,
516 settle: settle.clone(),
517 run_id: crate::remote::fresh_run_id(),
518 bynk,
519 smoke,
520 },
521 );
522 }
523 Err(refusal) => return refused(refusal.to_string()),
524 }
525 }
526 };
527 if coverage && inspect {
533 return coverage_unsupported(
534 program,
535 json,
536 "`--coverage` cannot be combined with `--inspect` — coverage needs the `tsc → node` run, not the inspector.",
537 );
538 }
539 if coverage && no_run {
540 return coverage_unsupported(
541 program,
542 json,
543 "`--coverage` cannot be combined with `--no-run` — there is no run to measure.",
544 );
545 }
546 let filter = crate::test_filter::TestFilter::new(&suite, &case).partial(partial_selection);
550 let seed_hex = match seed.as_deref() {
554 Some(raw) => match normalise_seed(raw) {
555 Some(hex) => Some(hex),
556 None => {
557 if !json {
558 emsg!(
559 "{program} test: warning: ignoring --seed `{raw}` (not a hex value like 0x5f3a)"
560 );
561 }
562 None
563 }
564 },
565 None => None,
566 };
567 let output_root = output_root_for(&input, output.as_deref());
568 if !input.is_dir() {
569 emsg!(
570 "{program} test: error: input `{}` must be a project directory containing `.bynk` files",
571 input.display()
572 );
573 return ExitCode::FAILURE;
574 }
575 let options = {
584 let o = match crate::try_project_options(&input)
591 .map_err(|e| e.to_string())
592 .and_then(|o| Ok(o.schema_registry(crate::schema_lock::read_only(&input)?)))
593 .and_then(
596 |o| Ok(o.contracts(crate::project_contracts(&input, crate::CliProfile::Dev)?)),
597 )
598 .and_then(|o| {
600 let files = bynk_project::snapshots::read_snapshot_files(&input)
601 .map_err(|e| format!("could not read `snapshots/`: {e}"))?;
602 Ok(o.snapshot_files(files))
603 }) {
604 Ok(o) => match with_overlays(o, &input, mutant_overlay, overlay) {
605 Ok(o) => o,
606 Err(e) => return fail_run(program, json, stream, e),
607 },
608 Err(e) => return fail_run(program, json, stream, e),
609 };
610 let o = o.remote_tests(remote.as_ref().map(|run| crate::project::RemoteTests {
613 skip_unsupported,
614 vars: run.vars.clone(),
615 secrets: run.secrets.clone(),
616 dev: run.dev_env.is_some(),
617 only_env: run.dev_env.clone(),
618 }));
619 if inspect {
620 o.import_ext(ImportExt::Ts)
621 } else {
622 o
623 }
624 };
625 let mut smoke_skips: Vec<(String, crate::project::RemoteSkip)> = Vec::new();
629 let options = if smoke {
630 let methods = match remote.as_ref() {
631 Some(run) if run.dev_env.is_none() && !smoke_unsafe => crate::smoke::Methods::SafeOnly,
632 _ => crate::smoke::Methods::All,
633 };
634 let report = std::env::var_os(crate::remote::DEV_URLS_ENV).is_none();
636 match crate::smoke::prepare(program, options, methods, json, stream, report && !print) {
637 Ok(mut prepared) => {
638 if print {
639 print!("{}", prepared.smoke.print(&input));
640 return ExitCode::SUCCESS;
641 }
642 smoke_skips = prepared.smoke.remote_skips();
643 prepared.options
644 }
645 Err(code) => return code,
646 }
647 } else {
648 options
649 };
650 let out = match crate::project::compile_project(&options) {
651 Ok(out) => out,
652 Err(failure) => {
653 if json {
654 crate::test_stream::print_run(
655 stream,
656 &TestRun::compile_error(crate::project_failure_short_lines(&failure)),
657 );
658 } else {
659 crate::print_project_failure(&failure);
660 }
661 return ExitCode::FAILURE;
662 }
663 };
664 let mut out = out;
670 let mut doc_aliases: Vec<(String, String)> = Vec::new();
671 if remote.is_none()
674 && !smoke
675 && let Some(sources) = &options.sources
676 {
677 let docs = crate::doc_examples::DocExamples::collect(sources);
678 if !docs.is_empty() {
679 let mut errors = Vec::new();
680 let mut checked = None;
681 if docs.has_base() {
682 let check = crate::project::check_project(
683 &options.clone().sources(docs.check_overlay(sources)),
684 );
685 errors.extend(docs.remap(check.errors));
686 checked = Some((check.snapshots, check.display_root));
687 }
688 for layer in 0..docs.layer_count() {
691 let check = crate::project::check_project(
692 &options.clone().sources(docs.layer_overlay(layer, sources)),
693 );
694 errors.extend(docs.remap_layer(layer, check.errors));
695 checked = Some((check.snapshots, check.display_root));
696 }
697 let (snapshots, display_root) = checked.expect("a check ran");
698 if !errors.is_empty() {
699 let failure = crate::project::ProjectFailure {
700 errors,
701 snapshots,
702 display_root,
703 };
704 if json {
705 crate::test_stream::print_run(
706 stream,
707 &TestRun::compile_error(crate::project_failure_short_lines(&failure)),
708 );
709 } else {
710 crate::print_project_failure(&failure);
711 }
712 return ExitCode::FAILURE;
713 }
714 if docs.has_runnable() {
715 out = match crate::project::compile_project(
716 &options.clone().sources(docs.run_overlay(sources)),
717 ) {
718 Ok(out) => out,
719 Err(failure) => {
720 if json {
721 crate::test_stream::print_run(
722 stream,
723 &TestRun::compile_error(crate::project_failure_short_lines(
724 &failure,
725 )),
726 );
727 } else {
728 crate::print_project_failure(&failure);
729 }
730 return ExitCode::FAILURE;
731 }
732 };
733 doc_aliases = docs.run_aliases();
734 for case in out.discovered.iter_mut().flat_map(|s| s.cases.iter_mut()) {
736 if let Some(loc) = case.location.as_mut() {
737 case.doc = crate::doc_examples::is_synthetic_path(&loc.path, &doc_aliases);
739 loc.path = crate::doc_examples::apply_aliases(&loc.path, &doc_aliases)
740 .into_owned();
741 }
742 }
743 }
744 }
745 }
746 if no_run && json {
752 let suites = discovery_suites(&out);
753 if suites.is_empty() && require_tests {
754 return report_no_tests(program, &input, true, stream, true);
755 }
756 crate::test_stream::print_run(stream, &TestRun::discovered(suites));
757 return ExitCode::SUCCESS;
758 }
759 let snapshot_run = if smoke || remote.is_some() {
762 None
763 } else {
764 let stored = bynk_project::snapshots::read_snapshot_files(&input).unwrap_or_default();
765 crate::snapshots::SnapshotRun::new(
766 update_snapshots,
767 &input,
768 out.snapshot_files.clone(),
769 stored,
770 )
771 };
772 if let Some(run) = remote.as_mut() {
775 run.skipped = out
776 .discovered
777 .iter()
778 .flat_map(|s| s.skipped.iter().map(|k| (s.name.clone(), k.clone())))
779 .collect();
780 eprint!("{program} test: {}", run.banner());
781 if !json {
782 for (suite, skip) in run
783 .skipped
784 .iter()
785 .filter(|(suite, skip)| filter.selects(suite, &skip.case))
786 {
787 eprintln!(
788 "{program} test: skipped `{suite}` case \"{}\" [{}]: {}",
789 skip.case, skip.code, skip.reason
790 );
791 }
792 }
793 run.skipped.append(&mut smoke_skips);
795 }
796
797 let mut wrote_any_test = false;
799 let mut has_integration = false;
800 for (path, doc) in &out.artefacts.docs {
801 if let Err(e) = crate::write_document(path, doc, &out.artefacts.docs, &output_root) {
805 emsg!(
806 "{program} test: error: could not write `{}`: {e}",
807 output_root.join(path).display()
808 );
809 return ExitCode::FAILURE;
810 }
811 let rel = path.to_string_lossy();
812 if rel.starts_with("tests/") {
813 wrote_any_test = true;
814 }
815 if rel.starts_with("tests/integration_") {
816 has_integration = true;
817 }
818 }
819
820 let mut workers_modules = None;
828 if has_integration {
829 let workers_out =
833 crate::project::compile_project(&options.clone().target(BuildTarget::Workers));
834 let workers_out = match workers_out {
835 Ok(o) => o,
836 Err(failure) => {
837 if json {
838 crate::test_stream::print_run(
839 stream,
840 &TestRun::compile_error(crate::project_failure_short_lines(&failure)),
841 );
842 } else {
843 crate::print_project_failure(&failure);
844 }
845 return ExitCode::FAILURE;
846 }
847 };
848 for (path, doc) in &workers_out.artefacts.docs {
849 if path.to_string_lossy().starts_with("tests/") {
850 continue;
851 }
852 if let Err(e) =
853 crate::write_document(path, doc, &workers_out.artefacts.docs, &output_root)
854 {
855 emsg!(
856 "{program} test: error: could not write `{}`: {e}",
857 output_root.join(path).display()
858 );
859 return ExitCode::FAILURE;
860 }
861 }
862 workers_modules = Some(workers_out.artefacts);
863 }
864
865 if let Err(code) = finish_output(program, &output_root, &out, workers_modules.as_ref()) {
866 return code;
867 }
868
869 if !wrote_any_test {
870 return report_no_tests(program, &input, require_tests, stream, json);
871 }
872
873 let main_ts = output_root.join("tests").join("main.ts");
874 if no_run {
875 emsg!("{program} test: tests emitted to {}", main_ts.display());
879 return ExitCode::SUCCESS;
880 }
881
882 if inspect {
887 return run_inspect(program, &main_ts, seed_hex.as_deref(), &filter, smoke);
888 }
889
890 let tsconfig = output_root.join("tsconfig.json");
891 if coverage
895 && let Err(e) = std::fs::write(
896 &tsconfig,
897 bynk_emit::emitter::emit_tsconfig_with_source_maps(),
898 )
899 {
900 return coverage_unsupported(
901 program,
902 json,
903 format!("could not enable source maps for coverage: {e}"),
904 );
905 }
906 let out_js_root = output_root.join("out-js");
915 let main_js = out_js_root.join("tests").join("main.js");
916
917 let prepared = write_esm_marker(&out_js_root).map_err(|e| {
923 let marker = out_js_root.join("package.json");
924 format!("could not write {}: {e}", marker.display())
925 });
926 if let Err(msg) =
927 prepared.and_then(|()| provision_npm(&input, &output_root, &out_js_root, no_install))
928 {
929 return fail_run(program, json, stream, msg);
930 }
931
932 let manager = crate::npm_install::system_tool_manager(&input);
939 let mut start_failures: Vec<String> = Vec::new();
940 let tsc_runners = crate::tools::Ladder::tsc(manager);
941 for rung in tsc_runners.rungs() {
942 let mut cmd = rung.command();
943 cmd.arg("-p").arg(&tsconfig).args(["--pretty", "false"]);
946 let tsc_ok = match cmd.stdout(Stdio::piped()).stderr(Stdio::piped()).output() {
949 Ok(o) if o.status.success() => true,
950 Ok(o) => {
951 let mut detail = String::from_utf8_lossy(&o.stdout).into_owned();
953 let err_text = String::from_utf8_lossy(&o.stderr);
954 if !err_text.trim().is_empty() {
955 if !detail.is_empty() {
956 detail.push('\n');
957 }
958 detail.push_str(&err_text);
959 }
960 let failure = crate::tsc_report::diagnose(
961 &detail,
962 &output_root,
963 &out.snapshots,
964 &out.display_root,
965 );
966 if json {
967 let run = match &failure {
968 Some(f) => {
969 TestRun::codegen_error(crate::project_failure_short_lines(f), detail)
970 }
971 None => TestRun::runtime_error(
972 "tsc rejected the generated TypeScript",
973 Some(detail),
974 ),
975 };
976 crate::test_stream::print_run(stream, &run);
977 } else {
978 match &failure {
979 Some(f) => crate::print_project_failure(f),
980 None => eprint!("{detail}"),
981 }
982 emsg!(
983 "{program} test: error: tsc reported errors against {}",
984 tsconfig.display()
985 );
986 }
987 return ExitCode::FAILURE;
988 }
989 Err(e) => {
990 start_failures.push(rung.start_failure(&e));
991 continue;
992 }
993 };
994 if tsc_ok {
995 let mut node_cmd = crate::tools::node_command();
996 node_cmd.arg(&main_js);
997 if smoke {
998 node_cmd.env(crate::smoke::STRICT_WIRE_ENV, "1");
999 }
1000 if let Some(file) = &declared_statuses {
1001 node_cmd.env(crate::smoke::DECLARED_ENV, file);
1002 }
1003 if coverage {
1007 return run_with_coverage(
1008 program,
1009 node_cmd,
1010 json,
1011 seed_hex.as_deref(),
1012 &filter,
1013 &out_js_root,
1014 &output_root,
1015 &input,
1016 &out.discovered,
1017 );
1018 }
1019 return match finish_runner(
1020 program,
1021 node_cmd,
1022 format,
1023 seed_hex.as_deref(),
1024 &filter,
1025 remote.as_ref(),
1026 &smoke_skips,
1027 &out.discovered,
1028 &doc_aliases,
1029 snapshot_run.as_ref(),
1030 run_timeout,
1031 ) {
1032 Ok(code) => code,
1033 Err(e) if e.kind() == std::io::ErrorKind::TimedOut => {
1034 return report_timeout(program, json, stream, &e);
1035 }
1036 Err(e) => {
1037 if json {
1038 crate::test_stream::print_run(
1039 stream,
1040 &TestRun::runtime_error(format!("could not run node: {e}"), None),
1041 );
1042 } else {
1043 emsg!(
1044 "{program} test: error: tsc succeeded but `node {}` failed: {e}",
1045 main_js.display()
1046 );
1047 }
1048 ExitCode::FAILURE
1049 }
1050 };
1051 }
1052 }
1053
1054 if coverage {
1058 if !start_failures.is_empty() {
1061 return report_start_failures(program, json, stream, &start_failures, true, manager);
1062 }
1063 return coverage_unsupported(
1064 program,
1065 json,
1066 "`--coverage` requires `tsc` and `node` on PATH (the CI-shaped path with `.js.map`s); the `tsx` fallback is not supported for coverage.",
1067 );
1068 }
1069
1070 let tsx_runners = crate::tools::Ladder::tsx(manager);
1072 for rung in tsx_runners.rungs() {
1073 let mut cmd = rung.command();
1074 cmd.arg(&main_ts);
1075 if smoke {
1076 cmd.env(crate::smoke::STRICT_WIRE_ENV, "1");
1077 }
1078 if let Some(file) = &declared_statuses {
1079 cmd.env(crate::smoke::DECLARED_ENV, file);
1080 }
1081 match finish_runner(
1082 program,
1083 cmd,
1084 format,
1085 seed_hex.as_deref(),
1086 &filter,
1087 remote.as_ref(),
1088 &smoke_skips,
1089 &out.discovered,
1090 &doc_aliases,
1091 snapshot_run.as_ref(),
1092 run_timeout,
1093 ) {
1094 Ok(code) => return code,
1095 Err(e) if e.kind() == std::io::ErrorKind::TimedOut => {
1098 return report_timeout(program, json, stream, &e);
1099 }
1100 Err(e) => start_failures.push(rung.start_failure(&e)),
1101 }
1102 }
1103
1104 if !start_failures.is_empty() {
1105 return report_start_failures(program, json, stream, &start_failures, false, manager);
1106 }
1107
1108 if json {
1109 crate::test_stream::print_run(
1110 stream,
1111 &TestRun::runtime_error(
1112 "no test runner found: requires `tsc` (with Node.js) or `tsx` on PATH",
1113 None,
1114 ),
1115 );
1116 } else {
1117 emsg!(
1118 "{program} test: error: requires either `tsc` (with Node.js) or `tsx` on PATH. \
1119 Install one of:\n{}",
1120 install_advice(manager, false)
1121 );
1122 }
1123 ExitCode::FAILURE
1124}
1125
1126fn finish_output(
1138 program: &str,
1139 output_root: &Path,
1140 out: &ProjectOutput,
1141 workers: Option<&bynk_emit::emit_model::Artefacts>,
1142) -> Result<(), ExitCode> {
1143 let mut written: std::collections::HashSet<PathBuf> = out
1144 .artefacts
1145 .docs
1146 .keys()
1147 .chain(out.artefacts.modules.keys())
1148 .cloned()
1149 .collect();
1150 for modules in [Some(&out.artefacts.modules), workers.map(|w| &w.modules)]
1151 .into_iter()
1152 .flatten()
1153 {
1154 if let Err(e) = crate::write_modules_for_node(modules, output_root) {
1155 emsg!("{program} test: error: could not write a WebAssembly module: {e}");
1156 return Err(ExitCode::FAILURE);
1157 }
1158 }
1159 if let Some(workers) = workers {
1160 written.extend(
1161 workers
1162 .docs
1163 .keys()
1164 .filter(|path| !path.to_string_lossy().starts_with("tests/"))
1165 .chain(workers.modules.keys())
1166 .cloned(),
1167 );
1168 }
1169 crate::output::prune_output_except(output_root, &written).map_err(|e| {
1170 emsg!(
1171 "{program} test: error: could not remove stale output from `{}`: {e}",
1172 output_root.display()
1173 );
1174 ExitCode::FAILURE
1175 })
1176}
1177
1178fn report_no_tests(
1182 program: &str,
1183 input: &Path,
1184 require_tests: bool,
1185 stream: bool,
1186 json: bool,
1187) -> ExitCode {
1188 if json {
1189 let run = if require_tests {
1190 TestRun::no_tests_error(format!("no tests found in {}", input.display()))
1191 } else {
1192 empty_run()
1193 };
1194 crate::test_stream::print_run(stream, &run);
1195 } else if require_tests {
1196 emsg!(
1197 "{program} test: error: no tests found in {}",
1198 input.display()
1199 );
1200 } else {
1201 emsg!(
1202 "{program} test: warning: no tests found in {}",
1203 input.display()
1204 );
1205 }
1206 if require_tests {
1207 ExitCode::FAILURE
1208 } else {
1209 ExitCode::SUCCESS
1210 }
1211}
1212
1213fn with_overlays(
1217 mut options: crate::project::CompileOptions,
1218 input: &Path,
1219 mutant: Option<(PathBuf, String)>,
1220 overlay: Option<std::collections::HashMap<PathBuf, String>>,
1221) -> Result<crate::project::CompileOptions, String> {
1222 if let Some((path, text)) = mutant {
1223 options
1224 .sources
1225 .get_or_insert_with(Default::default)
1226 .insert(path, text);
1227 }
1228 match overlay {
1229 Some(overlay) => {
1230 crate::source_overlay::apply_overlay(options, input, overlay).map_err(|e| e.to_string())
1231 }
1232 None => Ok(options),
1233 }
1234}
1235
1236fn report_timeout(program: &str, json: bool, stream: bool, e: &std::io::Error) -> ExitCode {
1239 if json {
1240 crate::test_stream::print_run(stream, &TestRun::timeout_error(e.to_string()));
1241 } else {
1242 emsg!("{program} test: error: the run {e}");
1243 }
1244 ExitCode::FAILURE
1245}
1246
1247fn report_start_failures(
1252 program: &str,
1253 json: bool,
1254 stream: bool,
1255 failures: &[String],
1256 coverage: bool,
1257 manager: PackageManager,
1258) -> ExitCode {
1259 if json {
1260 crate::test_stream::print_run(
1261 stream,
1262 &TestRun::runtime_error("no test runner could be started", Some(failures.join("\n"))),
1263 );
1264 } else {
1265 emsg!("{program} test: error: no test runner could be started:");
1266 for failure in failures {
1267 eprintln!(" - {failure}");
1268 }
1269 eprintln!("Or install another:\n{}", install_advice(manager, coverage));
1270 }
1271 ExitCode::FAILURE
1272}
1273
1274fn install_advice(manager: PackageManager, coverage: bool) -> String {
1277 let tsc = format!(
1278 " - `{}` (provides tsc, which type-checks; requires Node.js to run output)",
1279 manager.global_install(&crate::tools::pins::typescript_spec())
1280 );
1281 if coverage {
1282 return tsc;
1283 }
1284 let runner = manager.runner_label().unwrap_or("npx");
1286 format!(
1287 "{tsc}\n - `{}` (runs TypeScript in one step, without type-checking)\n Or run inside a project where `{runner} tsc` / `{runner} tsx` resolves.",
1288 manager.global_install(crate::tools::pins::TSX_SPEC)
1289 )
1290}
1291
1292fn empty_run() -> TestRun {
1295 TestRun::empty()
1296}
1297
1298fn discovery_suites(out: &ProjectOutput) -> Vec<Suite> {
1302 out.discovered
1303 .iter()
1304 .map(|s| Suite {
1305 name: s.name.clone(),
1306 kind: s.kind.to_string(),
1307 cases: s
1308 .cases
1309 .iter()
1310 .map(|c| Case {
1311 name: c.name.clone(),
1312 outcome: "discovered".to_string(),
1313 message: None,
1314 location: c.location.as_ref().map(|l| Location {
1315 path: l.path.clone(),
1316 line: l.line,
1317 col: l.col,
1318 }),
1319 retries: None,
1320 detached_failures: None,
1321 tier: c.tier.map(str::to_string),
1322 kind: c.generative.map(str::to_string),
1323 seed: None,
1324 counterexample: None,
1325 violation: None,
1326 refusals: None,
1327 origin: c.doc.then(|| "doc".to_string()),
1328 warnings: None,
1329 duration_ms: None,
1330 })
1331 .collect(),
1332 })
1333 .collect()
1334}
1335
1336#[allow(clippy::too_many_arguments)]
1350fn finish_runner(
1351 program: &str,
1352 mut cmd: ProcCommand,
1353 format: TestFormat,
1354 seed_hex: Option<&str>,
1355 filter: &crate::test_filter::TestFilter,
1356 remote: Option<&crate::remote::RemoteRun>,
1357 local_skips: &[(String, crate::project::RemoteSkip)],
1359 discovered: &[crate::project::DiscoveredSuite],
1360 aliases: &[(String, String)],
1361 snapshots: Option<&crate::snapshots::SnapshotRun>,
1363 timeout: Option<std::time::Duration>,
1365) -> std::io::Result<ExitCode> {
1366 if let Some(hex) = seed_hex {
1367 cmd.env(env_protocol::TEST_SEED, hex);
1368 }
1369 if let Some(run) = remote {
1372 cmd.env(env_protocol::TEST_TARGETS, run.targets_json());
1373 cmd.env(crate::remote::SECRETS_ENV, run.secrets_json());
1374 cmd.env(env_protocol::TEST_SETTLE_MS, run.settle_ms.to_string());
1375 cmd.env(crate::remote::RUN_ID_ENV, &run.run_id);
1378 }
1379 let selected_skips: Vec<&(String, crate::project::RemoteSkip)> = remote
1382 .map_or(local_skips, |run| run.skipped.as_slice())
1383 .iter()
1384 .filter(|(suite, skip)| filter.selects(suite, &skip.case))
1385 .collect();
1386 filter
1387 .clone()
1388 .with_skipped(
1389 selected_skips
1390 .iter()
1391 .map(|(suite, skip)| (suite.as_str(), skip.case.as_str())),
1392 )
1393 .apply(program, &mut cmd);
1394 if let Some(run) = snapshots {
1395 if run.update {
1396 cmd.env(crate::snapshots::UPDATE_ENV, "1");
1397 }
1398 if format == TestFormat::Rich {
1399 cmd.env(crate::snapshots::REPORT_ENV, "1");
1400 }
1401 }
1402 if format == TestFormat::Ndjson {
1403 cmd.env(env_protocol::TEST_FORMAT, "ndjson");
1405 let mut events = crate::test_stream::Stream::new(crate::test_stream::StreamContext {
1406 discovered,
1407 skipped: selected_skips
1408 .iter()
1409 .map(|(suite, k)| (suite.clone(), k.case.clone(), k.reason.clone()))
1410 .collect(),
1411 transport: remote.map(crate::remote::RemoteRun::transport),
1412 snapshots,
1413 });
1414 let status =
1415 crate::test_stream::forward(cmd, &mut events, &mut std::io::stdout().lock(), aliases)?;
1416 for warning in events.warnings() {
1417 crate::colour::eprintln(&warning.line(program));
1418 }
1419 if let Some(run) = snapshots
1422 && let Some(report) = run.report_for(events.snapshot_report())
1423 && let Err(e) = run.settle(&report)
1424 {
1425 emsg!("{program} test: error: could not update snapshots: {e}");
1426 return Ok(ExitCode::FAILURE);
1427 }
1428 events.unmatched().report(program);
1429 return Ok(exit_from(status.success() && events.ended()));
1430 }
1431 if format == TestFormat::Json {
1432 cmd.env(env_protocol::TEST_FORMAT, "ndjson");
1433 let out = output_within(cmd.stdout(Stdio::piped()).stderr(Stdio::piped()), timeout)?;
1434 let stdout = String::from_utf8_lossy(&out.stdout);
1435 let stderr = String::from_utf8_lossy(&out.stderr);
1436 let stdout = crate::doc_examples::apply_aliases(&stdout, aliases);
1437 let stderr = crate::doc_examples::apply_aliases(&stderr, aliases);
1438 let parsed = crate::test_json::parse_ndjson(&stdout);
1439 let unmatched = parsed.unmatched.clone();
1440 let snapshot_report = parsed.snapshots.clone();
1441 let mut doc = parsed.into_document(&stderr).with_tiers(discovered);
1442 let mut settle_failed = None;
1444 if let Some(run) = snapshots {
1445 let counts = match run.report_for(snapshot_report.as_ref()) {
1446 Some(report) => match run.settle(&report) {
1447 Ok(counts) => counts,
1448 Err(e) => {
1449 settle_failed = Some(e);
1450 run.counts(Some(&report))
1451 }
1452 },
1453 None => run.counts(None),
1454 };
1455 doc = doc.with_snapshots(Some(counts));
1456 }
1457 let skipped: Vec<(String, String, String)> = selected_skips
1458 .iter()
1459 .map(|(suite, k)| (suite.clone(), k.case.clone(), k.reason.clone()))
1460 .collect();
1461 doc = match remote {
1462 Some(run) => doc.with_remote(run.transport(), &skipped),
1463 None => doc.with_skips(&skipped),
1464 };
1465 crate::test_stream::print_text(&doc.render());
1466 for warning in doc.warnings() {
1467 crate::colour::eprintln(&warning.line(program));
1468 }
1469 unmatched.report(program);
1470 if let Some(e) = settle_failed {
1471 emsg!("{program} test: error: could not update snapshots: {e}");
1472 return Ok(ExitCode::FAILURE);
1473 }
1474 Ok(exit_from_document(out.status.success(), &doc))
1475 } else if aliases.is_empty() && snapshots.is_none() && !crate::colour::stdout() {
1476 let status = cmd
1477 .stdout(Stdio::inherit())
1478 .stderr(Stdio::inherit())
1479 .status()?;
1480 Ok(exit_from(status.success()))
1481 } else {
1482 let (status, report) = run_aliased(cmd, aliases, crate::colour::stdout())?;
1487 if let Some(run) = snapshots {
1488 let counts = match run.report_for(report.as_ref()) {
1489 Some(report) => match run.settle(&report) {
1490 Ok(counts) => counts,
1491 Err(e) => {
1492 emsg!("{program} test: error: could not update snapshots: {e}");
1493 return Ok(ExitCode::FAILURE);
1494 }
1495 },
1496 None => run.counts(None),
1497 };
1498 if let Some(line) = run.summary_line(counts) {
1499 println!("{line}");
1500 }
1501 }
1502 Ok(exit_from(status.success()))
1503 }
1504}
1505
1506fn kill_tree(child: &mut std::process::Child) {
1509 #[cfg(unix)]
1510 {
1511 unsafe {
1514 libc::killpg(child.id() as libc::pid_t, libc::SIGKILL);
1515 }
1516 }
1517 #[cfg(windows)]
1518 {
1519 let _ = ProcCommand::new("taskkill")
1520 .args(["/T", "/F", "/PID", &child.id().to_string()])
1521 .stdout(Stdio::null())
1522 .stderr(Stdio::null())
1523 .status();
1524 }
1525 let _ = child.kill();
1526}
1527
1528fn output_within(
1532 cmd: &mut ProcCommand,
1533 timeout: Option<std::time::Duration>,
1534) -> std::io::Result<std::process::Output> {
1535 use std::io::Read;
1536 let Some(timeout) = timeout else {
1537 return cmd.output();
1538 };
1539 #[cfg(unix)]
1543 std::os::unix::process::CommandExt::process_group(cmd, 0);
1544 let mut child = cmd.spawn()?;
1545 let drain = |pipe: Option<Box<dyn Read + Send>>| {
1546 std::thread::spawn(move || {
1547 let mut buf = Vec::new();
1548 if let Some(mut pipe) = pipe {
1549 let _ = pipe.read_to_end(&mut buf);
1550 }
1551 buf
1552 })
1553 };
1554 let out_reader = drain(
1555 child
1556 .stdout
1557 .take()
1558 .map(|p| Box::new(p) as Box<dyn Read + Send>),
1559 );
1560 let err_reader = drain(
1561 child
1562 .stderr
1563 .take()
1564 .map(|p| Box::new(p) as Box<dyn Read + Send>),
1565 );
1566 let deadline = std::time::Instant::now() + timeout;
1567 let status = loop {
1568 if let Some(status) = child.try_wait()? {
1569 break Some(status);
1570 }
1571 if std::time::Instant::now() >= deadline {
1572 kill_tree(&mut child);
1573 let _ = child.wait();
1574 break None;
1575 }
1576 std::thread::sleep(std::time::Duration::from_millis(20));
1577 };
1578 let stdout = out_reader.join().unwrap_or_default();
1579 let stderr = err_reader.join().unwrap_or_default();
1580 match status {
1581 Some(status) => Ok(std::process::Output {
1582 status,
1583 stdout,
1584 stderr,
1585 }),
1586 None => Err(std::io::Error::new(
1587 std::io::ErrorKind::TimedOut,
1588 format!("timed out after {}s", timeout.as_secs()),
1589 )),
1590 }
1591}
1592
1593fn run_aliased(
1596 mut cmd: ProcCommand,
1597 aliases: &[(String, String)],
1598 colour: bool,
1599) -> std::io::Result<(std::process::ExitStatus, Option<crate::snapshots::Report>)> {
1600 use std::io::{BufRead, BufReader, Write};
1601 fn forward(
1606 pipe: impl std::io::Read,
1607 aliases: &[(String, String)],
1608 mut out: impl Write,
1609 report: Option<&mut Option<crate::snapshots::Report>>,
1610 colour: bool,
1611 ) {
1612 let mut report = report;
1613 let mut lines = crate::colour::TestLines::default();
1614 let mut reader = BufReader::new(pipe);
1615 let mut buffer = Vec::new();
1616 loop {
1617 buffer.clear();
1618 match reader.read_until(b'\n', &mut buffer) {
1619 Ok(0) | Err(_) => break,
1620 Ok(_) => {}
1621 }
1622 let line = String::from_utf8_lossy(&buffer);
1623 if let Some(found) = report.as_deref_mut()
1625 && let Some(parsed) = crate::snapshots::Report::from_marked_line(&line)
1626 {
1627 *found = Some(parsed);
1628 continue;
1629 }
1630 let line = crate::doc_examples::apply_aliases(&line, aliases);
1631 let line = if colour {
1632 lines.paint(&line)
1633 } else {
1634 line.into_owned()
1635 };
1636 let _ = out.write_all(line.as_bytes());
1637 let _ = out.flush();
1638 }
1639 }
1640 if colour {
1643 cmd.env_remove("NO_COLOR").env("FORCE_COLOR", "1");
1644 }
1645 let mut child = cmd.stdout(Stdio::piped()).stderr(Stdio::piped()).spawn()?;
1646 let stderr_pipe = child.stderr.take();
1647 let err_aliases = aliases.to_vec();
1648 let errors = std::thread::spawn(move || {
1649 if let Some(pipe) = stderr_pipe {
1650 forward(pipe, &err_aliases, std::io::stderr().lock(), None, false);
1651 }
1652 });
1653 let mut report = None;
1654 if let Some(pipe) = child.stdout.take() {
1655 forward(
1656 pipe,
1657 aliases,
1658 std::io::stdout().lock(),
1659 Some(&mut report),
1660 colour,
1661 );
1662 }
1663 let status = child.wait()?;
1664 let _ = errors.join();
1665 Ok((status, report))
1666}
1667
1668fn exit_from(success: bool) -> ExitCode {
1669 if success {
1670 ExitCode::SUCCESS
1671 } else {
1672 ExitCode::FAILURE
1673 }
1674}
1675
1676fn exit_from_document(runner_ok: bool, doc: &TestRun) -> ExitCode {
1680 exit_from(runner_ok && doc.error.is_none())
1681}
1682
1683fn coverage_unsupported(program: &str, json: bool, message: impl Into<String>) -> ExitCode {
1687 let message = message.into();
1688 if json {
1689 crate::test_stream::print_run(false, &TestRun::runtime_error(message, None));
1691 } else {
1692 emsg!("{program} test --coverage: error: {message}");
1693 }
1694 ExitCode::FAILURE
1695}
1696
1697#[allow(clippy::too_many_arguments)]
1706fn run_with_coverage(
1707 program: &str,
1708 mut cmd: ProcCommand,
1709 json: bool,
1710 seed_hex: Option<&str>,
1711 filter: &crate::test_filter::TestFilter,
1712 out_js_root: &Path,
1713 out_root: &Path,
1714 source_root: &Path,
1715 discovered: &[crate::project::DiscoveredSuite],
1716) -> ExitCode {
1717 let cov_dir = out_root.join(".v8-coverage");
1720 let _ = std::fs::remove_dir_all(&cov_dir);
1721 if let Err(e) = std::fs::create_dir_all(&cov_dir) {
1722 return coverage_unsupported(
1723 program,
1724 json,
1725 format!("could not create the coverage dir: {e}"),
1726 );
1727 }
1728 cmd.env("NODE_V8_COVERAGE", &cov_dir);
1729 if let Some(hex) = seed_hex {
1730 cmd.env(env_protocol::TEST_SEED, hex);
1731 }
1732 filter.apply(program, &mut cmd);
1733
1734 let collect = || {
1735 crate::coverage::collect_coverage(&cov_dir, out_js_root, out_root, source_root)
1736 .unwrap_or_default()
1737 };
1738
1739 let code = if json {
1740 cmd.env(env_protocol::TEST_FORMAT, "ndjson");
1741 let out = match cmd.stdout(Stdio::piped()).stderr(Stdio::piped()).output() {
1742 Ok(o) => o,
1743 Err(e) => {
1744 let _ = std::fs::remove_dir_all(&cov_dir);
1745 return coverage_unsupported(program, true, format!("could not run node: {e}"));
1746 }
1747 };
1748 let stdout = String::from_utf8_lossy(&out.stdout);
1749 let stderr = String::from_utf8_lossy(&out.stderr);
1750 let report = collect();
1751 let parsed = crate::test_json::parse_ndjson(&stdout);
1752 let unmatched = parsed.unmatched.clone();
1753 let doc = parsed
1754 .into_document(&stderr)
1755 .with_tiers(discovered)
1756 .with_coverage(&report);
1757 print!("{}", doc.render());
1758 for warning in doc.warnings() {
1759 crate::colour::eprintln(&warning.line(program));
1760 }
1761 unmatched.report(program);
1762 exit_from_document(out.status.success(), &doc)
1763 } else {
1764 let colour = crate::colour::stdout();
1765 let status = if colour {
1766 run_aliased(cmd, &[], true).map(|(status, _)| status)
1767 } else {
1768 cmd.stdout(Stdio::inherit())
1769 .stderr(Stdio::inherit())
1770 .status()
1771 };
1772 let status = match status {
1773 Ok(s) => s,
1774 Err(e) => {
1775 let _ = std::fs::remove_dir_all(&cov_dir);
1776 emsg!("{program} test --coverage: error: could not run node: {e}");
1777 return ExitCode::FAILURE;
1778 }
1779 };
1780 let report = collect();
1781 print!("{}", crate::coverage::render_rich(&report, colour));
1782 exit_from(status.success())
1783 };
1784 let _ = std::fs::remove_dir_all(&cov_dir);
1785 code
1786}
1787
1788fn write_esm_marker(out_js_root: &Path) -> std::io::Result<()> {
1791 std::fs::create_dir_all(out_js_root)?;
1792 std::fs::write(
1793 out_js_root.join("package.json"),
1794 "{\n \"type\": \"module\"\n}\n",
1795 )
1796}
1797
1798const NODE_INSPECT_PORT: u16 = 9229;
1800
1801fn inspect_brk_arg(default_port_free: bool) -> &'static str {
1810 if default_port_free {
1811 "--inspect-brk"
1812 } else {
1813 "--inspect-brk=127.0.0.1:0"
1814 }
1815}
1816
1817fn run_inspect(
1824 program: &str,
1825 entry: &Path,
1826 seed_hex: Option<&str>,
1827 filter: &crate::test_filter::TestFilter,
1828 smoke: bool,
1829) -> ExitCode {
1830 let Some(mut cmd) = crate::tools::resolved_node_command() else {
1831 emsg!("{program} test --inspect: error: `node` was not found on PATH");
1832 return ExitCode::FAILURE;
1833 };
1834 emsg!("{program} test --inspect: launching the test runner under Node's inspector.");
1835 eprintln!(" Attach a JavaScript debugger to the inspector URL below; breakpoints set");
1836 eprintln!(" in `.bynk` sources resolve through the emitted source maps.");
1837 eprintln!(" (Requires Node \u{2265} 22.6 for TypeScript type-stripping.)");
1838 if let Some(hex) = seed_hex {
1839 cmd.env(env_protocol::TEST_SEED, hex);
1840 }
1841 if smoke {
1842 cmd.env(crate::smoke::STRICT_WIRE_ENV, "1");
1843 }
1844 filter.apply(program, &mut cmd);
1845 let default_free = std::net::TcpListener::bind(("127.0.0.1", NODE_INSPECT_PORT)).is_ok();
1846 if !default_free {
1847 eprintln!(
1848 " Port {NODE_INSPECT_PORT} is in use, so the inspector takes a free port; use the URL below."
1849 );
1850 }
1851 cmd.arg("--experimental-strip-types")
1852 .arg(inspect_brk_arg(default_free))
1853 .arg(entry);
1854 match cmd
1855 .stdout(Stdio::inherit())
1856 .stderr(Stdio::inherit())
1857 .status()
1858 {
1859 Ok(s) => exit_from(s.success()),
1860 Err(e) => {
1861 emsg!("{program} test --inspect: error: could not run node: {e}");
1862 ExitCode::FAILURE
1863 }
1864 }
1865}
1866
1867#[cfg(test)]
1868mod inspect_port_tests {
1869
1870 use super::inspect_brk_arg;
1871
1872 #[test]
1873 fn uses_the_default_port_when_free_and_a_free_port_otherwise() {
1874 assert_eq!(inspect_brk_arg(true), "--inspect-brk");
1875 assert_eq!(inspect_brk_arg(false), "--inspect-brk=127.0.0.1:0");
1876 }
1877}
1878
1879#[cfg(test)]
1880mod exit_from_document_tests {
1881 use super::*;
1882
1883 fn exit_for(runner_ok: bool, stdout: &str) -> ExitCode {
1884 let doc = crate::test_json::parse_ndjson(stdout).into_document("");
1885 exit_from_document(runner_ok, &doc)
1886 }
1887
1888 #[test]
1891 fn a_stream_that_never_completes_fails_the_run_even_when_the_runner_exits_zero() {
1892 let failure = ExitCode::FAILURE;
1893 assert_eq!(exit_for(true, ""), failure);
1894 assert_eq!(
1895 exit_for(true, r#"{"type":"suite-begin","name":"s","kind":"system"}"#),
1896 failure
1897 );
1898 let complete = concat!(
1899 r#"{"type":"suite-begin","name":"s","kind":"system"}"#,
1900 "\n",
1901 r#"{"type":"case","name":"c","outcome":"pass"}"#,
1902 "\n",
1903 r#"{"type":"run-end","passed":1,"failed":0}"#,
1904 "\n",
1905 );
1906 assert_eq!(exit_for(true, complete), ExitCode::SUCCESS);
1907 assert_eq!(exit_for(false, complete), failure);
1908 }
1909}
1910
1911#[cfg(test)]
1912mod output_within_tests {
1913 use super::*;
1914
1915 #[cfg(unix)]
1916 #[test]
1917 fn output_within_kills_a_process_that_outlives_its_timeout() {
1918 let mut cmd = ProcCommand::new("sleep");
1919 cmd.arg("30").stdout(Stdio::piped()).stderr(Stdio::piped());
1920 let started = std::time::Instant::now();
1921 let err = output_within(&mut cmd, Some(std::time::Duration::from_millis(100)))
1922 .expect_err("sleep outlives 100ms");
1923 assert_eq!(err.kind(), std::io::ErrorKind::TimedOut);
1924 assert!(started.elapsed() < std::time::Duration::from_secs(10));
1925
1926 let mut tree = ProcCommand::new("sh");
1928 tree.args(["-c", "sleep 30 & wait"])
1929 .stdout(Stdio::piped())
1930 .stderr(Stdio::piped());
1931 let started = std::time::Instant::now();
1932 let err = output_within(&mut tree, Some(std::time::Duration::from_millis(200)))
1933 .expect_err("the shell outlives 200ms");
1934 assert_eq!(err.kind(), std::io::ErrorKind::TimedOut);
1935 assert!(
1936 started.elapsed() < std::time::Duration::from_secs(10),
1937 "the grandchild was killed with its parent"
1938 );
1939
1940 let mut quick = ProcCommand::new("echo");
1941 quick
1942 .arg("hi")
1943 .stdout(Stdio::piped())
1944 .stderr(Stdio::piped());
1945 let out = output_within(&mut quick, Some(std::time::Duration::from_secs(30))).unwrap();
1946 assert_eq!(String::from_utf8_lossy(&out.stdout).trim(), "hi");
1947 }
1948
1949 #[cfg(windows)]
1955 #[test]
1956 fn output_within_kills_a_windows_process_tree() {
1957 use std::os::windows::process::CommandExt;
1958 use std::time::{Duration, Instant};
1959
1960 const MARK: &str = "-n 37 127.0.0.1";
1962
1963 fn survivors() -> Result<String, String> {
1964 let out = ProcCommand::new("powershell")
1965 .args([
1966 "-NoProfile",
1967 "-Command",
1968 "Get-CimInstance Win32_Process -Filter \"Name='ping.exe'\" | \
1969 Where-Object { $_.CommandLine -like '*-n 37 127.0.0.1*' } | \
1970 ForEach-Object { \"$($_.ProcessId) $($_.CommandLine)\" }",
1971 ])
1972 .output()
1973 .map_err(|e| format!("could not run powershell: {e}"))?;
1974 if !out.status.success() {
1975 return Err(format!(
1976 "powershell failed ({}): {}",
1977 out.status,
1978 String::from_utf8_lossy(&out.stderr).trim()
1979 ));
1980 }
1981 Ok(String::from_utf8_lossy(&out.stdout).trim().to_string())
1982 }
1983 fn cleanup() {
1984 let _ = ProcCommand::new("powershell")
1985 .args([
1986 "-NoProfile",
1987 "-Command",
1988 "Get-CimInstance Win32_Process -Filter \"Name='ping.exe'\" | \
1989 Where-Object { $_.CommandLine -like '*-n 37 127.0.0.1*' } | \
1990 ForEach-Object { Stop-Process -Id $_.ProcessId -Force }",
1991 ])
1992 .output();
1993 }
1994
1995 let mut cmd = ProcCommand::new("cmd");
1998 cmd.raw_arg(format!("/c \"start /b ping {MARK} & ping {MARK}\""))
1999 .stdout(Stdio::piped())
2000 .stderr(Stdio::piped());
2001
2002 let (tx, rx) = std::sync::mpsc::channel();
2005 let started = Instant::now();
2006 std::thread::spawn(move || {
2007 let _ = tx.send(output_within(&mut cmd, Some(Duration::from_millis(500))));
2008 });
2009 let result = match rx.recv_timeout(Duration::from_secs(60)) {
2010 Ok(result) => result,
2011 Err(_) => {
2012 let seen = survivors();
2013 cleanup();
2014 panic!(
2015 "output_within did not return within 60s of a 500ms timeout: the \
2016 grandchildren still held the pipes after taskkill. ping processes \
2017 alive: {seen:?}. Switch kill_tree to a Job Object (kill on close)."
2018 );
2019 }
2020 };
2021 let elapsed = started.elapsed();
2022 let err = match result {
2023 Err(e) => e,
2024 Ok(out) => {
2025 cleanup();
2026 panic!("expected a timeout, got status {:?}", out.status);
2027 }
2028 };
2029 assert_eq!(err.kind(), std::io::ErrorKind::TimedOut, "error: {err}");
2030 assert!(
2031 elapsed < Duration::from_secs(20),
2032 "TimedOut took {elapsed:?}; the pings last about 37s, so the tree was not killed"
2033 );
2034
2035 let deadline = Instant::now() + Duration::from_secs(10);
2038 let mut seen;
2039 loop {
2040 seen = survivors();
2041 if matches!(&seen, Ok(s) if s.is_empty()) || Instant::now() >= deadline {
2042 break;
2043 }
2044 std::thread::sleep(Duration::from_millis(250));
2045 }
2046 match seen {
2047 Ok(s) if s.is_empty() => {}
2048 Ok(s) => {
2049 cleanup();
2050 panic!("taskkill left processes running after the timeout:\n{s}");
2051 }
2052 Err(e) => eprintln!("could not check for survivors ({e}); relying on the timing"),
2054 }
2055 }
2056}
2057
2058fn provision_npm(
2067 project_root: &Path,
2068 output_root: &Path,
2069 out_js_root: &Path,
2070 no_install: bool,
2071) -> Result<(), String> {
2072 let manifest = std::fs::read_to_string(output_root.join("package.json")).unwrap_or_default();
2073 if !manifest.contains("\"dependencies\"") {
2074 return Ok(());
2075 }
2076 let modules = output_root.join("node_modules");
2077 crate::npm_install::install_for_project(
2078 project_root,
2079 output_root,
2080 crate::npm_install::configured_manager(project_root).as_deref(),
2081 crate::npm_install::Mode::of(
2082 false,
2083 no_install || crate::npm_install::no_install_from_env(),
2084 ),
2085 )?;
2086 let link = out_js_root.join("node_modules");
2087 if link.symlink_metadata().is_ok() {
2089 let _ = std::fs::remove_file(&link).or_else(|_| std::fs::remove_dir(&link));
2091 }
2092 let target = std::fs::canonicalize(&modules)
2095 .map_err(|e| format!("could not resolve {}: {e}", modules.display()))?;
2096 #[cfg(unix)]
2097 std::os::unix::fs::symlink(&target, &link)
2098 .map_err(|e| format!("could not link {}: {e}", link.display()))?;
2099 #[cfg(windows)]
2101 {
2102 let plain = target
2104 .to_string_lossy()
2105 .trim_start_matches(r"\\?\")
2106 .to_string();
2107 let made = ProcCommand::new("cmd")
2108 .arg("/C")
2109 .arg("mklink")
2110 .arg("/J")
2111 .arg(&link)
2112 .arg(&plain)
2113 .output()
2114 .map_err(|e| format!("could not link {}: {e}", link.display()))?;
2115 if !made.status.success() {
2116 return Err(format!(
2117 "could not link {}: {}",
2118 link.display(),
2119 String::from_utf8_lossy(&made.stdout)
2120 ));
2121 }
2122 }
2123 Ok(())
2124}
2125
2126fn fail_run(program: &str, json: bool, stream: bool, msg: String) -> ExitCode {
2128 if json {
2129 crate::test_stream::print_run(stream, &TestRun::runtime_error(msg, None));
2130 } else {
2131 emsg!("{program} test: error: {msg}");
2132 }
2133 ExitCode::FAILURE
2134}