Skip to main content

bynk_driver/
test_json.rs

1//! v0.59: the `bynk test --format json` result model, plus the parser that
2//! folds the runner's NDJSON event stream into it.
3//!
4//! The generated `tests/main.ts` runner emits one JSON event per line when
5//! `BYNK_TEST_FORMAT=ndjson` (an **internal** protocol — proposal v0.59,
6//! Decision 2); `run_test` captures that stream and renders the single pinned
7//! **document** below. The document is built from `#[derive(Serialize)]` structs
8//! in **declaration order** — field order *is* the contract (the discipline
9//! `bynk/src/report.rs` calls out); we never use `serde_json::json!`, so a
10//! `preserve_order` feature enabled elsewhere in a build can't reorder it.
11//!
12//! There are three terminal states, distinguished by the consumer on the
13//! presence/`kind` of `error`:
14//! - **normal** — `suites` present, no `error` (may have `failed > 0`);
15//! - **compile** — the project never compiled: no `suites`, `error.kind ==
16//!   "compile"` carrying the `bynk` diagnostic lines;
17//! - **runtime** — the runner started then died before `run-end`: the observed
18//!   `suites` prefix *and* `error.kind == "runtime"` with the captured stderr.
19//!
20//! Two more `error.kind`s are additive: `"timeout"` (a `--mutate` run killed at
21//! its deadline) and `"no_tests"` (`--require-tests` on a project with none).
22
23use crate::emsg;
24use serde::Serialize;
25
26/// The pinned `bynk test --format json` document.
27#[derive(Debug, PartialEq, Serialize)]
28pub struct TestRun {
29    pub passed: u32,
30    pub failed: u32,
31    /// #2138: the cases a remote run skipped (`--skip-unsupported`). Absent
32    /// when zero, so every other document's layout is unchanged.
33    #[serde(skip_serializing_if = "is_zero")]
34    pub skipped: u32,
35    #[serde(skip_serializing_if = "Option::is_none")]
36    pub suites: Option<Vec<Suite>>,
37    #[serde(skip_serializing_if = "Option::is_none")]
38    pub error: Option<TestError>,
39    /// #854: the optional coverage block, present only for a `--coverage` run
40    /// that produced attributable lines. Last field, so every existing
41    /// document's byte layout is unchanged when it is absent.
42    #[serde(skip_serializing_if = "Option::is_none")]
43    pub coverage: Option<Coverage>,
44    /// #2138: where the `system` suites ran — `"remote:<target>"` under
45    /// `--against`. Absent for an in-process run. Last field, so every
46    /// existing document's layout is unchanged.
47    #[serde(skip_serializing_if = "Option::is_none")]
48    pub transport: Option<String>,
49    /// #2842: what the run did to the project's snapshots — written, updated and
50    /// obsolete counts. Absent for a project with no snapshot. Last field, so
51    /// every existing document's byte layout is unchanged.
52    #[serde(skip_serializing_if = "Option::is_none")]
53    pub snapshots: Option<crate::snapshots::Counts>,
54    /// #3585: the value a `bynk eval` snippet ended in. Absent for every run
55    /// that is not an evaluation. Last field, so every existing document's byte
56    /// layout is unchanged.
57    #[serde(skip_serializing_if = "Option::is_none")]
58    pub eval: Option<EvalValue>,
59}
60
61/// #3585: what a `bynk eval` snippet evaluated to: the wire shape of its final
62/// expression (what `Json.encode` gives it) and that expression's type.
63#[derive(Debug, Clone, PartialEq, Serialize)]
64pub struct EvalValue {
65    /// Absent when the value has no wire shape to report.
66    #[serde(skip_serializing_if = "Option::is_none")]
67    pub value: Option<serde_json::Value>,
68    #[serde(rename = "type")]
69    pub ty: String,
70}
71
72fn is_zero(n: &u32) -> bool {
73    *n == 0
74}
75
76/// The `coverage` block: whole-run totals plus one entry per measured `.bynk`
77/// file, keyed by project-relative path. Attributed to `.bynk` source lines, not
78/// emitted `.ts`/`.js` (issue #854); generated glue with no source origin is
79/// out-of-scope, never counted.
80#[derive(Debug, PartialEq, Serialize)]
81pub struct Coverage {
82    /// Covered executable lines across every measured file.
83    pub covered: u32,
84    /// Total executable lines across every measured file.
85    pub lines: u32,
86    /// Whole-run percentage (0–100), rounded.
87    pub percent: u32,
88    pub files: Vec<FileCoverage>,
89}
90
91/// One measured `.bynk` file's line coverage.
92#[derive(Debug, PartialEq, Serialize)]
93pub struct FileCoverage {
94    pub path: String,
95    pub covered: u32,
96    pub lines: u32,
97    pub percent: u32,
98    /// Uncovered executable lines, 1-based and ascending.
99    pub uncovered: Vec<u32>,
100    /// #2104: covered executable lines, 1-based and ascending. With
101    /// `uncovered`, every executable line, so an editor can mark both. Named
102    /// `covered_lines` because `covered` is already the count. Additive and
103    /// last, so a consumer that predates it is unaffected.
104    pub covered_lines: Vec<u32>,
105}
106
107impl From<&crate::coverage::CoverageReport> for Coverage {
108    fn from(r: &crate::coverage::CoverageReport) -> Self {
109        Coverage {
110            covered: r.total_covered(),
111            lines: r.total_lines(),
112            percent: r.total_percent(),
113            files: r
114                .files
115                .iter()
116                .map(|f| FileCoverage {
117                    path: f.path.clone(),
118                    covered: f.covered,
119                    lines: f.total,
120                    percent: crate::coverage::percent(f.covered, f.total),
121                    uncovered: f.uncovered.clone(),
122                    covered_lines: f.covered_lines.clone(),
123                })
124                .collect(),
125        }
126    }
127}
128
129#[derive(Debug, PartialEq, Serialize)]
130pub struct Suite {
131    pub name: String,
132    pub kind: String,
133    pub cases: Vec<Case>,
134}
135
136#[derive(Debug, PartialEq, Serialize)]
137pub struct Case {
138    pub name: String,
139    /// `"pass"` / `"fail"` from a run, `"skipped"` for a case a remote run
140    /// skipped (#2138), or `"discovered"` in a `--no-run`
141    /// discovery document (the case was listed, not executed).
142    pub outcome: String,
143    #[serde(skip_serializing_if = "Option::is_none")]
144    pub message: Option<String>,
145    #[serde(skip_serializing_if = "Option::is_none")]
146    pub location: Option<Location>,
147    /// #2138 (track §3.6): how often `--settle` retried the case's `expect`s
148    /// in a remote run. Absent when it wasn't retried.
149    #[serde(skip_serializing_if = "Option::is_none")]
150    pub retries: Option<u32>,
151    /// #3437: how many failures a detached effect (`e.detach()`) reported while the
152    /// case ran, each a fault or an `Err`. A report does not fail the case, as on
153    /// Workers (ADR 0478), so the count is how a noisy detach shows up. Absent when
154    /// none was reported.
155    #[serde(skip_serializing_if = "Option::is_none")]
156    pub detached_failures: Option<u32>,
157    /// The case's effective tier, `"unit"`, `"integration"` or `"system"`
158    /// (ADR 0153), attached from the compile's case table: the suite `kind`
159    /// follows the module name and cannot say it. Appended last and omitted when
160    /// absent (a property has none), so a document without it keeps its layout.
161    #[serde(skip_serializing_if = "Option::is_none")]
162    pub tier: Option<String>,
163    /// A failed generative case: `"property"` or `"history"`. Set with `seed`,
164    /// whatever the failure was, because a draw depends on the seed even when the
165    /// body threw something that is not an assertion. Follows `tier`; see the ADR
166    /// for appending optional `Case` fields.
167    #[serde(skip_serializing_if = "Option::is_none")]
168    pub kind: Option<String>,
169    /// The run's root seed, as the `0x…` text `--seed` accepts. With `--case`, it
170    /// reproduces the failed case's stream.
171    #[serde(skip_serializing_if = "Option::is_none")]
172    pub seed: Option<String>,
173    /// The shrunk counterexample as the runner rendered it (`p = 73`, or the
174    /// shrunk sequence of a history), when shrinking produced one.
175    #[serde(skip_serializing_if = "Option::is_none")]
176    pub counterexample: Option<String>,
177    /// #2272: the invariant or transition a violated case named, when a violation
178    /// failed it. Appended after `counterexample`; absent otherwise.
179    #[serde(skip_serializing_if = "Option::is_none")]
180    pub violation: Option<Violation>,
181    /// #2272: the steps of a failed history that an agent refused, each with the
182    /// declaration that refused it. A refusal is data on the step, not a failure of
183    /// its own, so `violation` does not say it. Appended after `violation`; absent
184    /// when no step was refused.
185    #[serde(skip_serializing_if = "Option::is_none")]
186    pub refusals: Option<Vec<Refusal>>,
187    /// #2461: where the case came from, `"doc"` for a doc-comment example marked
188    /// `bynk test`. Appended after `refusals` and absent for every other case, so a
189    /// document without doc examples keeps its layout; a reader treats a missing
190    /// `origin` as an ordinary `case`.
191    #[serde(skip_serializing_if = "Option::is_none")]
192    pub origin: Option<String>,
193    /// #2685: the warnings a smoke case raised, which do not fail it. Appended
194    /// after `origin` (and so before the stream's `durationMs`) and absent when
195    /// the case raised none, so every other document keeps its layout.
196    #[serde(skip_serializing_if = "Option::is_none")]
197    pub warnings: Option<Vec<Warning>>,
198    /// How long the case ran, in milliseconds, as its module measured it (#2267
199    /// stage 2). Never part of the JSON document, which stays deterministic; the
200    /// `ndjson` stream's `case` event carries it, last.
201    #[serde(skip)]
202    pub duration_ms: Option<f64>,
203}
204
205/// #2685: a warning a case raised without failing: a smoke case's answer
206/// (`bynk.test.smoke_undeclared_status`) outside the statuses its route's handler
207/// can return.
208#[derive(Debug, Clone, PartialEq, Serialize)]
209pub struct Warning {
210    pub code: String,
211    /// The route, as `METHOD /path`.
212    pub route: String,
213    /// The status the route answered.
214    pub status: u16,
215    /// The statuses its handler declares, ascending.
216    pub declared: Vec<u16>,
217    /// The warning as a sentence, as it is written to stderr.
218    pub message: String,
219}
220
221impl Warning {
222    /// The warning a runner `warning` event describes; `None` for one missing a
223    /// field.
224    pub(crate) fn from_event(value: &serde_json::Value) -> Option<Warning> {
225        Some(Warning {
226            code: value.get("code")?.as_str()?.to_string(),
227            route: value.get("route")?.as_str()?.to_string(),
228            status: u16::try_from(value.get("status")?.as_u64()?).ok()?,
229            declared: value
230                .get("declared")?
231                .as_array()?
232                .iter()
233                .filter_map(|n| u16::try_from(n.as_u64()?).ok())
234                .collect(),
235            message: value.get("message")?.as_str()?.to_string(),
236        })
237    }
238
239    /// The line a run writes to stderr for this warning.
240    pub fn line(&self, program: &str) -> String {
241        format!("{program} test: warning[{}]: {}", self.code, self.message)
242    }
243}
244
245#[derive(Debug, PartialEq, Serialize)]
246pub struct Location {
247    pub path: String,
248    pub line: u32,
249    pub col: u32,
250}
251
252/// #2272: the declaration a violated invariant or transition names. `kind` is the
253/// declaration's own kind, `"invariant"` or `"transition"`, which the name alone
254/// cannot say (an invariant and a transition may share one).
255#[derive(Debug, PartialEq, Serialize)]
256pub struct Violation {
257    pub kind: String,
258    pub agent: String,
259    pub name: String,
260    pub location: Option<Location>,
261}
262
263/// #2272: a step of a driven history that an agent refused. `index` is the step's
264/// position in the shrunk sequence the case reports (from 0), `call` the handler it
265/// called, and the rest names the declaration that refused it, as [`Violation`] does.
266#[derive(Debug, PartialEq, Serialize)]
267pub struct Refusal {
268    pub index: u32,
269    pub call: String,
270    pub kind: String,
271    pub agent: String,
272    pub name: String,
273    pub location: Option<Location>,
274}
275
276#[derive(Debug, PartialEq, Serialize)]
277pub struct TestError {
278    pub kind: String,
279    #[serde(skip_serializing_if = "Option::is_none")]
280    pub message: Option<String>,
281    /// `bynk` diagnostic lines (`path:line:col: severity[category]: message`),
282    /// for `kind == "compile"`. Empty (and omitted) otherwise.
283    #[serde(skip_serializing_if = "Vec::is_empty")]
284    pub diagnostics: Vec<String>,
285    /// Captured stderr from a crashed run, for `kind == "runtime"`.
286    #[serde(skip_serializing_if = "Option::is_none")]
287    pub stderr: Option<String>,
288}
289
290impl TestRun {
291    /// A normal run with no suites (no tests, or `--no-run`).
292    pub fn empty() -> Self {
293        TestRun {
294            passed: 0,
295            failed: 0,
296            skipped: 0,
297            suites: Some(Vec::new()),
298            error: None,
299            coverage: None,
300            transport: None,
301            snapshots: None,
302            eval: None,
303        }
304    }
305
306    /// Attach a coverage block (`--coverage`, issue #854). A report with no
307    /// attributed line is dropped rather than serialising an empty block, so a
308    /// coverage run over a project with nothing measurable reads like a normal
309    /// run.
310    pub fn with_coverage(mut self, report: &crate::coverage::CoverageReport) -> Self {
311        if !report.is_empty() {
312            self.coverage = Some(Coverage::from(report));
313        }
314        self
315    }
316
317    /// v0.67: a **discovery** document (`--no-run --format json`) — the suites and
318    /// cases the compile retained, listed without running. `passed`/`failed` are
319    /// 0 and each case carries `outcome: "discovered"` (see [`Case`]), so the
320    /// "every case has an outcome" invariant holds and no consumer mistakes a
321    /// listed case for a result. Reconciles against a later run document: same
322    /// suite `name`/`kind`, same case `name`s.
323    pub fn discovered(suites: Vec<Suite>) -> Self {
324        TestRun {
325            passed: 0,
326            failed: 0,
327            skipped: 0,
328            suites: Some(suites),
329            error: None,
330            coverage: None,
331            transport: None,
332            snapshots: None,
333            eval: None,
334        }
335    }
336
337    /// The document for a run that could not start or complete outside the
338    /// compile step (the runner couldn't be launched, `tsc` rejected the
339    /// emitted TS, or the runner died). No suites — use [`ParsedRun::into_document`]
340    /// when a partial suite prefix was observed.
341    pub fn runtime_error(message: impl Into<String>, stderr: Option<String>) -> Self {
342        TestRun {
343            passed: 0,
344            failed: 0,
345            skipped: 0,
346            suites: None,
347            error: Some(TestError {
348                kind: "runtime".to_string(),
349                message: Some(message.into()),
350                diagnostics: Vec::new(),
351                stderr: stderr.filter(|s| !s.trim().is_empty()),
352            }),
353            coverage: None,
354            transport: None,
355            snapshots: None,
356            eval: None,
357        }
358    }
359
360    /// #3068: `tsc` rejected generated TypeScript. The Bynk diagnostics are
361    /// `compile`-kind lines like any other; the raw `tsc` text rides in `stderr`.
362    pub fn codegen_error(diagnostics: Vec<String>, tsc_output: String) -> Self {
363        let mut run = Self::compile_error(diagnostics);
364        if let Some(e) = run.error.as_mut() {
365            e.stderr = Some(tsc_output).filter(|s| !s.trim().is_empty());
366        }
367        run
368    }
369
370    /// #3069: the document for a run killed after `--mutate`'s per-mutant
371    /// timeout. Its own kind, so no consumer reads a timeout from a message.
372    pub fn timeout_error(message: impl Into<String>) -> Self {
373        let mut run = Self::runtime_error(message, None);
374        if let Some(error) = run.error.as_mut() {
375            error.kind = "timeout".to_string();
376        }
377        run
378    }
379
380    /// #3087: the document for `--require-tests` on a project with no tests.
381    pub fn no_tests_error(message: impl Into<String>) -> Self {
382        let mut run = Self::runtime_error(message, None);
383        if let Some(error) = run.error.as_mut() {
384            error.kind = "no_tests".to_string();
385        }
386        run
387    }
388
389    /// The document for a project that never compiled.
390    pub fn compile_error(diagnostics: Vec<String>) -> Self {
391        TestRun {
392            passed: 0,
393            failed: 0,
394            skipped: 0,
395            suites: None,
396            error: Some(TestError {
397                kind: "compile".to_string(),
398                message: None,
399                diagnostics,
400                stderr: None,
401            }),
402            coverage: None,
403            transport: None,
404            snapshots: None,
405            eval: None,
406        }
407    }
408
409    /// Attach each case's tier from the compile's case table, matched by suite
410    /// and case name (the names the runner reports are the ones discovery lists).
411    /// A case the table does not hold keeps whatever tier it has.
412    /// #2842: the snapshot counts the document reports.
413    pub fn with_snapshots(mut self, counts: Option<crate::snapshots::Counts>) -> Self {
414        self.snapshots = counts;
415        self
416    }
417
418    pub fn with_tiers(mut self, discovered: &[crate::project::DiscoveredSuite]) -> Self {
419        for suite in self.suites.iter_mut().flatten() {
420            let Some(known) = discovered.iter().find(|d| d.name == suite.name) else {
421                continue;
422            };
423            for case in &mut suite.cases {
424                let known_case = known.cases.iter().find(|c| c.name == case.name);
425                if let Some(tier) = known_case.and_then(|c| c.tier) {
426                    case.tier = Some(tier.to_string());
427                }
428                if known_case.is_some_and(|c| c.doc) {
429                    case.origin = Some("doc".to_string());
430                }
431            }
432        }
433        self
434    }
435
436    /// #2138: fold a remote run into the document — its `transport`, and each
437    /// skipped case as an `outcome: "skipped"` case whose `message` is why,
438    /// in its suite (a new `integration` suite when none of that name ran).
439    pub fn with_remote(mut self, transport: String, skipped: &[(String, String, String)]) -> Self {
440        self.transport = Some(transport);
441        self.with_skips(skipped)
442    }
443
444    /// Every warning the run's cases raised (#2685), in the order they ran.
445    pub fn warnings(&self) -> impl Iterator<Item = &Warning> {
446        self.suites
447            .iter()
448            .flatten()
449            .flat_map(|s| &s.cases)
450            .flat_map(|c| c.warnings.iter().flatten())
451    }
452
453    /// Each skipped case as an `outcome: "skipped"` case whose `message` is
454    /// why, in its suite: a remote run's (#2138) or a smoke run's (#2658).
455    pub fn with_skips(mut self, skipped: &[(String, String, String)]) -> Self {
456        if skipped.is_empty() {
457            return self;
458        }
459        self.skipped = u32::try_from(skipped.len()).unwrap_or(u32::MAX);
460        let suites = self.suites.get_or_insert_with(Vec::new);
461        for (suite, case, reason) in skipped {
462            let case = Case {
463                name: case.clone(),
464                outcome: "skipped".to_string(),
465                message: Some(reason.clone()),
466                location: None,
467                retries: None,
468                detached_failures: None,
469                // A remote or smoke run skips only `system` cases.
470                tier: Some("system".to_string()),
471                kind: None,
472                seed: None,
473                counterexample: None,
474                violation: None,
475                refusals: None,
476                origin: None,
477                warnings: None,
478                duration_ms: None,
479            };
480            match suites.iter_mut().find(|s| &s.name == suite) {
481                Some(s) => s.cases.push(case),
482                None => suites.push(Suite {
483                    name: suite.clone(),
484                    kind: "integration".to_string(),
485                    cases: vec![case],
486                }),
487            }
488        }
489        self
490    }
491
492    /// Render to a pretty JSON string (trailing newline). Serde emits struct
493    /// fields in declaration order regardless of `preserve_order`.
494    pub fn render(&self) -> String {
495        let mut s = serde_json::to_string_pretty(self).expect("TestRun serialises");
496        s.push('\n');
497        s
498    }
499}
500
501/// The `--suite` and `--case` values a run selected nothing for (#2273), as
502/// `run-end` reports them: present only when a filter was given and a value
503/// went unmatched. A filter that selects nothing is an error, not a vacuous pass.
504#[derive(Debug, Default, Clone, PartialEq, Eq)]
505pub struct Unmatched {
506    pub suites: Vec<String>,
507    pub cases: Vec<String>,
508}
509
510impl Unmatched {
511    pub fn is_empty(&self) -> bool {
512        self.suites.is_empty() && self.cases.is_empty()
513    }
514
515    /// One line per unmatched value, without the `<program> test:` prefix.
516    pub fn messages(&self) -> Vec<String> {
517        let suites = self
518            .suites
519            .iter()
520            .map(|s| format!("no suite named --suite {s:?}"));
521        let cases = self
522            .cases
523            .iter()
524            .map(|c| format!("no case matched --case {c:?}"));
525        suites.chain(cases).collect()
526    }
527
528    /// Print the error for each unmatched value to stderr, after the run's
529    /// usual output, so a consumer still reads the document.
530    pub fn report(&self, program: &str) {
531        for message in self.messages() {
532            emsg!("{program} test: error: {message}");
533        }
534    }
535}
536
537/// The outcome of parsing the runner's NDJSON stream: the suites observed, the
538/// running tallies, and whether a `run-end` event was seen (a missing `run-end`
539/// means the runner died mid-stream — a crashed/incomplete run).
540#[derive(Debug, Default, PartialEq)]
541pub struct ParsedRun {
542    pub passed: u32,
543    pub failed: u32,
544    pub suites: Vec<Suite>,
545    pub complete: bool,
546    /// What a `--suite`/`--case` filter selected nothing for (#2273).
547    pub unmatched: Unmatched,
548    /// #2842: the runner's snapshot report, when its build takes snapshots.
549    pub snapshots: Option<crate::snapshots::Report>,
550    /// #3585: the value a `bynk eval` case reported.
551    pub eval: Option<EvalValue>,
552}
553
554impl ParsedRun {
555    /// Fold this parsed stream into the final document. `node_ok` is whether the
556    /// runner process exited zero; `stderr` is its captured stderr (used only
557    /// for a crashed run). A stream with no `run-end` — or a non-zero exit with
558    /// no completion — becomes a `runtime` error carrying the observed prefix.
559    pub fn into_document(self, stderr: &str) -> TestRun {
560        if self.complete {
561            TestRun {
562                passed: self.passed,
563                failed: self.failed,
564                skipped: 0,
565                suites: Some(self.suites),
566                error: None,
567                coverage: None,
568                transport: None,
569                snapshots: None,
570                eval: self.eval,
571            }
572        } else {
573            let trimmed = stderr.trim();
574            TestRun {
575                passed: self.passed,
576                failed: self.failed,
577                skipped: 0,
578                suites: Some(self.suites),
579                error: Some(TestError {
580                    kind: "runtime".to_string(),
581                    message: Some("the test runner exited before completing".to_string()),
582                    diagnostics: Vec::new(),
583                    stderr: (!trimmed.is_empty()).then(|| trimmed.to_string()),
584                }),
585                coverage: None,
586                transport: None,
587                snapshots: None,
588                eval: None,
589            }
590        }
591    }
592}
593
594/// Parse the runner's NDJSON stdout into a [`ParsedRun`]. Unparseable or
595/// unrecognised lines are skipped (the stream is an internal protocol; a
596/// stray line should never abort the whole report).
597pub fn parse_ndjson(stdout: &str) -> ParsedRun {
598    let mut run = ParsedRun::default();
599    // #2685: a `warning` event belongs to the `case` event that follows it. Warnings
600    // attach by stream order, which relies on the runner running cases one at a
601    // time: a warning raised while a case runs precedes that case's own event.
602    let mut pending: Vec<Warning> = Vec::new();
603    for line in stdout.lines() {
604        let line = line.trim();
605        if line.is_empty() {
606            continue;
607        }
608        let Ok(value) = serde_json::from_str::<serde_json::Value>(line) else {
609            continue;
610        };
611        match value.get("type").and_then(|t| t.as_str()) {
612            Some("suite-begin") => {
613                run.suites.push(Suite {
614                    name: str_field(&value, "name"),
615                    kind: str_field(&value, "kind"),
616                    cases: Vec::new(),
617                });
618            }
619            Some("warning") => pending.extend(Warning::from_event(&value)),
620            Some("case") => {
621                let mut case = case_from_event(&value);
622                case.warnings = (!pending.is_empty()).then(|| std::mem::take(&mut pending));
623                if case.outcome == "pass" {
624                    run.passed += 1;
625                } else {
626                    run.failed += 1;
627                }
628                if let Some(suite) = run.suites.last_mut() {
629                    suite.cases.push(case);
630                }
631            }
632            Some("eval-value") => {
633                run.eval = Some(EvalValue {
634                    value: value.get("value").cloned(),
635                    ty: str_field(&value, "valueType"),
636                });
637            }
638            Some("snapshots") => {
639                run.snapshots = value
640                    .get("files")
641                    .map(crate::snapshots::Report::from_files_value);
642            }
643            Some("run-end") => {
644                run.complete = true;
645                run.unmatched = unmatched_from_event(&value);
646            }
647            _ => {}
648        }
649    }
650    run
651}
652
653/// The [`Case`] a runner `case` event describes, without its tier (which comes
654/// from the compile's case table). Shared by the document parser and the stream.
655pub(crate) fn case_from_event(value: &serde_json::Value) -> Case {
656    let message = value
657        .get("message")
658        .and_then(|m| m.as_str())
659        .map(str::to_string);
660    let location = value
661        .get("location")
662        .and_then(|l| l.as_str())
663        .and_then(parse_location);
664    let retries = value
665        .get("retries")
666        .and_then(serde_json::Value::as_u64)
667        .filter(|n| *n > 0)
668        .map(|n| u32::try_from(n).unwrap_or(u32::MAX));
669    let detached_failures = value
670        .get("detached_failures")
671        .and_then(serde_json::Value::as_u64)
672        .filter(|n| *n > 0)
673        .map(|n| u32::try_from(n).unwrap_or(u32::MAX));
674    let violation = value.get("violation").map(violation_from_json);
675    let refusals = refusals_from_json(value.get("refusals"));
676    Case {
677        name: str_field(value, "name"),
678        outcome: str_field(value, "outcome"),
679        message,
680        location,
681        retries,
682        detached_failures,
683        tier: None,
684        kind: str_opt(value, "kind"),
685        seed: str_opt(value, "seed"),
686        counterexample: str_opt(value, "counterexample"),
687        violation,
688        refusals,
689        origin: None,
690        warnings: None,
691        duration_ms: value.get("durationMs").and_then(serde_json::Value::as_f64),
692    }
693}
694
695/// A location as the ndjson event carries it (`path:line:col`) or the JSON document
696/// does (the driver serialises it from [`Location`], as an object).
697fn location_from_json(value: &serde_json::Value) -> Option<Location> {
698    value.get("location").and_then(|l| match l {
699        serde_json::Value::String(s) => parse_location(s),
700        serde_json::Value::Object(_) => Some(Location {
701            path: str_field(l, "path"),
702            line: l
703                .get("line")
704                .and_then(serde_json::Value::as_u64)
705                .unwrap_or(0) as u32,
706            col: l
707                .get("col")
708                .and_then(serde_json::Value::as_u64)
709                .unwrap_or(0) as u32,
710        }),
711        _ => None,
712    })
713}
714
715/// #2272: a runner `violation` object, as the case event and the document carry it.
716pub(crate) fn violation_from_json(value: &serde_json::Value) -> Violation {
717    Violation {
718        kind: str_field(value, "kind"),
719        agent: str_field(value, "agent"),
720        name: str_field(value, "name"),
721        location: location_from_json(value),
722    }
723}
724
725/// #2685: a case's `warnings` array, as the document carries it. A malformed
726/// entry is dropped, and an array left empty is absent.
727pub(crate) fn warnings_from_json(value: Option<&serde_json::Value>) -> Option<Vec<Warning>> {
728    let warnings: Vec<Warning> = value?
729        .as_array()?
730        .iter()
731        .filter_map(Warning::from_event)
732        .collect();
733    (!warnings.is_empty()).then_some(warnings)
734}
735
736/// #2272: a runner `refusals` array, as the case event and the document carry it. A
737/// malformed entry is dropped, and an array left empty is absent.
738pub(crate) fn refusals_from_json(value: Option<&serde_json::Value>) -> Option<Vec<Refusal>> {
739    let refusals: Vec<Refusal> = value?
740        .as_array()?
741        .iter()
742        .filter_map(|r| {
743            Some(Refusal {
744                index: u32::try_from(r.get("index")?.as_u64()?).ok()?,
745                call: r.get("call")?.as_str()?.to_string(),
746                kind: r.get("kind")?.as_str()?.to_string(),
747                agent: r.get("agent")?.as_str()?.to_string(),
748                name: r.get("name")?.as_str()?.to_string(),
749                location: location_from_json(r),
750            })
751        })
752        .collect();
753    (!refusals.is_empty()).then_some(refusals)
754}
755
756/// The values a runner `run-end` event reports as selecting nothing (#2273).
757pub(crate) fn unmatched_from_event(value: &serde_json::Value) -> Unmatched {
758    let Some(unmatched) = value.get("unmatched") else {
759        return Unmatched::default();
760    };
761    let strings = |key: &str| -> Vec<String> {
762        unmatched
763            .get(key)
764            .and_then(|v| v.as_array())
765            .map(|a| {
766                a.iter()
767                    .filter_map(|v| v.as_str())
768                    .map(str::to_string)
769                    .collect()
770            })
771            .unwrap_or_default()
772    };
773    Unmatched {
774        suites: strings("suites"),
775        cases: strings("cases"),
776    }
777}
778
779fn str_opt(value: &serde_json::Value, key: &str) -> Option<String> {
780    value.get(key).and_then(|v| v.as_str()).map(str::to_string)
781}
782
783fn str_field(value: &serde_json::Value, key: &str) -> String {
784    value
785        .get(key)
786        .and_then(|v| v.as_str())
787        .unwrap_or_default()
788        .to_string()
789}
790
791/// Split a `path:line:col` location string into structured fields. Returns
792/// `None` for anything that isn't that shape (e.g. the `"unknown"` fallback a
793/// non-assertion throw carries), so such a failure keeps its message but offers
794/// no click-through. Splits from the right, so a path containing `:` is safe.
795fn parse_location(s: &str) -> Option<Location> {
796    let (rest, col) = s.rsplit_once(':')?;
797    let (path, line) = rest.rsplit_once(':')?;
798    let line: u32 = line.parse().ok()?;
799    let col: u32 = col.parse().ok()?;
800    if path.is_empty() {
801        return None;
802    }
803    Some(Location {
804        path: path.to_string(),
805        line,
806        col,
807    })
808}
809
810#[cfg(test)]
811mod tests {
812    use super::*;
813
814    #[test]
815    fn a_warning_event_belongs_to_the_case_that_follows_it() {
816        let stream = concat!(
817            r#"{"type":"suite-begin","name":"s","kind":"integration","tests":2}"#,
818            "\n",
819            r#"{"type":"warning","code":"bynk.test.smoke_undeclared_status","route":"GET /a","status":409,"declared":[200,404],"message":"m"}"#,
820            "\n",
821            r#"{"type":"case","suite":"s","name":"one","outcome":"pass"}"#,
822            "\n",
823            r#"{"type":"case","suite":"s","name":"two","outcome":"pass"}"#,
824            "\n",
825            r#"{"type":"run-end","passed":2,"failed":0}"#,
826            "\n",
827        );
828        let run = parse_ndjson(stream);
829        // A warning does not fail the case it is on.
830        assert_eq!((run.passed, run.failed), (2, 0));
831        let cases = &run.suites[0].cases;
832        let warning = &cases[0].warnings.as_ref().expect("the first case warns")[0];
833        assert_eq!(warning.code, "bynk.test.smoke_undeclared_status");
834        assert_eq!(warning.route, "GET /a");
835        assert_eq!(warning.status, 409);
836        assert_eq!(warning.declared, vec![200, 404]);
837        assert_eq!(cases[1].warnings, None);
838        let doc = run.into_document("").render();
839        assert!(
840            doc.contains(r#""warnings": ["#) && doc.matches("warnings").count() == 1,
841            "{doc}"
842        );
843    }
844
845    fn known(
846        suite: &str,
847        cases: &[(&str, Option<&'static str>)],
848    ) -> crate::project::DiscoveredSuite {
849        crate::project::DiscoveredSuite {
850            name: suite.to_string(),
851            kind: "unit",
852            cases: cases
853                .iter()
854                .map(|(name, tier)| crate::project::DiscoveredCase {
855                    name: (*name).to_string(),
856                    location: None,
857                    tier: *tier,
858                    generative: None,
859                    doc: false,
860                })
861                .collect(),
862            skipped: Vec::new(),
863            envs: Vec::new(),
864        }
865    }
866
867    /// A case's measured duration is read from the runner's event, and is not part of
868    /// the document: the JSON document stays deterministic (#2267 stage 2).
869    #[test]
870    fn a_cases_duration_is_read_but_never_written_to_the_document() {
871        let ndjson = concat!(
872            r#"{"type":"suite-begin","name":"s","kind":"unit","tests":1}"#,
873            "\n",
874            r#"{"type":"case","suite":"s","name":"c","outcome":"pass","durationMs":1.5}"#,
875            "\n",
876            r#"{"type":"suite-end","name":"s"}"#,
877            "\n",
878            r#"{"type":"run-end","passed":1,"failed":0}"#,
879            "\n",
880        );
881        let parsed = parse_ndjson(ndjson);
882        assert_eq!(parsed.suites[0].cases[0].duration_ms, Some(1.5));
883        let rendered = parsed.into_document("").render();
884        assert!(!rendered.contains("durationMs"), "{rendered}");
885    }
886
887    /// #3437: the failures a detached effect reported while a case ran are a count on
888    /// the case; zero and absent both leave it out.
889    #[test]
890    fn a_cases_detached_failures_are_kept_and_zero_is_dropped() {
891        let ndjson = concat!(
892            r#"{"type":"suite-begin","name":"s","kind":"unit","tests":2}"#,
893            "\n",
894            r#"{"type":"case","suite":"s","name":"a","outcome":"pass","detached_failures":2}"#,
895            "\n",
896            r#"{"type":"case","suite":"s","name":"b","outcome":"pass","detached_failures":0}"#,
897            "\n",
898            r#"{"type":"suite-end","name":"s"}"#,
899            "\n",
900            r#"{"type":"run-end","passed":2,"failed":0}"#,
901            "\n",
902        );
903        let parsed = parse_ndjson(ndjson);
904        assert_eq!(parsed.suites[0].cases[0].detached_failures, Some(2));
905        assert_eq!(parsed.suites[0].cases[1].detached_failures, None);
906        let rendered = parsed.into_document("").render();
907        assert!(rendered.contains("\"detached_failures\": 2"), "{rendered}");
908        assert_eq!(
909            rendered.matches("detached_failures").count(),
910            1,
911            "{rendered}"
912        );
913    }
914
915    /// `run-end` names the `--suite`/`--case` values that selected nothing, when
916    /// the runner reports any (#2273); without the field there are none.
917    #[test]
918    fn run_end_reports_the_values_a_filter_selected_nothing_for() {
919        let ended = parse_ndjson(concat!(
920            r#"{"type":"run-begin","suites":0}"#,
921            "\n",
922            r#"{"type":"run-end","passed":0,"failed":0,"unmatched":{"suites":["nope"],"cases":["typo","other"]}}"#,
923            "\n",
924        ));
925        assert!(ended.complete);
926        assert_eq!(ended.unmatched.suites, vec!["nope".to_string()]);
927        assert_eq!(
928            ended.unmatched.cases,
929            vec!["typo".to_string(), "other".to_string()]
930        );
931        assert_eq!(
932            ended.unmatched.messages(),
933            vec![
934                "no suite named --suite \"nope\"".to_string(),
935                "no case matched --case \"typo\"".to_string(),
936                "no case matched --case \"other\"".to_string(),
937            ]
938        );
939
940        let plain = parse_ndjson(r#"{"type":"run-end","passed":1,"failed":0}"#);
941        assert!(plain.unmatched.is_empty());
942    }
943
944    /// A run document built from the runner's NDJSON takes each case's tier from
945    /// the compile's case table, by suite and case name: the runner's names are
946    /// discovery's, and a case the table does not hold (or holds without a tier)
947    /// keeps none.
948    #[test]
949    fn a_run_takes_each_cases_tier_from_the_case_table() {
950        let ndjson = concat!(
951            r#"{"type":"suite-begin","name":"shop","kind":"unit"}"#,
952            "\n",
953            r#"{"type":"case","name":"wired","outcome":"pass"}"#,
954            "\n",
955            r#"{"type":"case","name":"plain","outcome":"fail","message":"no"}"#,
956            "\n",
957            r#"{"type":"case","name":"a property","outcome":"pass"}"#,
958            "\n",
959            r#"{"type":"case","name":"unlisted","outcome":"pass"}"#,
960            "\n",
961            r#"{"type":"suite-begin","name":"other","kind":"unit"}"#,
962            "\n",
963            r#"{"type":"case","name":"wired","outcome":"pass"}"#,
964            "\n",
965            r#"{"type":"run-end"}"#,
966            "\n",
967        );
968        let table = [
969            known(
970                "shop",
971                &[
972                    ("wired", Some("system")),
973                    ("plain", Some("unit")),
974                    ("a property", None),
975                ],
976            ),
977            known("other", &[("wired", Some("integration"))]),
978        ];
979        let doc = parse_ndjson(ndjson).into_document("").with_tiers(&table);
980        let suites = doc.suites.unwrap();
981        let tiers = |i: usize| -> Vec<Option<String>> {
982            suites[i].cases.iter().map(|c| c.tier.clone()).collect()
983        };
984        assert_eq!(
985            tiers(0),
986            [Some("system".into()), Some("unit".into()), None, None]
987        );
988        assert_eq!(
989            tiers(1),
990            [Some("integration".into())],
991            "the same name in another suite"
992        );
993    }
994
995    /// #2104: a file's coverage carries both line lists, `covered_lines` last,
996    /// so the block's existing field order (the contract) is unchanged.
997    #[test]
998    fn file_coverage_carries_covered_and_uncovered_lines() {
999        let report = crate::coverage::CoverageReport {
1000            files: vec![crate::coverage::FileCoverage {
1001                path: "src/demo/m.bynk".into(),
1002                covered: 2,
1003                total: 5,
1004                uncovered: vec![7, 8, 9],
1005                covered_lines: vec![3, 4],
1006            }],
1007        };
1008        assert_eq!(
1009            serde_json::to_string(&Coverage::from(&report)).unwrap(),
1010            r#"{"covered":2,"lines":5,"percent":40,"files":[{"path":"src/demo/m.bynk","covered":2,"lines":5,"percent":40,"uncovered":[7,8,9],"covered_lines":[3,4]}]}"#
1011        );
1012    }
1013
1014    #[test]
1015    fn refusals_read_in_either_shape_and_drop_what_is_malformed() {
1016        let refusal = |location: &str| {
1017            format!(
1018                r#"{{"index":1,"call":"Spend","kind":"transition","agent":"Wallet","name":"never_decreases","location":{location}}}"#
1019            )
1020        };
1021        let as_event = refusals_from_json(
1022            serde_json::from_str(&format!(
1023                r#"[{}]"#,
1024                refusal(r#""src/demo/wallet.bynk:18:14""#)
1025            ))
1026            .ok()
1027            .as_ref(),
1028        )
1029        .unwrap();
1030        let as_document = refusals_from_json(
1031            serde_json::from_str(&format!(
1032                r#"[{}]"#,
1033                refusal(r#"{"path":"src/demo/wallet.bynk","line":18,"col":14}"#)
1034            ))
1035            .ok()
1036            .as_ref(),
1037        )
1038        .unwrap();
1039        assert_eq!(as_event, as_document);
1040        assert_eq!(as_event[0].index, 1);
1041        assert_eq!(as_event[0].kind, "transition");
1042        assert_eq!(as_event[0].location.as_ref().unwrap().line, 18);
1043
1044        // A refusal missing a field is dropped, and an array left empty is absent.
1045        let malformed: serde_json::Value =
1046            serde_json::from_str(r#"[{"index":0,"call":"Spend","kind":"invariant"}]"#).unwrap();
1047        assert_eq!(refusals_from_json(Some(&malformed)), None);
1048        assert_eq!(refusals_from_json(Some(&serde_json::json!([]))), None);
1049        assert_eq!(refusals_from_json(Some(&serde_json::json!("x"))), None);
1050        assert_eq!(refusals_from_json(None), None);
1051    }
1052
1053    #[test]
1054    fn a_violation_reads_its_location_in_either_shape() {
1055        // The ndjson event carries `path:line:col`; the JSON document, which `merge`
1056        // reads back, carries the `Location` object. Both name the same place (#2272).
1057        let as_event = serde_json::json!({
1058            "kind": "transition", "agent": "Meter", "name": "same",
1059            "location": "src/demo/m.bynk:28:14"
1060        });
1061        let as_document = serde_json::json!({
1062            "kind": "transition", "agent": "Meter", "name": "same",
1063            "location": { "path": "src/demo/m.bynk", "line": 28, "col": 14 }
1064        });
1065        let expected = Some(Location {
1066            path: "src/demo/m.bynk".to_string(),
1067            line: 28,
1068            col: 14,
1069        });
1070        assert_eq!(violation_from_json(&as_event).location, expected);
1071        assert_eq!(violation_from_json(&as_document).location, expected);
1072    }
1073
1074    #[test]
1075    fn a_doc_example_case_is_marked_and_no_other_is() {
1076        let table = vec![crate::project::DiscoveredSuite {
1077            name: "demo.m".to_string(),
1078            kind: "unit",
1079            cases: vec![
1080                crate::project::DiscoveredCase {
1081                    name: "doc example m.bynk:4".to_string(),
1082                    location: None,
1083                    tier: Some("unit"),
1084                    generative: None,
1085                    doc: true,
1086                },
1087                crate::project::DiscoveredCase {
1088                    name: "real".to_string(),
1089                    location: None,
1090                    tier: Some("unit"),
1091                    generative: None,
1092                    doc: false,
1093                },
1094            ],
1095            skipped: Vec::new(),
1096            envs: Vec::new(),
1097        }];
1098        let ndjson = concat!(
1099            r#"{"type":"suite-begin","name":"demo.m","kind":"unit","tests":2}"#,
1100            "\n",
1101            r#"{"type":"case","suite":"demo.m","name":"doc example m.bynk:4","outcome":"pass"}"#,
1102            "\n",
1103            r#"{"type":"case","suite":"demo.m","name":"real","outcome":"pass"}"#,
1104            "\n",
1105            r#"{"type":"suite-end","name":"demo.m"}"#,
1106            "\n",
1107            r#"{"type":"run-end","passed":2,"failed":0}"#,
1108            "\n",
1109        );
1110        let doc = parse_ndjson(ndjson).into_document("").with_tiers(&table);
1111        let rendered = doc.render();
1112        // Appended after the other optional fields, and only on the doc case.
1113        assert_eq!(rendered.matches("\"origin\"").count(), 1, "{rendered}");
1114        assert!(rendered.contains("\"origin\": \"doc\""), "{rendered}");
1115        let suites = doc.suites.as_ref().unwrap();
1116        assert_eq!(suites[0].cases[0].origin.as_deref(), Some("doc"));
1117        assert_eq!(suites[0].cases[1].origin, None);
1118    }
1119}