Skip to main content

bynk/
test.rs

1//! `bynk test` — discover and run a project's test declarations.
2//!
3//! Runs in-process (#2998, E1): the body is [`bynk_driver::test_runner::run_test`],
4//! the one `bynk test` runs, so no separate compiler binary is needed and no second
5//! compiler can skew from this one. What stays a child process is what always
6//! was: `tsc`/`node` for the runner, and the `bynk dev` that `--against dev`
7//! starts. This module adds what only `bynk` can supply: the workspace loop,
8//! the smoke run's declared-status table (walked by `bynk-ide`), and the path
9//! of this binary for `--against dev`.
10
11use bynk_driver::emsg;
12use std::path::{Path, PathBuf};
13use std::process::ExitCode;
14
15use bynk_driver::test_filter::TestFilter;
16use bynk_driver::test_runner::TestArgs;
17
18/// Run `bynk test`.
19pub fn run(args: TestArgs) -> ExitCode {
20    // #2207 (decision C): at a workspace root, test every member in order,
21    // each under a header. Every member runs, and the run fails if any does.
22    // #3274: `--each` makes a manifest-less directory of projects the same.
23    let workspace = match bynk_driver::workspace_at_each(&args.input, args.each) {
24        Ok(w) => w,
25        Err(message) => {
26            emsg!("bynk test: error: {message}");
27            return ExitCode::FAILURE;
28        }
29    };
30    if let Some(workspace) = workspace {
31        let workspace = match workspace {
32            Ok(w) => w,
33            Err(e) => {
34                emsg!(
35                    "bynk test: error: {}: {e}",
36                    bynk_driver::display_path(Path::new(""), &args.input.join("bynk.toml"))
37                );
38                return ExitCode::FAILURE;
39            }
40        };
41        if let Some(refusal) = workspace_refusal(&args) {
42            emsg!("bynk test: error: {refusal}");
43            return ExitCode::FAILURE;
44        }
45        let members: Vec<PathBuf> = workspace
46            .members
47            .iter()
48            .map(|member| bynk_driver::member_dir(&args.input, member))
49            .collect();
50        // #2273: a `--suite`/`--case` value may live in one member only, so
51        // each member runs as part of the selection, and the values are judged
52        // here against every member's suites.
53        let filter = TestFilter::new(&args.suite, &args.case);
54        if !filter.is_empty()
55            && let Some(available) = bynk_driver::test_runner::discover_cases("bynk", &members)
56        {
57            let unmatched = filter.unmatched_in(&available);
58            if !unmatched.is_empty() {
59                unmatched.report("bynk");
60                return ExitCode::FAILURE;
61            }
62        }
63        let mut failed = false;
64        for member in members {
65            println!("{}", bynk_driver::member_header(&member));
66            // Flushed before the child writes to the same stdout.
67            let _ = std::io::Write::flush(&mut std::io::stdout());
68            let member_args = TestArgs {
69                input: member,
70                each: false,
71                partial_selection: !filter.is_empty(),
72                ..args.clone()
73            };
74            failed |= run_one(member_args) != ExitCode::SUCCESS;
75        }
76        return if failed {
77            ExitCode::FAILURE
78        } else {
79            ExitCode::SUCCESS
80        };
81    }
82    run_one(args)
83}
84
85/// Why `args` can't run across a workspace's members, if they can't: one JSON
86/// document, one output directory and one deployment each belong to a single
87/// project.
88fn workspace_refusal(args: &TestArgs) -> Option<&'static str> {
89    if args.format == bynk_driver::test_runner::TestFormat::Json {
90        Some("`--format json` reports one project — run it inside a member of this workspace")
91    } else if args.format == bynk_driver::test_runner::TestFormat::Ndjson {
92        Some("`--format ndjson` streams one project — run it inside a member of this workspace")
93    } else if args.output.is_some() {
94        Some("`--output` names one project's output — run it inside a member of this workspace")
95    } else if args.mutate {
96        Some("`--mutate` mutates one project — run it inside a member of this workspace")
97    } else if args.against.is_some() {
98        Some("`--against` runs one project's suites — run it inside a member of this workspace")
99    } else {
100        None
101    }
102}
103
104/// Run the suites of one project.
105fn run_one(mut args: TestArgs) -> ExitCode {
106    let input = args.input.clone();
107    // #2138: a run against a local `bynk dev` starts it through this binary.
108    if args.against.as_deref() == Some(bynk_driver::remote::DEV) {
109        match std::env::current_exe() {
110            Ok(path) => args.dev_command = Some(path),
111            Err(e) => {
112                emsg!(
113                    "bynk test: error: could not find this `bynk` binary to start `bynk dev`: {e}"
114                );
115                return ExitCode::FAILURE;
116            }
117        }
118    }
119    // #2685: the statuses each route can answer, which a smoke case's answer is
120    // compared against. The walk is `bynk-ide`'s, so `bynk` makes it and hands
121    // the runner the result; the table is only for a run that calls routes.
122    // It goes in a file, since a large project's table could exceed what an
123    // environment variable can hold (`E2BIG`), and the runner reads a file.
124    let declared_file = (args.smoke && !args.print).then(|| {
125        let table = crate::openapi::declared_statuses(&input);
126        let path = std::env::temp_dir().join(format!(
127            "bynk-smoke-declared-{}-{}.json",
128            std::process::id(),
129            std::time::SystemTime::now()
130                .duration_since(std::time::UNIX_EPOCH)
131                .map_or(0, |d| d.as_nanos())
132        ));
133        std::fs::write(&path, serde_json::to_string(&table).unwrap_or_default()).map(|()| path)
134    });
135    match declared_file {
136        Some(Ok(path)) => args.declared_statuses = Some(path),
137        Some(Err(e)) => {
138            emsg!(
139                "bynk test: warning: could not write the smoke table, so undeclared statuses are not checked: {e}"
140            );
141        }
142        None => {}
143    }
144    let declared = args.declared_statuses.clone();
145    let code = bynk_driver::test_runner::run_test("bynk", args);
146    if let Some(path) = &declared {
147        let _ = std::fs::remove_file(path);
148    }
149    code
150}