Skip to main content

bynk_emit/
testgen.rs

1//! Test-harness generation: `suite`/`test integration` processing, the test entry
2//! (`tests/main.ts`), the discovery manifest and the embedded test-runtime fragments. The
3//! fragments are authored as modules under `bynk-emit/runtime/src/testing/` and reach the harness
4//! only through `runtime_splice` (1B.3a, #4047).
5//!
6//! 1B.2a (#4028, ADR "Where test generation lives"): moved here from the driver's
7//! `project/tests_emit{.rs,/}`, beside `emitter`. It reads no file, spawns no process and holds
8//! no thread-local; the driver keeps orchestration, file I/O and running the tests, and calls
9//! [`process_tests`], [`process_integration_tests`], [`discovery_manifest`] and
10//! [`emit_test_main`]. Production output never lives here: the commons barrel is
11//! `emitter::commons_barrel`.
12//!
13//! P5.4 (`design/tracks/semantics-in-the-checker.md` §6): the checking half
14//! of [`process_tests`]/[`process_integration_tests`] — target/participant
15//! resolution, duplicate-case-name detection, `stub`-clause resolution, and
16//! case/property body type-checking — relocated to
17//! `bynk_check::test_suites` (as [`test_suites::phase_test_bodies`]/
18//! [`test_suites::phase_integration_bodies`]), shared with
19//! `bynk_check::analysis::analyse_project` so a `.bynk` test file gets
20//! diagnostics and `RefSink` bindings (go-to-definition/find-references)
21//! through the LSP again, closing category 7 of
22//! `bynk-check/src/analysis.rs`'s own residual-gap accounting — the last of
23//! the seven. This file keeps both functions' exact signatures (`run_checks`
24//! needs no change) and everything Phase 5 (TypeScript emission) needs: the
25//! two functions now call the relocated checking phase first, then emit only
26//! for what it returns as ready. Several functions the checking phase needs
27//! are genuinely dual-use — also needed here to lower a checked body to
28//! TypeScript — and stayed `pub` in `bynk_check::test_suites` rather than
29//! being duplicated; every call into that module below is qualified
30//! (`test_suites::foo(...)`) for exactly that reason (see that module's own
31//! doc comment for the full accounting).
32
33use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
34use std::path::{Component, Path, PathBuf};
35use std::sync::Arc;
36
37use crate::emit_model::*;
38use crate::emitter;
39use crate::emitter::RuntimeUse;
40use crate::emitter::bindings::WorkerBinding;
41use crate::emitter::harness_names::{
42    SysdriveKind, route_with, sysdrive_name, wrong_method_driver_name,
43};
44use bynk_check::checker;
45use bynk_check::checker::ExprId;
46use bynk_check::hints::HintSink;
47use bynk_check::index::RefSink;
48use bynk_check::locals::LocalsSink;
49use bynk_check::project_model::handler_cross_caps;
50use bynk_check::requirements::RequirementSink;
51use bynk_check::resolver::{self, ResolvedCommons};
52use bynk_check::symbols::*;
53use bynk_project::UnitKind;
54use bynk_project::discovery::*;
55use bynk_project::paths::*;
56use bynk_syntax::error::CompileError;
57// #1759: every namespace a test module imports, from one definition.
58use crate::ts_build::*;
59use bynk_check::checker::Types;
60use bynk_check::d1_migrations::D1Migrations;
61use bynk_check::test_suites::{self};
62use bynk_check::wire_format;
63use bynk_syntax::ast::{Case, Visibility};
64
65// -- v0.7 / v0.118: test declaration processing --
66
67mod case_body;
68mod harness;
69mod integration_module;
70mod names;
71mod property_generators;
72mod property_tests;
73mod runtime_splice;
74mod stubs;
75mod system_jobs;
76mod system_request;
77mod system_support;
78mod test_cases;
79mod test_deps;
80mod test_main;
81mod test_module;
82mod test_runtime_modules;
83pub use self::harness::RunnableTest;
84pub use self::harness::discovery_manifest;
85use self::harness::*;
86use self::integration_module::*;
87use self::names::*;
88use self::property_generators::*;
89use self::property_tests::*;
90use self::runtime_splice::*;
91use self::stubs::*;
92use self::system_jobs::*;
93use self::system_request::*;
94use self::system_support::*;
95use self::test_cases::*;
96pub use self::test_deps::TestAssetFiles;
97use self::test_deps::*;
98pub use self::test_main::emit_test_main;
99use self::test_main::*;
100use self::test_module::*;
101
102/// #2685: the tail of the synthesised smoke suite's file name (`<stem>.smoke.bynk`), which a
103/// test build reads to name its typed routes to the decoder.
104pub const SMOKE_SUITE_SUFFIX: &str = ".smoke.bynk";
105
106/// #3386: the fixed signing key a `SignedCookie` actor's key variable takes in a test run (base64url of
107/// 32 bytes), as the verifier refuses the short `TEST_SECRET`.
108pub const TEST_SESSION_KEY: &str = "Ynluay10ZXN0LXNlc3Npb24ta2V5LTAxMjM0NTY3ODk";
109
110/// The name of the synthetic case. `bynk-driver` lowers a case of this name
111/// with its tail reported, and the run selects it by this name.
112pub const EVAL_CASE: &str = "bynk eval";
113
114/// 1A.34: a checker fact a suite's lowering needed and did not find is a compiler fault, reported
115/// as a `bynk.internal.missing_checker_fact` diagnostic at the `.bynk` span (the case body's), and
116/// the module's output is not used. Read once the module has lowered; the result says whether any
117/// fault was recorded, so the caller drops the module's output rather than stage it.
118///
119/// A project that already has an error-severity diagnostic (in any suite: `errors` is shared by
120/// every suite) is not reported: a program that failed checking lacks facts by construction (a
121/// mixed-tier suite has no receiver namespace), so a fault there is noise on top of the real error.
122/// The faults are still drained and the output still dropped. Warnings do not count: a build with
123/// only warnings succeeds, so its fault must be reported, or the dropped module would go unexplained.
124fn drain_internal_faults(errors: &mut Vec<CompileError>, runtime_use: &RuntimeUse) -> bool {
125    let faults = runtime_use.take_faults();
126    let faulted = !faults.is_empty();
127    let failed = errors
128        .iter()
129        .any(|e| bynk_syntax::Severity::for_error(e) == bynk_syntax::Severity::Error);
130    if !failed {
131        errors.extend(
132            faults
133                .into_iter()
134                .map(crate::emitter::InternalFault::into_compile_error),
135        );
136    }
137    faulted
138}
139
140/// P5.4: `test <target>` suite processing. The checking half (target/`stub`
141/// resolution, duplicate-case-name detection, case/property body
142/// type-checking — formerly this function's own Phases 2-4) now lives in
143/// [`test_suites::phase_test_bodies`]; only a target that passed every gate
144/// comes back, keyed by its resolved `stub` map, so the loop below is Phase
145/// 5 (TypeScript emission) alone, over exactly the targets ready for it.
146#[allow(clippy::too_many_arguments)]
147pub fn process_tests(
148    test_groups: &BTreeMap<String, Vec<usize>>,
149    parsed: &[ParsedFile],
150    kinds: &BTreeMap<String, UnitKind>,
151    unit_tables: &HashMap<String, UnitTable>,
152    exports_visibility: &HashMap<String, HashMap<String, Visibility>>,
153    unit_consumes: &HashMap<String, Vec<String>>,
154    unit_consumes_aliases: &HashMap<String, HashMap<String, String>>,
155    unit_uses: &HashMap<String, Vec<String>>,
156    // #3162: the declarations recovery skipped, per unit.
157    broken: &bynk_check::project_model::BrokenDeclNames,
158    // v0.17 (Locale capability track, slice 1, #844): capability name -> owning
159    // unit, per target, for capabilities flattened in via `consumes U { Cap }`
160    // (this never includes anything a target declares itself). Needed so
161    // `__makeTestDeps()` wires an adapter-flattened capability (real *or*
162    // stubbed) — it is not in `UnitTable.capabilities`, which holds only
163    // locally-declared capabilities.
164    unit_flattened: &HashMap<String, HashMap<String, String>>,
165    // v0.132: production unit name -> its `parsed` file indices, so a barrel can
166    // resolve a multi-file commons the test module imports back to its files.
167    groups: &BTreeMap<String, Vec<usize>>,
168    import_ext: ImportExt,
169    // v0.115: whether the build emits the contract guard (dev/test). The runner
170    // attack relies on the guard to assert `ensures`, so it is emitted only when
171    // the guard is (they are always paired — `bynk test` sets both).
172    contracts: bool,
173    // v0.132: running set of already-emitted barrel output paths, shared with the
174    // integration pass so a commons imported by both is barrelled exactly once.
175    emitted_barrels: &mut HashSet<PathBuf>,
176    // #1883, slice 3: the declared assets, for `svc.GET(asset)` in a case.
177    asset_files: &TestAssetFiles,
178    // #2842: the stored snapshot files, by project-relative path.
179    snapshot_files: Option<&BTreeMap<String, String>>,
180    // P4b (#2608): each `D1` database's migrations, run on every test database.
181    d1_migrations: &D1Migrations,
182    // #3108: the schemas those migrations build, which a case's literal D1
183    // statements are prepared against (`None` under `[check] d1_sql = false`).
184    d1_sql: Option<&bynk_check::d1_sql::D1Sql>,
185    // #1975: each user adapter's binding module, as an extensionless path
186    // from the output root, for a test that builds the binding for real.
187    binding_modules: &HashMap<String, String>,
188    // #2052: each event's effective schema version, keyed `<unit>.<Event>`
189    // (`emit_project`'s `schema_effective_versions`), for the default envelope
190    // of a `svc.event(e)` address.
191    schema_versions: &HashMap<String, i64>,
192    // #2050: each unit's resolved callees, for [`target_emits_events`].
193    unit_callees: &HashMap<String, HashMap<ExprId, bynk_check::checker::Callee>>,
194    // #2052: each events service's shape, for whether `svc.event(e)` forwards the
195    // envelope (`EventSubscriberShape::wants_envelope`).
196    unit_event_subscriber_shapes: &HashMap<
197        String,
198        HashMap<String, bynk_model::EventSubscriberShape>,
199    >,
200    // The driver's `project_mentions_encode_plain(parsed)` (#2991), which stays there: a suite
201    // calling `Json.encodePlain` needs its own `Option` encoders to carry the plain branch.
202    plain_json: bool,
203    errors: &mut Vec<CompileError>,
204    refs: &mut RefSink,
205    tys: &Arc<Types>,
206) -> (Vec<StagedFile>, Vec<RunnableTest>) {
207    let mut outputs: Vec<StagedFile> = Vec::new();
208    let mut runnable_tests: Vec<RunnableTest> = Vec::new();
209
210    let ready = test_suites::phase_test_bodies(
211        test_groups,
212        parsed,
213        kinds,
214        unit_tables,
215        exports_visibility,
216        unit_consumes,
217        unit_consumes_aliases,
218        unit_uses,
219        broken,
220        errors,
221        refs,
222        &mut bynk_check::locals::LocalsSink::new(),
223        tys,
224        d1_sql,
225    );
226
227    let mut sorted_targets: Vec<&String> = ready.keys().collect();
228    sorted_targets.sort();
229
230    for target_name in sorted_targets {
231        let target_stubs = &ready[target_name];
232        // `ready` only contains targets `phase_test_bodies` resolved against
233        // `kinds` — this lookup cannot miss.
234        let target_kind = *kinds
235            .get(target_name)
236            .expect("phase_test_bodies only returns targets it resolved against `kinds`");
237        let indices = test_groups.get(target_name).unwrap();
238        // #1814: the types the target's privileged view reaches but does not
239        // import, computed once per target for every runner below.
240        let hidden =
241            test_suites::privileged_view(target_name, unit_tables, unit_uses, unit_consumes)
242                .map(|v| v.hidden)
243                .unwrap_or_default();
244
245        // -- Phase 5: emit TypeScript test module. --
246        let runtime_use = RuntimeUse::default();
247        let emit_out = emit_test_module(
248            target_name,
249            target_kind,
250            indices,
251            parsed,
252            target_stubs,
253            unit_tables,
254            unit_consumes,
255            unit_consumes_aliases,
256            unit_uses,
257            unit_flattened,
258            exports_visibility,
259            import_ext,
260            contracts,
261            &hidden,
262            asset_harness(
263                target_name,
264                unit_uses,
265                unit_consumes,
266                unit_tables,
267                asset_files,
268            ),
269            fixture_consts(indices, parsed, asset_files),
270            binding_modules,
271            schema_versions,
272            unit_event_subscriber_shapes.get(target_name),
273            target_emits_events(
274                target_name,
275                target_kind,
276                unit_tables,
277                unit_flattened,
278                unit_callees,
279            ),
280            d1_migrations,
281            snapshot_files,
282            plain_json,
283            &runtime_use,
284            tys,
285        );
286        let emit_out = if drain_internal_faults(errors, &runtime_use) {
287            None
288        } else {
289            emit_out
290        };
291        if let Some((path, program, source_map, runnable)) = emit_out {
292            outputs.push(StagedFile {
293                output_path: path,
294                document: Document::Ts(program),
295                source_map,
296                debug_metadata: None,
297            });
298            runnable_tests.push(runnable);
299
300            // v0.132: the module imports the target and each of its `consumes` /
301            // `uses` targets as a namespace (`import * as ns from "./<name>.js"`).
302            // Any of those that is a multi-file commons has no `out/<name>.ts`, so
303            // emit an aggregating barrel (deduped) to make the import resolve.
304            let mut imported: Vec<&str> = vec![target_name.as_str()];
305            if let Some(consumed) = unit_consumes.get(target_name) {
306                imported.extend(consumed.iter().map(String::as_str));
307            }
308            if let Some(used) = unit_uses.get(target_name) {
309                imported.extend(used.iter().map(String::as_str));
310            }
311            // #1814: and the owner of each reached type it imports.
312            imported.extend(hidden.values().map(String::as_str));
313            for name in imported {
314                if let Some(barrel) = crate::emitter::commons_barrel::emit_commons_barrel(
315                    name,
316                    groups,
317                    parsed,
318                    import_ext,
319                    emitted_barrels,
320                    &[],
321                ) {
322                    outputs.push(barrel);
323                }
324            }
325        }
326    }
327
328    // v0.16: the top-level `tests/main.ts` runner is emitted once by the caller
329    // after both unit- and integration-test passes, so it can aggregate both.
330    (outputs, runnable_tests)
331}
332
333/// P5.4: `test integration "name"` suite processing. Validates the `wires`
334/// participant set (existence, ≥ 2, no duplicates, full `consumes` closure),
335/// type-checks each case body as a cross-context call from a synthetic
336/// harness root that consumes every participant, and emits a TypeScript
337/// module that stands the participants up as in-process Workers wired by
338/// simulated Service Bindings and runs the cases across the real
339/// serialise/deserialise wire. The checking half (participant inference, the
340/// `system`-needs-a-serialisation-edge gate, duplicate-case-name detection,
341/// the harness cross-context view, and per-case body type-checking) now
342/// lives in [`test_suites::phase_integration_bodies`], which hands back each
343/// ready group's harness [`resolver::CrossContextInfo`] — the one piece
344/// worth not recomputing here (built from clone-heavy maps).
345/// `participants`/`uses_targets`/`case_inputs` are cheap and pure, so the
346/// loop below recomputes them exactly as this function always did, using the
347/// now-relocated [`test_suites::infer_participants`].
348/// The `D1` inputs an integration suite is processed with: each database's
349/// migrations, run on every test database (P4b, #2608), and the schemas they
350/// build, which a `D1.peek` read in a case is prepared against (#3147; `None`
351/// under `[check] d1_sql = false`).
352#[derive(Clone, Copy)]
353pub struct IntegrationD1<'a> {
354    pub migrations: &'a D1Migrations,
355    pub sql: Option<&'a bynk_check::d1_sql::D1Sql>,
356}
357
358impl<'a> IntegrationD1<'a> {
359    pub fn new(migrations: &'a D1Migrations, sql: Option<&'a bynk_check::d1_sql::D1Sql>) -> Self {
360        Self { migrations, sql }
361    }
362}
363
364#[allow(clippy::too_many_arguments)]
365pub fn process_integration_tests(
366    integration_groups: &BTreeMap<String, Vec<usize>>,
367    parsed: &[ParsedFile],
368    kinds: &BTreeMap<String, UnitKind>,
369    unit_tables: &HashMap<String, UnitTable>,
370    unit_consumes: &HashMap<String, Vec<String>>,
371    unit_consumes_aliases: &HashMap<String, HashMap<String, String>>,
372    unit_uses: &HashMap<String, Vec<String>>,
373    // #3162: the declarations recovery skipped, per unit.
374    broken: &bynk_check::project_model::BrokenDeclNames,
375    // v0.132: production unit name -> its `parsed` file indices (see `process_tests`).
376    groups: &BTreeMap<String, Vec<usize>>,
377    // v0.132: barrel-path dedup set shared with the unit-test pass.
378    emitted_barrels: &mut HashSet<PathBuf>,
379    // #1883, slice 3: the declared assets, for `svc.GET(asset)` in a case.
380    asset_files: &TestAssetFiles,
381    // P4b (#2608): each `D1` database's migrations, run on every test database.
382    d1: IntegrationD1<'_>,
383    // #1959: each context's Worker bindings, bound on each participant's
384    // `env`. `None` when earlier errors stop the build anyway.
385    context_bindings: Option<&BTreeMap<String, Vec<WorkerBinding>>>,
386    // `bynk_check::symbols::discover_event_subscribers`' table.
387    event_subscribers: &BTreeMap<(String, String), Vec<(String, String)>>,
388    // #2138: a remote test build (`CompileOptions::remote_tests`).
389    remote: Option<&crate::emit_model::RemoteTests>,
390    // The driver's `project_mentions_encode_plain(parsed)` (#2991), which stays there: a suite
391    // calling `Json.encodePlain` needs its own `Option` encoders to carry the plain branch.
392    plain_json: bool,
393    errors: &mut Vec<CompileError>,
394    refs: &mut RefSink,
395    tys: &Arc<Types>,
396) -> (Vec<StagedFile>, Vec<RunnableTest>) {
397    let mut outputs: Vec<StagedFile> = Vec::new();
398    let mut runnables: Vec<RunnableTest> = Vec::new();
399
400    let ready = test_suites::phase_integration_bodies(
401        integration_groups,
402        parsed,
403        kinds,
404        unit_tables,
405        unit_consumes,
406        unit_consumes_aliases,
407        unit_uses,
408        broken,
409        errors,
410        refs,
411        tys,
412        d1.sql,
413    );
414    let d1_migrations = d1.migrations;
415
416    let mut sorted: Vec<&String> = ready.keys().collect();
417    sorted.sort();
418
419    for group_name in sorted {
420        let indices = integration_groups.get(group_name).unwrap();
421        let first = indices[0];
422        let Some(decl) = parsed[first].integration() else {
423            continue;
424        };
425        // v0.118: there is no `suite` string any more — the wired suite is named
426        // for its target context. The participant set is INFERRED from the
427        // target's transitive `consumes` closure (no `wires` list).
428        let suite_target = decl.target.joined();
429        let suite_name = suite_target.clone();
430        // #1856: contexts only; a capability-only unit is provided in-process.
431        let participants = test_suites::infer_participants(&suite_target, unit_consumes, kinds);
432        // #1959: the Workers the harness stands up: also every subscriber to
433        // a participant's events, so the fan-out has somewhere to deliver.
434        let harness_participants = test_suites::infer_harness_participants(
435            &suite_target,
436            unit_consumes,
437            kinds,
438            event_subscribers,
439        );
440        // `ready` only contains groups `phase_integration_bodies` built a
441        // harness cross-context view for — this lookup cannot miss.
442        let cross_context = ready
443            .get(group_name)
444            .expect("phase_integration_bodies only returns groups it resolved");
445
446        let mut uses_targets: Vec<String> = Vec::new();
447        for &i in indices {
448            if let Some(d) = parsed[i].integration() {
449                for u in &d.uses {
450                    let q = u.target.joined();
451                    if !uses_targets.contains(&q) {
452                        uses_targets.push(q);
453                    }
454                }
455            }
456        }
457
458        // -- Emit the integration module. --
459        // Collect each case with the fragment file it came from, so a suite
460        // split across files maps each case body under its own source.
461        let mut case_inputs: Vec<SystemCaseInput> = Vec::new();
462        for &i in indices {
463            let Some(d) = parsed[i].integration() else {
464                continue;
465            };
466            let rel_path = parsed[i].identity_path().to_string_lossy().into_owned();
467            let map_source = parsed[i].map_source_name();
468            for case in &d.cases {
469                case_inputs.push(SystemCaseInput {
470                    case,
471                    suite_fns: test_suites::SuiteItems::of(d),
472                    tier: case_effective_tier(case, d),
473                    env: bynk_check::test_env::case_env(d, case, asset_files.fixtures),
474                    env_values: bynk_check::test_env::case_env_values(d, case),
475                    source: parsed[i].source(),
476                    rel_path: rel_path.clone(),
477                    map_source: map_source.clone(),
478                });
479            }
480        }
481        // #2134: an `env` entry lands on every participant's Worker `env`, so
482        // it may not name a binding one of them declares, nor a key the
483        // harness sets there itself (a call edge's key, a foreign caller's
484        // secret), which would silently win over it. `context_bindings` is
485        // `None` when earlier errors stop the build, and the check with it.
486        if let Some(all) = context_bindings {
487            let mut names: BTreeMap<String, String> = BTreeMap::new();
488            for p in &harness_participants {
489                for b in all.get(p).into_iter().flatten() {
490                    names
491                        .entry(b.name.clone())
492                        .or_insert_with(|| format!("a binding of `{p}`'s Worker"));
493                }
494                for secret in foreign_caller_secrets(p, unit_tables) {
495                    names.entry(secret).or_insert_with(|| {
496                        format!("a foreign caller's secret the harness sets on `{p}`'s Worker")
497                    });
498                }
499            }
500            // #2137: the harness clock the harness puts on every participant.
501            names.entry("__bynkClock".to_string()).or_insert_with(|| {
502                "the harness clock the test harness sets on the participants' Workers".to_string()
503            });
504            // Every edge key the harness may set, from its own caller and
505            // between participants (`emit_integration_harness`).
506            let callers = std::iter::once(HARNESS_CALLER)
507                .chain(harness_participants.iter().map(String::as_str));
508            for key in callers.filter_map(wire_format::edge_key_from).chain(
509                harness_participants
510                    .iter()
511                    .filter_map(|p| wire_format::edge_key_to(p)),
512            ) {
513                names.entry(key).or_insert_with(|| {
514                    "a call-edge key the harness sets on the participants' Workers".to_string()
515                });
516            }
517            for &i in indices {
518                if let Some(d) = parsed[i].integration() {
519                    bynk_check::test_env::check_env_binding_clash(d, &names, errors);
520                }
521            }
522        }
523        // #1814: the harness view the cases were checked in.
524        let view =
525            test_suites::integration_view(&uses_targets, &participants, unit_tables, unit_uses);
526        let runtime_use = RuntimeUse::default();
527        let emitted = emit_integration_module(
528            &suite_name,
529            &participants,
530            &harness_participants,
531            context_bindings,
532            &uses_targets,
533            &view,
534            cross_context,
535            unit_tables,
536            &case_inputs,
537            participants.first().and_then(|target| {
538                asset_harness(target, unit_uses, unit_consumes, unit_tables, asset_files)
539            }),
540            fixture_consts(indices, parsed, asset_files),
541            remote,
542            d1_migrations,
543            errors,
544            tys,
545            plain_json,
546            &runtime_use,
547        );
548        let emitted = if drain_internal_faults(errors, &runtime_use) {
549            None
550        } else {
551            emitted
552        };
553        if let Some((path, program, source_map, runnable)) = emitted {
554            outputs.push(StagedFile {
555                output_path: path,
556                document: Document::Ts(program),
557                source_map,
558                debug_metadata: None,
559            });
560            runnables.push(runnable);
561
562            // v0.132: the integration module imports each `uses` commons as a
563            // namespace (`import * as ns from "./<name>.js"`); participants come
564            // in through `../workers/`, so only `uses_targets` need a barrel.
565            // Emit one (deduped) for each that is a multi-file commons.
566            // #1814: and the owner of each reached type it imports.
567            let owners: BTreeSet<&String> = view.hidden.values().collect();
568            for name in uses_targets.iter().chain(owners) {
569                if let Some(barrel) = crate::emitter::commons_barrel::emit_commons_barrel(
570                    name,
571                    groups,
572                    parsed,
573                    ImportExt::Js,
574                    emitted_barrels,
575                    &[],
576                ) {
577                    outputs.push(barrel);
578                }
579            }
580        }
581    }
582
583    (outputs, runnables)
584}
585
586/// I3 (#1971): the secrets participant `p`'s foreign callers sign under, which
587/// the harness sets on its `env` so a case calling `by <ForeignActor>` signs
588/// as that actor.
589fn foreign_caller_secrets(p: &str, unit_tables: &HashMap<String, UnitTable>) -> Vec<String> {
590    let Some(t) = unit_tables.get(p) else {
591        return Vec::new();
592    };
593    let mut secrets: Vec<String> = t
594        .services
595        .values()
596        .flat_map(|s| s.handlers.iter())
597        .filter_map(|h| bynk_check::actors::call_admission_for(h, &t.actors))
598        .flat_map(|a| a.foreign.into_iter().map(|f| f.secret))
599        .collect();
600    secrets.sort();
601    secrets.dedup();
602    secrets
603}
604
605/// v0.118: one `system`-tier case paired with the fragment file it was declared
606/// in, so [`emit_integration_module`] maps each case body under its own source.
607struct SystemCaseInput<'a> {
608    case: &'a Case,
609    /// #2834: the declaring suite's helper `fn`s.
610    suite_fns: test_suites::SuiteItems<'a>,
611    /// The case's effective tier, which its suite default may supply.
612    tier: bynk_syntax::ast::TestTier,
613    /// #2134: the variables and secrets the case runs with (its suite's
614    /// `env`, overlaid by its own), each fixture as its text.
615    env: BTreeMap<String, String>,
616    /// #2956: the same entries as written, for the case runner, which names
617    /// a fixture's module-level constant rather than repeat its text.
618    env_values: BTreeMap<String, bynk_check::test_env::EnvValue>,
619    source: &'a str,
620    rel_path: String,
621    map_source: String,
622}
623
624/// Type-reference builders shared by the split-out test modules.
625#[cfg(test)]
626mod test_support {
627    use bynk_syntax::ast::{BaseType, Ident, TypeRef};
628    use bynk_syntax::span::Span;
629
630    pub(super) fn named(n: &str) -> TypeRef {
631        TypeRef::Named(Ident {
632            name: n.to_string(),
633            span: Span::default(),
634        })
635    }
636    pub(super) fn base(b: BaseType) -> TypeRef {
637        TypeRef::Base(b, Span::default())
638    }
639}
640
641#[cfg(test)]
642mod tests {
643    use super::*;
644    use bynk_syntax::ast::{BaseType, TypeRef};
645    use bynk_syntax::span::Span;
646
647    // -- the unified emitter type-ref renderers -------------------------------
648    use super::test_support::{base, named};
649
650    /// A type reference as the text of its `TsType` node.
651    fn ts_type_ref(r: &TypeRef) -> String {
652        bynk_ts::print_type(&emitter::ts_types::ts_type_of(r))
653    }
654
655    fn faulted_use() -> RuntimeUse {
656        let ru = RuntimeUse::default();
657        ru.note_internal_fault(Span::new(1, 2), "receiver namespace".to_string());
658        ru
659    }
660
661    #[test]
662    fn a_fault_is_reported_when_the_project_has_no_other_error() {
663        let mut errors = Vec::new();
664        assert!(drain_internal_faults(&mut errors, &faulted_use()));
665        assert_eq!(errors.len(), 1);
666        assert_eq!(errors[0].category, crate::emitter::MISSING_CHECKER_FACT);
667    }
668
669    #[test]
670    fn a_fault_in_a_project_that_already_has_errors_is_drained_not_reported() {
671        let mut errors = vec![CompileError::new("test.other", Span::new(0, 1), "x")];
672        let ru = faulted_use();
673        assert!(
674            drain_internal_faults(&mut errors, &ru),
675            "the output is still dropped"
676        );
677        assert_eq!(errors.len(), 1, "no internal error on top of the real one");
678        assert!(ru.take_faults().is_empty(), "drained");
679    }
680
681    #[test]
682    fn a_fault_beside_only_warnings_is_still_reported() {
683        let warning = bynk_syntax::diagnostics::REGISTRY
684            .iter()
685            .find(|d| d.severity == bynk_syntax::Severity::Warning)
686            .expect("the registry has a warning")
687            .code;
688        let mut errors = vec![CompileError::new(warning, Span::new(0, 1), "x")];
689        let ru = faulted_use();
690        assert!(drain_internal_faults(&mut errors, &ru));
691        assert_eq!(errors.len(), 2, "the warning, then the reported fault");
692        assert_eq!(errors[1].category, crate::emitter::MISSING_CHECKER_FACT);
693    }
694
695    #[test]
696    fn ts_type_ref_bases_and_generics() {
697        assert_eq!(ts_type_ref(&base(BaseType::Int)), "number");
698        assert_eq!(ts_type_ref(&base(BaseType::Float)), "number");
699        assert_eq!(ts_type_ref(&base(BaseType::String)), "string");
700        assert_eq!(ts_type_ref(&base(BaseType::Bool)), "boolean");
701        assert_eq!(ts_type_ref(&named("Order")), "Order");
702        assert_eq!(
703            ts_type_ref(&TypeRef::List(Box::new(named("Order")), Span::default())),
704            "readonly Order[]"
705        );
706        assert_eq!(
707            ts_type_ref(&TypeRef::Option(
708                Box::new(base(BaseType::Int)),
709                Span::default()
710            )),
711            "Option<number>"
712        );
713        assert_eq!(
714            ts_type_ref(&TypeRef::Effect(
715                Box::new(TypeRef::Unit(Span::default())),
716                Span::default()
717            )),
718            "globalThis.Promise<void>"
719        );
720        assert_eq!(
721            ts_type_ref(&TypeRef::Map(
722                Box::new(base(BaseType::String)),
723                Box::new(named("V")),
724                Span::default()
725            )),
726            "ReadonlyMap<string, V>"
727        );
728        assert_eq!(
729            ts_type_ref(&TypeRef::Result(
730                Box::new(named("T")),
731                Box::new(named("E")),
732                Span::default()
733            )),
734            "Result<T, E>"
735        );
736        assert_eq!(
737            ts_type_ref(&TypeRef::HttpResult(Box::new(named("T")), Span::default())),
738            "HttpResult<T>"
739        );
740        assert_eq!(
741            ts_type_ref(&TypeRef::ValidationError(Span::default())),
742            "ValidationError"
743        );
744        assert_eq!(
745            ts_type_ref(&TypeRef::DecodeError(Span::default())),
746            "DecodeError"
747        );
748    }
749
750    #[test]
751    fn ts_type_ref_fn_uses_positional_param_names() {
752        let f = TypeRef::Fn(
753            vec![base(BaseType::Int), named("Order")],
754            Box::new(TypeRef::Unit(Span::default())),
755            Span::default(),
756        );
757        assert_eq!(ts_type_ref(&f), "(a0: number, a1: Order) => void");
758    }
759
760    #[test]
761    fn ts_type_ref_qualified_prefixes_only_scoped_names() {
762        let mut scope: HashSet<String> = HashSet::new();
763        scope.insert("Order".to_string());
764        // A named type in the privileged scope is qualified with the namespace.
765        assert_eq!(
766            bynk_ts::print_type(&emitter::ts_types::ts_type_ref_qualified_ts_type(
767                &named("Order"),
768                &scope,
769                "Ns"
770            )),
771            "Ns.Order"
772        );
773        // A named type outside the scope is left bare.
774        assert_eq!(
775            bynk_ts::print_type(&emitter::ts_types::ts_type_ref_qualified_ts_type(
776                &named("Other"),
777                &scope,
778                "Ns"
779            )),
780            "Other"
781        );
782        // Qualification recurses through generic arguments.
783        assert_eq!(
784            bynk_ts::print_type(&emitter::ts_types::ts_type_ref_qualified_ts_type(
785                &TypeRef::List(Box::new(named("Order")), Span::default()),
786                &scope,
787                "Ns"
788            )),
789            "readonly Ns.Order[]"
790        );
791        // Base types are unaffected by qualification.
792        assert_eq!(
793            bynk_ts::print_type(&emitter::ts_types::ts_type_ref_qualified_ts_type(
794                &base(BaseType::Int),
795                &scope,
796                "Ns"
797            )),
798            "number"
799        );
800    }
801
802    /// #2138: only a remote build reads `BYNK_TEST_RUN_ID`; an in-process
803    /// module's `run.id` is `"local"` whatever the environment says.
804    #[test]
805    fn run_id_reads_the_environment_only_in_a_remote_build() {
806        let remote = bynk_ts::print_stmt(&run_id_stmt(true), 0);
807        assert!(remote.contains("BYNK_TEST_RUN_ID"));
808        let local = bynk_ts::print_stmt(&run_id_stmt(false), 0);
809        assert!(!local.contains("BYNK_TEST_RUN_ID"));
810        assert!(local.contains("\"local\""));
811    }
812}