Skip to main content

bynk_driver/
dev_run.rs

1//! #2138 (end-to-end testing track ยง3.5): `bynk test --against dev`, the
2//! `system` suites run against a local `bynk dev` the runner starts itself.
3//!
4//! For each distinct `env` the `system` cases run with (one group), this:
5//!
6//! 1. starts `bynk dev --ready-json` (local `wrangler dev`/workerd only, never
7//!    `-- --remote`) with the group's `env` and a fixed test value for every
8//!    other secret the Workers declare, passed as `-- --var NAME:VALUE`;
9//! 2. waits for the readiness file, whose URLs must all be loopback;
10//! 3. runs the group's cases against those URLs (this binary again, with
11//!    [`crate::remote::DEV_URLS_ENV`] and [`crate::remote::DEV_ENV_ENV`]),
12//!    signing with the same secret values;
13//! 4. stops `bynk dev` by its own pid (it stops its wranglers and their
14//!    `workerd`s), then its process group if anything is left.
15//!
16//! Groups run in turn; their results are reported together.
17
18use crate::emsg;
19use std::collections::{BTreeMap, BTreeSet};
20use std::path::{Path, PathBuf};
21use std::process::{Child, Command, ExitCode, Stdio};
22use std::time::{Duration, Instant};
23
24use crate::project::{BuildTarget, RemoteTests};
25
26use crate::remote::{DEV, DEV_ENV_ENV, DEV_SECRETS_ENV, DEV_URLS_ENV, is_loopback_http};
27use crate::test_json::TestRun;
28
29/// The value every declared secret the case doesn't set takes, both in the
30/// Workers (`-- --var`) and in the runner that signs for them.
31pub const TEST_SECRET: &str = "__bynk_test_secret";
32
33// 1B.2a (#4028): defined beside the test-harness generation that embeds it.
34pub use bynk_emit::testgen::TEST_SESSION_KEY;
35
36/// How long to wait for a `bynk dev` to answer before giving up.
37const READY_TIMEOUT: Duration = Duration::from_secs(180);
38
39/// How long a stopped `bynk dev` gets to stop its Workers before its process
40/// group is killed.
41const STOP_GRACE: Duration = Duration::from_secs(30);
42
43/// What the orchestration needs from the `test` invocation.
44#[derive(Debug, Clone)]
45pub struct DevRunArgs {
46    pub input: PathBuf,
47    pub output: PathBuf,
48    pub json: bool,
49    /// `--format ndjson`: the merged result is printed as a stream. The groups
50    /// run as `--format json` children, so it is written when they have finished.
51    pub stream: bool,
52    pub seed: Option<String>,
53    /// The `--suite`/`--case` set, forwarded to each group's run.
54    pub filter: crate::test_filter::TestFilter,
55    pub skip_unsupported: bool,
56    /// `--settle`, forwarded to each group's run.
57    pub settle: Option<String>,
58    /// The `run.id` every group's run shares.
59    pub run_id: String,
60    /// The `bynk` binary that starts `bynk dev`.
61    pub bynk: PathBuf,
62    /// `--smoke` (#2658): run the synthesised smoke suites, forwarded to each
63    /// group's run.
64    pub smoke: bool,
65}
66
67/// Run every `system` suite against a local `bynk dev`, one per distinct
68/// `env`.
69pub fn run(program: &str, args: &DevRunArgs) -> ExitCode {
70    let fail = |message: String| {
71        if args.json {
72            crate::test_stream::print_run(args.stream, &TestRun::runtime_error(message, None));
73        } else {
74            emsg!("{program} test: error: {message}");
75        }
76        ExitCode::FAILURE
77    };
78    let plan = match plan(program, args) {
79        Ok(plan) => plan,
80        Err(Planned::Failed(code)) => return code,
81        Err(Planned::Message(m)) => return fail(m),
82    };
83    // The groups run in separate processes, each seeing only its own cases, so
84    // the values that select nothing are judged here, over all of them, before
85    // anything starts (#2273).
86    let unmatched = args.filter.unmatched_in(&plan.cases);
87    if !unmatched.is_empty() {
88        return fail(unmatched.messages().join("; "));
89    }
90    if plan.groups.is_empty() {
91        if args.json {
92            crate::test_stream::print_run(
93                args.stream,
94                &TestRun::empty().with_remote(format!("remote:{DEV}"), &[]),
95            );
96        } else {
97            emsg!("{program} test: warning: no `system` suites to run against `bynk dev`");
98        }
99        return ExitCode::SUCCESS;
100    }
101    let mut docs: Vec<serde_json::Value> = Vec::new();
102    let mut all_ok = true;
103    for (i, group) in plan.groups.iter().enumerate() {
104        let vars = dev_vars(group, &plan.secrets, &plan.session_secrets);
105        if !args.json {
106            emsg!(
107                "{program} test: starting `bynk dev`{}",
108                if group.is_empty() {
109                    String::new()
110                } else {
111                    format!(
112                        " with env {}",
113                        group
114                            .iter()
115                            .map(|(k, v)| format!("{k}={v:?}"))
116                            .collect::<Vec<_>>()
117                            .join(", ")
118                    )
119                }
120            );
121        }
122        let ready = args.output.join(format!(".bynk-dev-ready-{i}.json"));
123        let log = args.output.join(format!(".bynk-dev-{i}.log"));
124        let mut dev = match Dev::start(&args.bynk, &args.input, &ready, &log, &vars) {
125            Ok(dev) => dev,
126            Err(e) => return fail(format!("could not start `bynk dev`: {e}")),
127        };
128        let urls = match dev.wait_ready(&ready) {
129            Ok(urls) => urls,
130            Err(e) => {
131                drop(dev);
132                return fail(format!("{e} (its output is in {})", log.display()));
133            }
134        };
135        let outcome = run_group(args, group, &urls, &vars);
136        dev.stop();
137        match outcome {
138            Ok((ok, doc)) => {
139                all_ok &= ok;
140                docs.extend(doc);
141            }
142            Err(e) => return fail(e),
143        }
144    }
145    if args.json {
146        crate::test_stream::print_run(args.stream, &merge(&docs));
147    }
148    if all_ok {
149        ExitCode::SUCCESS
150    } else {
151        ExitCode::FAILURE
152    }
153}
154
155/// The groups to run, and the secrets the Workers declare.
156struct Plan {
157    groups: Vec<BTreeMap<String, String>>,
158    secrets: BTreeSet<String>,
159    /// #3386: the variables holding a `SignedCookie` actor's signing key.
160    session_secrets: BTreeSet<String>,
161    /// Every (suite, case) a group can run, to judge `--suite`/`--case` against.
162    cases: Vec<(String, String)>,
163}
164
165enum Planned {
166    /// A compile failure, already reported.
167    Failed(ExitCode),
168    Message(String),
169}
170
171/// The options of the `--against dev` build: the Workers target, the remote-test
172/// plan, and the `dev` profile's contracts (#3107: `[profile.dev] contracts`,
173/// on by default).
174fn plan_options(args: &DevRunArgs) -> Result<crate::project::CompileOptions, Planned> {
175    Ok(crate::try_project_options(&args.input)
176        .map_err(|e| Planned::Message(e.to_string()))?
177        .contracts(
178            crate::project_contracts(&args.input, crate::CliProfile::Dev)
179                .map_err(Planned::Message)?,
180        )
181        .remote_tests(Some(RemoteTests {
182            skip_unsupported: args.skip_unsupported,
183            dev: true,
184            ..RemoteTests::default()
185        }))
186        .target(BuildTarget::Workers))
187}
188
189/// Compile the project as a `--against dev` build once: refuse what a real
190/// runtime can't honour (as the group runs would), and read the distinct
191/// `env` maps of its `system` cases and the secrets its Workers declare.
192fn plan(program: &str, args: &DevRunArgs) -> Result<Plan, Planned> {
193    let options = plan_options(args)?;
194    // #2658: plan the smoke suites' run; this is where its skips are reported.
195    let options = if args.smoke {
196        crate::smoke::prepare(
197            program,
198            options,
199            crate::smoke::Methods::All,
200            args.json,
201            args.stream,
202            true,
203        )
204        .map_err(Planned::Failed)?
205        .options
206    } else {
207        options
208    };
209    let out = match crate::project::compile_project(&options) {
210        Ok(out) => out,
211        Err(failure) => {
212            if args.json {
213                crate::test_stream::print_run(
214                    args.stream,
215                    &TestRun::compile_error(crate::project_failure_short_lines(&failure)),
216                );
217            } else {
218                crate::print_project_failure(&failure);
219            }
220            return Err(Planned::Failed(ExitCode::FAILURE));
221        }
222    };
223    let mut groups: Vec<BTreeMap<String, String>> = Vec::new();
224    for env in out.discovered.iter().flat_map(|s| s.envs.iter()) {
225        if !groups.contains(env) {
226            groups.push(env.clone());
227        }
228    }
229    // A suite the dev run executes has `envs` (the groups are built from them),
230    // so its cases are the ones a value can select. A case the build skipped
231    // (`--skip-unsupported`) still exists, so a value naming one is not unmatched.
232    let cases = out
233        .discovered
234        .iter()
235        .flat_map(|s| {
236            s.cases
237                .iter()
238                .filter(|_| !s.envs.is_empty())
239                .map(|c| (s.name.clone(), c.name.clone()))
240                .chain(s.skipped.iter().map(|k| (s.name.clone(), k.case.clone())))
241        })
242        .collect();
243    let mut secrets = BTreeSet::new();
244    let mut session_secrets = BTreeSet::new();
245    for (path, doc) in &out.artefacts.docs {
246        if path.file_name().is_some_and(|n| n == "bynk-secrets.json") {
247            let manifest: serde_json::Value = serde_json::from_str(&doc.text()).unwrap_or_default();
248            for key in ["declared", "read"] {
249                for name in manifest[key].as_array().into_iter().flatten() {
250                    if let Some(name) = name.as_str() {
251                        secrets.insert(name.to_string());
252                    }
253                }
254            }
255            for entry in manifest["session"].as_array().into_iter().flatten() {
256                if let Some(name) = entry["secret"].as_str() {
257                    session_secrets.insert(name.to_string());
258                }
259            }
260        }
261    }
262    Ok(Plan {
263        groups,
264        secrets,
265        session_secrets,
266        cases,
267    })
268}
269
270/// The variables one `bynk dev` serves: the group's `env`, then each declared
271/// secret the group doesn't set at the fixed test value.
272pub fn dev_vars(
273    group: &BTreeMap<String, String>,
274    secrets: &BTreeSet<String>,
275    session_secrets: &BTreeSet<String>,
276) -> BTreeMap<String, String> {
277    let mut vars = group.clone();
278    for s in session_secrets {
279        vars.entry(s.clone())
280            .or_insert_with(|| TEST_SESSION_KEY.to_string());
281    }
282    for s in secrets {
283        vars.entry(s.clone())
284            .or_insert_with(|| TEST_SECRET.to_string());
285    }
286    vars
287}
288
289/// Run one group's cases against `urls`: this binary again, as a run
290/// against `dev` with the URLs and the group's `env`, and the group's
291/// variables in its environment so the drivers sign with them. Returns
292/// whether it passed and, under `--format json`, its document.
293fn run_group(
294    args: &DevRunArgs,
295    group: &BTreeMap<String, String>,
296    urls: &BTreeMap<String, String>,
297    vars: &BTreeMap<String, String>,
298) -> Result<(bool, Option<serde_json::Value>), String> {
299    let me = std::env::current_exe().map_err(|e| format!("could not find this binary: {e}"))?;
300    let mut cmd = Command::new(me);
301    cmd.arg("test")
302        .arg(&args.input)
303        .arg("--output")
304        .arg(&args.output);
305    cmd.arg("--format")
306        .arg(if args.json { "json" } else { "rich" });
307    cmd.args(["--against", DEV]);
308    if let Some(seed) = &args.seed {
309        cmd.args(["--seed", seed]);
310    }
311    cmd.args(args.filter.args());
312    if !args.filter.is_empty() {
313        cmd.arg("--partial-selection");
314    }
315    if args.skip_unsupported {
316        cmd.arg("--skip-unsupported");
317    }
318    if args.smoke {
319        cmd.arg("--smoke");
320    }
321    if let Some(settle) = &args.settle {
322        cmd.args(["--settle", settle]);
323    }
324    cmd.env_remove(crate::remote::DEV_COMMAND_ENV);
325    // One `run.id` for every group of this run, through the orchestration's
326    // own variable: the group's runner always sets the harness's.
327    cmd.env(crate::remote::DEV_RUN_ID_ENV, &args.run_id);
328    cmd.env(
329        DEV_URLS_ENV,
330        serde_json::to_string(urls).expect("a string map serialises"),
331    );
332    cmd.env(
333        DEV_ENV_ENV,
334        serde_json::to_string(group).expect("a string map serialises"),
335    );
336    // One JSON variable, never a variable per name: an `env` entry or secret
337    // named `PATH` or `NODE_OPTIONS` must not change the runner itself.
338    cmd.env(
339        DEV_SECRETS_ENV,
340        serde_json::to_string(vars).expect("a string map serialises"),
341    );
342    if args.json {
343        let out = cmd
344            .stderr(Stdio::inherit())
345            .output()
346            .map_err(|e| format!("could not run the suites: {e}"))?;
347        let doc = serde_json::from_slice(&out.stdout)
348            .map_err(|e| format!("the run printed no JSON document: {e}"))?;
349        Ok((out.status.success(), Some(doc)))
350    } else {
351        let status = cmd
352            .status()
353            .map_err(|e| format!("could not run the suites: {e}"))?;
354        Ok((status.success(), None))
355    }
356}
357
358/// Fold the groups' documents into one: counts summed, suites of the same
359/// name merged, the first error kept, `transport: "remote:dev"`.
360fn merge(docs: &[serde_json::Value]) -> TestRun {
361    use crate::test_json::{Case, Location, Suite, TestError};
362    let count = |d: &serde_json::Value, k: &str| d[k].as_u64().unwrap_or(0) as u32;
363    let mut run = TestRun::empty();
364    run.transport = Some(format!("remote:{DEV}"));
365    let suites = run.suites.get_or_insert_with(Vec::new);
366    for doc in docs {
367        run.passed += count(doc, "passed");
368        run.failed += count(doc, "failed");
369        run.skipped += count(doc, "skipped");
370        for s in doc["suites"].as_array().into_iter().flatten() {
371            let name = s["name"].as_str().unwrap_or_default().to_string();
372            let cases = s["cases"].as_array().into_iter().flatten().map(|c| Case {
373                name: c["name"].as_str().unwrap_or_default().to_string(),
374                outcome: c["outcome"].as_str().unwrap_or_default().to_string(),
375                message: c["message"].as_str().map(str::to_string),
376                location: c["location"].as_object().map(|l| Location {
377                    path: l["path"].as_str().unwrap_or_default().to_string(),
378                    line: l["line"].as_u64().unwrap_or(0) as u32,
379                    col: l["col"].as_u64().unwrap_or(0) as u32,
380                }),
381                retries: c["retries"].as_u64().map(|n| n as u32),
382                detached_failures: c["detached_failures"].as_u64().map(|n| n as u32),
383                tier: c["tier"].as_str().map(str::to_string),
384                kind: c["kind"].as_str().map(str::to_string),
385                seed: c["seed"].as_str().map(str::to_string),
386                counterexample: c["counterexample"].as_str().map(str::to_string),
387                violation: c
388                    .get("violation")
389                    .map(crate::test_json::violation_from_json),
390                refusals: crate::test_json::refusals_from_json(c.get("refusals")),
391                origin: c["origin"].as_str().map(str::to_string),
392                warnings: crate::test_json::warnings_from_json(c.get("warnings")),
393                // The groups run as `json`, whose document holds no durations.
394                duration_ms: None,
395            });
396            match suites.iter_mut().find(|x| x.name == name) {
397                Some(existing) => {
398                    // Every group's build reports the same skipped cases;
399                    // list each once.
400                    for case in cases {
401                        let repeat = case.outcome == "skipped"
402                            && existing
403                                .cases
404                                .iter()
405                                .any(|c| c.outcome == "skipped" && c.name == case.name);
406                        if repeat {
407                            run.skipped = run.skipped.saturating_sub(1);
408                        } else {
409                            existing.cases.push(case);
410                        }
411                    }
412                }
413                None => suites.push(Suite {
414                    name,
415                    kind: s["kind"].as_str().unwrap_or("integration").to_string(),
416                    cases: cases.collect(),
417                }),
418            }
419        }
420        if run.error.is_none()
421            && let Some(e) = doc["error"].as_object()
422        {
423            run.error = Some(TestError {
424                kind: e["kind"].as_str().unwrap_or("runtime").to_string(),
425                message: e
426                    .get("message")
427                    .and_then(|m| m.as_str())
428                    .map(str::to_string),
429                diagnostics: e
430                    .get("diagnostics")
431                    .and_then(|d| d.as_array())
432                    .into_iter()
433                    .flatten()
434                    .filter_map(|d| d.as_str().map(str::to_string))
435                    .collect(),
436                stderr: e.get("stderr").and_then(|m| m.as_str()).map(str::to_string),
437            });
438        }
439    }
440    run
441}
442
443/// Remove a readiness file left by an earlier run, so it is never read as
444/// this session being ready. A missing file is fine.
445pub fn remove_stale(ready: &Path) -> std::io::Result<()> {
446    match std::fs::remove_file(ready) {
447        Err(e) if e.kind() != std::io::ErrorKind::NotFound => Err(e),
448        _ => Ok(()),
449    }
450}
451
452/// Two distinct localhost ports, free when asked: the base of the HTTP and
453/// the inspector allocations `bynk dev` makes.
454fn free_ports() -> std::io::Result<(u16, u16)> {
455    let a = std::net::TcpListener::bind("127.0.0.1:0")?;
456    let b = std::net::TcpListener::bind("127.0.0.1:0")?;
457    Ok((a.local_addr()?.port(), b.local_addr()?.port()))
458}
459
460/// A running `bynk dev`, stopped on drop.
461struct Dev {
462    child: Child,
463    stopped: bool,
464}
465
466impl Dev {
467    fn start(
468        bynk: &Path,
469        input: &Path,
470        ready: &Path,
471        log: &Path,
472        vars: &BTreeMap<String, String>,
473    ) -> std::io::Result<Dev> {
474        if let Some(dir) = ready.parent() {
475            std::fs::create_dir_all(dir)?;
476        }
477        // A file left by an earlier run that was killed must never read as
478        // this session being ready.
479        crate::dev_run::remove_stale(ready)?;
480        let (port, inspector) = free_ports()?;
481        let log_file = std::fs::File::create(log)?;
482        let mut cmd = Command::new(bynk);
483        cmd.arg("dev")
484            .arg(input)
485            .arg("--base-port")
486            .arg(port.to_string())
487            .arg("--inspect-port")
488            .arg(inspector.to_string())
489            .arg("--ready-json")
490            .arg(ready)
491            .arg("--");
492        // Only variables are passed through: never `--remote`.
493        for (k, v) in vars {
494            cmd.arg("--var").arg(format!("{k}:{v}"));
495        }
496        #[cfg(unix)]
497        std::os::unix::process::CommandExt::process_group(&mut cmd, 0);
498        let child = cmd
499            .stdin(Stdio::null())
500            .stdout(log_file.try_clone()?)
501            .stderr(log_file)
502            .spawn()?;
503        Ok(Dev {
504            child,
505            stopped: false,
506        })
507    }
508
509    /// Wait for the readiness file and read its URLs, which must all be
510    /// loopback.
511    fn wait_ready(&mut self, ready: &Path) -> Result<BTreeMap<String, String>, String> {
512        let deadline = Instant::now() + READY_TIMEOUT;
513        loop {
514            if let Ok(text) = std::fs::read_to_string(ready)
515                && let Ok(urls) = serde_json::from_str::<BTreeMap<String, String>>(&text)
516            {
517                if let Some(bad) = urls.values().find(|u| !is_loopback_http(u)) {
518                    return Err(format!("`bynk dev` reported `{bad}`, which isn't loopback"));
519                }
520                return Ok(urls);
521            }
522            if let Ok(Some(status)) = self.child.try_wait() {
523                return Err(format!("`bynk dev` exited before it was ready ({status})"));
524            }
525            if Instant::now() >= deadline {
526                return Err(format!(
527                    "`bynk dev` wasn't ready within {}s",
528                    READY_TIMEOUT.as_secs()
529                ));
530            }
531            std::thread::sleep(Duration::from_millis(250));
532        }
533    }
534
535    /// Stop `bynk dev`: SIGTERM to its own pid, so it stops its Workers; then,
536    /// always, its whole process group, so a wrangler or `workerd` it leaves
537    /// behind (because it exited first, or didn't stop them in time) never
538    /// leaks. Runs once; a second call (the drop after an explicit stop) does
539    /// nothing.
540    fn stop(&mut self) {
541        if self.stopped {
542            return;
543        }
544        self.stopped = true;
545        #[cfg(unix)]
546        {
547            let pid = self.child.id().to_string();
548            if !matches!(self.child.try_wait(), Ok(Some(_))) {
549                let _ = Command::new("kill").args(["-s", "TERM", &pid]).status();
550                let deadline = Instant::now() + STOP_GRACE;
551                while Instant::now() < deadline {
552                    if matches!(self.child.try_wait(), Ok(Some(_))) {
553                        break;
554                    }
555                    std::thread::sleep(Duration::from_millis(100));
556                }
557            }
558            // `bynk dev` leads its own process group, so `-<pid>` names
559            // exactly what it started and nothing else on the machine.
560            let _ = Command::new("kill")
561                .args(["-s", "KILL", "--", &format!("-{pid}")])
562                .stderr(Stdio::null())
563                .status();
564        }
565        let _ = self.child.kill();
566        let _ = self.child.wait();
567    }
568}
569
570impl Drop for Dev {
571    fn drop(&mut self) {
572        self.stop();
573    }
574}
575
576#[cfg(test)]
577mod tests {
578    use super::*;
579
580    /// #3107: the `--against dev` build is the `dev` profile, so
581    /// `[profile.dev] contracts` decides its guard (on by default).
582    #[test]
583    fn the_plan_builds_the_dev_profile() {
584        let dir = std::env::temp_dir().join(format!(
585            "bynk_3107_plan_{}_{:?}",
586            std::process::id(),
587            std::thread::current().id()
588        ));
589        let _ = std::fs::remove_dir_all(&dir);
590        std::fs::create_dir_all(dir.join("src")).unwrap();
591        std::fs::write(
592            dir.join("src/calc.bynk"),
593            "commons calc {\n  fn dbl(n: Int) -> Int { n + n }\n}\n",
594        )
595        .unwrap();
596        let args = DevRunArgs {
597            input: dir.clone(),
598            output: dir.join("out"),
599            json: false,
600            stream: false,
601            seed: None,
602            filter: crate::test_filter::TestFilter::default(),
603            skip_unsupported: false,
604            settle: None,
605            run_id: String::new(),
606            bynk: PathBuf::new(),
607            smoke: false,
608        };
609        let manifest =
610            |extra: &str| format!("[project]\nname = \"calc\"\nversion = \"0.1.0\"\n{extra}");
611        let contracts = |extra: &str| {
612            std::fs::write(dir.join("bynk.toml"), manifest(extra)).unwrap();
613            plan_options(&args).ok().expect("options").contracts
614        };
615        assert!(contracts(""), "on by default");
616        assert!(!contracts("\n[profile.dev]\ncontracts = false\n"));
617        assert!(
618            contracts("\n[profile.release]\ncontracts = false\n"),
619            "release does not touch it"
620        );
621        let _ = std::fs::remove_dir_all(&dir);
622    }
623
624    /// A merged `--against dev` document keeps each case's `tier`, which the
625    /// groups' own documents carry.
626    #[test]
627    fn merging_the_groups_keeps_each_cases_tier() {
628        let doc = serde_json::json!({
629            "passed": 1, "failed": 0,
630            "suites": [{"name": "shop", "kind": "integration", "cases": [
631                {"name": "wired", "outcome": "pass", "tier": "system"},
632                {"name": "plain", "outcome": "pass"}
633            ]}]
634        });
635        let merged = merge(&[doc]);
636        let cases = &merged.suites.as_ref().unwrap()[0].cases;
637        assert_eq!(cases[0].tier.as_deref(), Some("system"));
638        assert_eq!(cases[1].tier, None);
639    }
640
641    #[test]
642    fn a_session_key_variable_gets_the_session_test_key() {
643        let session = BTreeSet::from(["SESSION_KEY".to_string(), "OTHER_KEY".to_string()]);
644        let group = BTreeMap::from([("OTHER_KEY".to_string(), "mine".to_string())]);
645        let vars = dev_vars(&group, &BTreeSet::new(), &session);
646        assert_eq!(vars["SESSION_KEY"], TEST_SESSION_KEY);
647        assert_eq!(vars["OTHER_KEY"], "mine", "a group's own value wins");
648        // A name that is both an ordinary secret and a session key takes the session key.
649        let both = BTreeSet::from(["SESSION_KEY".to_string()]);
650        let vars = dev_vars(&BTreeMap::new(), &both, &session);
651        assert_eq!(vars["SESSION_KEY"], TEST_SESSION_KEY);
652    }
653
654    #[test]
655    fn a_group_s_env_wins_and_other_secrets_get_the_test_value() {
656        let group = BTreeMap::from([
657            ("PAYMENTS".to_string(), "fake".to_string()),
658            ("AUTH_SECRET".to_string(), "s3".to_string()),
659        ]);
660        let secrets = BTreeSet::from(["AUTH_SECRET".to_string(), "HOOK_SECRET".to_string()]);
661        let vars = dev_vars(&group, &secrets, &BTreeSet::new());
662        assert_eq!(vars["PAYMENTS"], "fake");
663        assert_eq!(vars["AUTH_SECRET"], "s3");
664        assert_eq!(vars["HOOK_SECRET"], TEST_SECRET);
665    }
666
667    #[test]
668    fn a_stale_ready_file_is_removed_before_a_session_starts() {
669        let dir = std::env::temp_dir().join(format!("bynk-dev-stale-{}", std::process::id()));
670        std::fs::create_dir_all(&dir).unwrap();
671        let ready = dir.join(".bynk-dev-ready-0.json");
672        // An earlier, killed run's file, pointing somewhere bogus.
673        std::fs::write(&ready, r#"{"svc":"http://localhost:1"}"#).unwrap();
674        // `Dev::start` removes it before spawning, even when the spawn then
675        // fails (here: no such binary), so it can never read as ready.
676        let started = Dev::start(
677            &dir.join("no-such-bynk"),
678            &dir,
679            &ready,
680            &dir.join("dev.log"),
681            &BTreeMap::new(),
682        );
683        assert!(started.is_err());
684        assert!(!ready.exists(), "the stale file is gone");
685        remove_stale(&ready).expect("removing an absent file is fine");
686        let _ = std::fs::remove_dir_all(&dir);
687    }
688
689    #[test]
690    fn group_documents_merge_into_one() {
691        let a = serde_json::json!({"passed": 1, "failed": 0, "suites": [{"name": "s", "kind": "integration", "cases": [{"name": "a", "outcome": "pass"}]}], "transport": "remote:dev"});
692        let b = serde_json::json!({"passed": 0, "failed": 1, "suites": [{"name": "s", "kind": "integration", "cases": [{"name": "b", "outcome": "fail", "message": "m"}]}], "transport": "remote:dev"});
693        let run = merge(&[a, b]);
694        assert_eq!((run.passed, run.failed), (1, 1));
695        let suites = run.suites.expect("suites");
696        assert_eq!(suites.len(), 1);
697        assert_eq!(suites[0].cases.len(), 2);
698        assert_eq!(run.transport.as_deref(), Some("remote:dev"));
699    }
700}