Skip to main content

bynk_driver/
test_stream.rs

1//! `bynk test --format ndjson` (#2267, Slice D stage 1): the supported result
2//! stream.
3//!
4//! The runner already writes one JSON event per line (`BYNK_TEST_FORMAT=ndjson`),
5//! an internal protocol between the generated entry and the driver. `--format
6//! json` collects all of it and prints one document at the end; `--format ndjson`
7//! forwards it as it arrives, so a consumer sees each suite when that suite
8//! finishes. The events the driver prints are its own, not the runner's lines
9//! passed through, so the contract does not depend on the runner's wording:
10//!
11//! - `run-begin {suites}`
12//! - `suite-begin {name, kind, tests}`
13//! - `case {suite, <the document's case fields>}`: the same object the JSON
14//!   document holds for the case, in the same field order, behind `type` and
15//!   `suite`, so it carries `tier` and the generative fields too
16//! - `suite-end {name}`
17//! - `run-end {passed, failed, skipped?, transport?, snapshots?}`; `snapshots` is
18//!   `{written, updated, obsolete}`, present when the project takes snapshots
19//! - `error {kind, message?, diagnostics?, stderr?}`: the document's `error`
20//!   object, for a compile failure, a run the driver could not start or finish,
21//!   and a runner that died before `run-end`
22//!
23//! The stream ends with exactly one of `run-end` or `error`. A case a remote run
24//! skipped (`--skip-unsupported`) is a `case` event with outcome `skipped`
25//! between the last `suite-end` and `run-end`. A line that is not a recognised
26//! runner event is dropped. Field order is the contract; a consumer ignores
27//! event types and fields it does not know.
28
29use std::io::{BufRead, BufReader, Write};
30use std::process::{Child, Command, ExitStatus, Stdio};
31
32use serde::Serialize;
33
34use crate::test_json::{
35    Case, TestError, TestRun, Unmatched, Warning, case_from_event, unmatched_from_event,
36};
37
38#[derive(Serialize)]
39struct RunBegin {
40    r#type: &'static str,
41    suites: usize,
42}
43
44#[derive(Serialize)]
45struct SuiteBegin<'a> {
46    r#type: &'static str,
47    name: &'a str,
48    kind: &'a str,
49    tests: usize,
50}
51
52#[derive(Serialize)]
53struct CaseEvent<'a> {
54    r#type: &'static str,
55    suite: &'a str,
56    #[serde(flatten)]
57    case: &'a Case,
58    /// After the document's case fields, so a later optional `Case` field still
59    /// lands before it.
60    #[serde(rename = "durationMs", skip_serializing_if = "Option::is_none")]
61    duration_ms: Option<f64>,
62}
63
64#[derive(Serialize)]
65struct SuiteEnd<'a> {
66    r#type: &'static str,
67    name: &'a str,
68}
69
70#[derive(Serialize)]
71struct RunEnd<'a> {
72    r#type: &'static str,
73    passed: u32,
74    failed: u32,
75    #[serde(skip_serializing_if = "is_zero")]
76    skipped: u32,
77    #[serde(skip_serializing_if = "Option::is_none")]
78    transport: Option<&'a str>,
79    /// #2842: the snapshot counts; absent for a project with no snapshot.
80    #[serde(skip_serializing_if = "Option::is_none")]
81    snapshots: Option<crate::snapshots::Counts>,
82}
83
84#[derive(Serialize)]
85struct ErrorEvent<'a> {
86    r#type: &'static str,
87    #[serde(flatten)]
88    error: &'a TestError,
89}
90
91fn is_zero(n: &u32) -> bool {
92    *n == 0
93}
94
95fn line<T: Serialize>(event: &T) -> String {
96    // The structs hold only strings and numbers, which always serialise.
97    let mut text = serde_json::to_string(event).unwrap_or_default();
98    text.push('\n');
99    text
100}
101
102fn run_begin(suites: usize) -> String {
103    line(&RunBegin {
104        r#type: "run-begin",
105        suites,
106    })
107}
108
109fn suite_begin(name: &str, kind: &str, tests: usize) -> String {
110    line(&SuiteBegin {
111        r#type: "suite-begin",
112        name,
113        kind,
114        tests,
115    })
116}
117
118fn case_event(suite: &str, case: &Case) -> String {
119    line(&CaseEvent {
120        r#type: "case",
121        suite,
122        case,
123        duration_ms: case.duration_ms,
124    })
125}
126
127fn suite_end(name: &str) -> String {
128    line(&SuiteEnd {
129        r#type: "suite-end",
130        name,
131    })
132}
133
134fn run_end(
135    passed: u32,
136    failed: u32,
137    skipped: u32,
138    transport: Option<&str>,
139    snapshots: Option<crate::snapshots::Counts>,
140) -> String {
141    line(&RunEnd {
142        r#type: "run-end",
143        passed,
144        failed,
145        skipped,
146        transport,
147        snapshots,
148    })
149}
150
151fn error_event(error: &TestError) -> String {
152    line(&ErrorEvent {
153        r#type: "error",
154        error,
155    })
156}
157
158/// The stream for a document held in full: a run that could not start (a
159/// compile failure, a launch error) is one `error` event, and a normal one is
160/// its suites' events then `run-end`. Used where nothing is read live.
161pub fn events_for(run: &TestRun) -> String {
162    let mut out = String::new();
163    let Some(suites) = &run.suites else {
164        if let Some(error) = &run.error {
165            out.push_str(&error_event(error));
166        }
167        return out;
168    };
169    // The live stream never sees a skipped case: the runner did not run it. So a
170    // suite's `tests` counts the cases between its `suite-begin` and `suite-end`,
171    // and a suite made only of skipped cases (which `with_remote` adds for them)
172    // has no such block, only its skipped cases after the last `suite-end`.
173    let ran = |suite: &&crate::test_json::Suite| {
174        suite.cases.is_empty() || suite.cases.iter().any(|c| c.outcome != "skipped")
175    };
176    out.push_str(&run_begin(suites.iter().filter(ran).count()));
177    for suite in suites.iter().filter(ran) {
178        let cases: Vec<&Case> = suite
179            .cases
180            .iter()
181            .filter(|c| c.outcome != "skipped")
182            .collect();
183        out.push_str(&suite_begin(&suite.name, &suite.kind, cases.len()));
184        for case in cases {
185            out.push_str(&case_event(&suite.name, case));
186        }
187        out.push_str(&suite_end(&suite.name));
188    }
189    for suite in suites {
190        for case in suite.cases.iter().filter(|c| c.outcome == "skipped") {
191            out.push_str(&case_event(&suite.name, case));
192        }
193    }
194    match &run.error {
195        Some(error) => out.push_str(&error_event(error)),
196        None => out.push_str(&run_end(
197            run.passed,
198            run.failed,
199            run.skipped,
200            run.transport.as_deref(),
201            run.snapshots,
202        )),
203    }
204    out
205}
206
207/// Print a document in `--format json`, or its events in `--format ndjson`.
208pub fn print_run(stream: bool, run: &TestRun) {
209    let text = if stream {
210        events_for(run)
211    } else {
212        run.render()
213    };
214    print_text(&text);
215}
216
217/// Print `text` to stdout, or to the [`capture`] in force (#3069: a finished
218/// `--format json` run is read back in process by `--mutate`).
219pub fn print_text(text: &str) {
220    CAPTURE.with(|c| match c.borrow_mut().as_mut() {
221        Some(buf) => buf.push_str(text),
222        None => print!("{text}"),
223    });
224}
225
226thread_local! {
227    /// Where [`print_run`] writes while [`capture`] is running, else stdout.
228    static CAPTURE: std::cell::RefCell<Option<String>> = const { std::cell::RefCell::new(None) };
229}
230
231/// Run `f`, collecting what it prints through [`print_run`] instead of writing
232/// it to stdout (#2998): `bynk test` asks a project for its discovery document
233/// in-process, where it used to read a child's stdout.
234///
235/// Re-entrant and panic-safe: a drop guard restores whatever capture was in
236/// force before (none, or an outer `capture`'s buffer), also when `f` unwinds,
237/// so a panic cannot leave later output swallowed. The text printed inside an
238/// inner capture goes to the inner result only, not to the outer one.
239pub fn capture<R>(f: impl FnOnce() -> R) -> (R, String) {
240    struct Restore(Option<Option<String>>);
241    impl Drop for Restore {
242        fn drop(&mut self) {
243            if let Some(previous) = self.0.take() {
244                CAPTURE.with(|c| *c.borrow_mut() = previous);
245            }
246        }
247    }
248    let previous = CAPTURE.with(|c| c.borrow_mut().replace(String::new()));
249    let mut guard = Restore(Some(previous));
250    let result = f();
251    let text = CAPTURE.with(|c| c.borrow_mut().take()).unwrap_or_default();
252    if let Some(previous) = guard.0.take() {
253        CAPTURE.with(|c| *c.borrow_mut() = previous);
254    }
255    (result, text)
256}
257
258#[cfg(test)]
259mod capture_tests {
260    use super::*;
261
262    #[test]
263    fn captures_and_nests() {
264        let run = || crate::test_json::TestRun::runtime_error("x".to_string(), None);
265        let (((), outer_text), outer) = capture(|| {
266            let r = capture(|| print_run(false, &run()));
267            print_run(false, &run());
268            r
269        });
270        assert!(
271            outer_text.contains("\"x\""),
272            "inner capture holds its own output"
273        );
274        assert!(
275            outer.contains("\"x\""),
276            "outer holds what it printed itself"
277        );
278        assert_eq!(outer_text.matches("\"x\"").count(), 1);
279        assert_eq!(outer.matches("\"x\"").count(), 1);
280    }
281
282    #[test]
283    fn a_panic_does_not_leave_output_swallowed() {
284        let caught = std::panic::catch_unwind(|| capture(|| panic!("boom")));
285        assert!(caught.is_err());
286        // The buffer is gone, so printing goes to stdout again: a nested
287        // capture starts from "no capture", and finds nothing leaked in.
288        let ((), text) = capture(|| {});
289        assert_eq!(text, "");
290        CAPTURE.with(|c| assert!(c.borrow().is_none()));
291    }
292}
293
294/// A remote run's skipped case, as it goes into the stream: suite, case, reason.
295pub type Skipped = (String, String, String);
296
297/// What the stream knows about the run besides the runner's own events.
298pub struct StreamContext<'a> {
299    /// The compile's case table, for each case's tier.
300    pub discovered: &'a [crate::project::DiscoveredSuite],
301    /// The cases a remote run skipped, which the runner never saw.
302    pub skipped: Vec<Skipped>,
303    /// `remote:<target>` under `--against`.
304    pub transport: Option<String>,
305    /// #2842: the project's snapshots, when the run reports them: the `run-end`
306    /// carries their counts.
307    pub snapshots: Option<&'a crate::snapshots::SnapshotRun>,
308}
309
310/// Turns the runner's event lines into the stream's, one at a time.
311pub struct Stream<'a> {
312    context: StreamContext<'a>,
313    ended: bool,
314    unmatched: Unmatched,
315    /// #2685: the warnings seen since the last `case` event, which that event
316    /// carries. They attach by stream order, which relies on cases running
317    /// one at a time.
318    pending: Vec<Warning>,
319    /// Every warning the run raised, for the driver to write to stderr.
320    warnings: Vec<Warning>,
321    /// #2842: the runner's `snapshots` event, once it has come.
322    snapshot_report: Option<crate::snapshots::Report>,
323}
324
325impl<'a> Stream<'a> {
326    pub fn new(context: StreamContext<'a>) -> Self {
327        Self {
328            context,
329            ended: false,
330            unmatched: Unmatched::default(),
331            pending: Vec::new(),
332            warnings: Vec::new(),
333            snapshot_report: None,
334        }
335    }
336
337    /// #2842: the snapshot report the runner sent, for the driver to settle.
338    pub fn snapshot_report(&self) -> Option<&crate::snapshots::Report> {
339        self.snapshot_report.as_ref()
340    }
341
342    /// The `--suite`/`--case` values the runner reported as selecting nothing:
343    /// not part of the stream, but the driver turns them into an error (#2273).
344    pub fn unmatched(&self) -> &Unmatched {
345        &self.unmatched
346    }
347
348    /// The warnings the run raised (#2685), in order.
349    pub fn warnings(&self) -> &[Warning] {
350        &self.warnings
351    }
352
353    /// `"doc"` for a doc-comment example's case (#2461), from the case table.
354    fn origin_of(&self, suite: &str, case: &str) -> Option<String> {
355        let known = self.context.discovered.iter().find(|d| d.name == suite)?;
356        known
357            .cases
358            .iter()
359            .find(|c| c.name == case)?
360            .doc
361            .then(|| "doc".to_string())
362    }
363
364    fn tier_of(&self, suite: &str, case: &str) -> Option<&'static str> {
365        self.context
366            .discovered
367            .iter()
368            .find(|d| d.name == suite)?
369            .cases
370            .iter()
371            .find(|c| c.name == case)?
372            .tier
373    }
374
375    /// The stream's text for one line of the runner's output: nothing for a line
376    /// that is not a recognised event.
377    pub fn push(&mut self, raw: &str) -> String {
378        let raw = raw.trim();
379        let Ok(value) = serde_json::from_str::<serde_json::Value>(raw) else {
380            return String::new();
381        };
382        let text = |key: &str| value.get(key).and_then(|v| v.as_str()).unwrap_or_default();
383        let count = |key: &str| {
384            value
385                .get(key)
386                .and_then(serde_json::Value::as_u64)
387                .map_or(0, |n| usize::try_from(n).unwrap_or(usize::MAX))
388        };
389        match text("type") {
390            "run-begin" => run_begin(count("suites")),
391            "suite-begin" => suite_begin(text("name"), text("kind"), count("tests")),
392            "warning" => {
393                if let Some(warning) = Warning::from_event(&value) {
394                    self.warnings.push(warning.clone());
395                    self.pending.push(warning);
396                }
397                String::new()
398            }
399            "case" => {
400                let mut case = case_from_event(&value);
401                case.warnings =
402                    (!self.pending.is_empty()).then(|| std::mem::take(&mut self.pending));
403                case.tier = self.tier_of(text("suite"), &case.name).map(str::to_string);
404                case.origin = self.origin_of(text("suite"), &case.name);
405                case_event(text("suite"), &case)
406            }
407            "suite-end" => suite_end(text("name")),
408            "snapshots" => {
409                self.snapshot_report = value
410                    .get("files")
411                    .map(crate::snapshots::Report::from_files_value);
412                String::new()
413            }
414            "run-end" => {
415                self.ended = true;
416                self.unmatched = unmatched_from_event(&value);
417                let mut out = String::new();
418                for (suite, name, reason) in &self.context.skipped {
419                    out.push_str(&case_event(
420                        suite,
421                        &Case {
422                            name: name.clone(),
423                            outcome: "skipped".to_string(),
424                            message: Some(reason.clone()),
425                            location: None,
426                            retries: None,
427                            detached_failures: None,
428                            tier: self.tier_of(suite, name).map(str::to_string),
429                            kind: None,
430                            seed: None,
431                            counterexample: None,
432                            violation: None,
433                            refusals: None,
434                            origin: self.origin_of(suite, name),
435                            warnings: None,
436                            duration_ms: None,
437                        },
438                    ));
439                }
440                let passed = u32::try_from(count("passed")).unwrap_or(u32::MAX);
441                let failed = u32::try_from(count("failed")).unwrap_or(u32::MAX);
442                let skipped = u32::try_from(self.context.skipped.len()).unwrap_or(u32::MAX);
443                out.push_str(&run_end(
444                    passed,
445                    failed,
446                    skipped,
447                    self.context.transport.as_deref(),
448                    self.context
449                        .snapshots
450                        .map(|run| run.counts(self.snapshot_report.as_ref())),
451                ));
452                out
453            }
454            _ => String::new(),
455        }
456    }
457
458    /// Whether the runner reached `run-end` (#4000): a stream that did not is an
459    /// incomplete report, whatever the runner process's own exit status was.
460    pub fn ended(&self) -> bool {
461        self.ended
462    }
463
464    /// What closes the stream when the runner's output has ended: nothing after
465    /// a `run-end`, else an `error` event, the runner having died mid-run.
466    pub fn finish(&self, stderr: &str) -> String {
467        if self.ended {
468            return String::new();
469        }
470        let trimmed = stderr.trim();
471        error_event(&TestError {
472            kind: "runtime".to_string(),
473            message: Some("the test runner exited before completing".to_string()),
474            diagnostics: Vec::new(),
475            stderr: (!trimmed.is_empty()).then(|| trimmed.to_string()),
476        })
477    }
478}
479
480/// Run `cmd`, forwarding each event to `out` as the runner writes it, and return
481/// its exit status. The runner's stderr is collected on a thread, so a full pipe
482/// cannot stall it. If `out` stops accepting output (a consumer that went away),
483/// the runner is killed rather than left running.
484pub fn forward(
485    mut cmd: Command,
486    stream: &mut Stream<'_>,
487    out: &mut impl Write,
488    aliases: &[(String, String)],
489) -> std::io::Result<ExitStatus> {
490    let mut child = cmd.stdout(Stdio::piped()).stderr(Stdio::piped()).spawn()?;
491    let stderr_pipe = child.stderr.take();
492    let collector = std::thread::spawn(move || {
493        let mut text = String::new();
494        if let Some(pipe) = stderr_pipe {
495            for line in BufReader::new(pipe).lines().map_while(Result::ok) {
496                text.push_str(&line);
497                text.push('\n');
498            }
499        }
500        text
501    });
502    let mut gone = false;
503    if let Some(pipe) = child.stdout.take() {
504        // Lossy, so a stray byte in a line cannot end the stream early.
505        let mut reader = BufReader::new(pipe);
506        let mut buffer = Vec::new();
507        loop {
508            buffer.clear();
509            match reader.read_until(b'\n', &mut buffer) {
510                Ok(0) | Err(_) => break,
511                Ok(_) => {}
512            }
513            let line = String::from_utf8_lossy(&buffer);
514            let text = stream.push(&crate::doc_examples::apply_aliases(&line, aliases));
515            if !text.is_empty() && write_and_flush(out, &text).is_err() {
516                gone = true;
517                break;
518            }
519        }
520    }
521    if gone {
522        kill(&mut child);
523    }
524    let status = child.wait()?;
525    let stderr = collector.join().unwrap_or_default();
526    if !gone {
527        let closing = stream.finish(&stderr);
528        if !closing.is_empty() {
529            let _ = write_and_flush(out, &closing);
530        }
531    }
532    Ok(status)
533}
534
535fn write_and_flush(out: &mut impl Write, text: &str) -> std::io::Result<()> {
536    out.write_all(text.as_bytes())?;
537    out.flush()
538}
539
540fn kill(child: &mut Child) {
541    let _ = child.kill();
542}
543
544#[cfg(test)]
545mod tests {
546    use super::*;
547    use crate::test_json::{Location, Suite};
548
549    fn context<'a>() -> StreamContext<'a> {
550        StreamContext {
551            discovered: &[],
552            skipped: Vec::new(),
553            transport: None,
554            snapshots: None,
555        }
556    }
557
558    fn case(name: &str, outcome: &str) -> Case {
559        Case {
560            name: name.to_string(),
561            outcome: outcome.to_string(),
562            message: None,
563            location: None,
564            retries: None,
565            detached_failures: None,
566            tier: None,
567            kind: None,
568            seed: None,
569            counterexample: None,
570            violation: None,
571            refusals: None,
572            origin: None,
573            warnings: None,
574            duration_ms: None,
575        }
576    }
577
578    #[test]
579    fn a_case_event_is_the_documents_case_behind_type_and_suite() {
580        let mut failed = case("never seventy three", "fail");
581        failed.message = Some("property failed".to_string());
582        failed.location = Some(Location {
583            path: "tests/m.test.bynk".to_string(),
584            line: 3,
585            col: 4,
586        });
587        failed.tier = Some("unit".to_string());
588        failed.kind = Some("property".to_string());
589        failed.seed = Some("0x5f3a".to_string());
590        failed.counterexample = Some("p = 73".to_string());
591        assert_eq!(
592            case_event("demo.m", &failed),
593            concat!(
594                r#"{"type":"case","suite":"demo.m","name":"never seventy three","outcome":"fail","#,
595                r#""message":"property failed","location":{"path":"tests/m.test.bynk","line":3,"col":4},"#,
596                r#""tier":"unit","kind":"property","seed":"0x5f3a","counterexample":"p = 73"}"#,
597                "\n"
598            )
599        );
600    }
601
602    #[test]
603    fn a_case_event_names_the_refused_steps_before_its_duration() {
604        let mut failed = case("every call is accepted", "fail");
605        failed.refusals = Some(vec![crate::test_json::Refusal {
606            index: 0,
607            call: "Spend".to_string(),
608            kind: "invariant".to_string(),
609            agent: "Wallet".to_string(),
610            name: "nonneg".to_string(),
611            location: Some(Location {
612                path: "src/demo/wallet.bynk".to_string(),
613                line: 9,
614                col: 13,
615            }),
616        }]);
617        failed.duration_ms = Some(3.0);
618        assert_eq!(
619            case_event("demo.wallet", &failed),
620            concat!(
621                r#"{"type":"case","suite":"demo.wallet","name":"every call is accepted","outcome":"fail","#,
622                r#""refusals":[{"index":0,"call":"Spend","kind":"invariant","agent":"Wallet","name":"nonneg","#,
623                r#""location":{"path":"src/demo/wallet.bynk","line":9,"col":13}}],"durationMs":3.0}"#,
624                "\n"
625            )
626        );
627    }
628
629    #[test]
630    fn a_case_event_ends_with_its_duration_when_the_runner_measured_one() {
631        let mut ran = case("one", "pass");
632        ran.tier = Some("unit".to_string());
633        ran.duration_ms = Some(12.5);
634        assert_eq!(
635            case_event("demo.m", &ran),
636            "{\"type\":\"case\",\"suite\":\"demo.m\",\"name\":\"one\",\"outcome\":\"pass\",\"tier\":\"unit\",\"durationMs\":12.5}\n"
637        );
638        // A case without one (a skipped case, a replayed document) has no field.
639        assert!(!case_event("demo.m", &case("two", "skipped")).contains("durationMs"));
640    }
641
642    #[test]
643    fn the_runners_events_become_the_streams_with_tiers() {
644        let discovered = [crate::project::DiscoveredSuite {
645            name: "demo.m".to_string(),
646            kind: "unit",
647            cases: vec![crate::project::DiscoveredCase {
648                name: "one".to_string(),
649                location: None,
650                tier: Some("unit"),
651                generative: None,
652                doc: false,
653            }],
654            skipped: Vec::new(),
655            envs: Vec::new(),
656        }];
657        let mut stream = Stream::new(StreamContext {
658            discovered: &discovered,
659            ..context()
660        });
661        let out: String = [
662            r#"{"type":"run-begin","suites":1}"#,
663            r#"{"type":"suite-begin","name":"demo.m","kind":"unit","tests":1}"#,
664            r#"{"type":"case","suite":"demo.m","name":"one","outcome":"pass","durationMs":0.25}"#,
665            r#"{"type":"suite-end","name":"demo.m"}"#,
666            "not an event",
667            r#"{"type":"something-new","x":1}"#,
668            r#"{"type":"run-end","passed":1,"failed":0,"unmatched":{"cases":["x"]}}"#,
669        ]
670        .iter()
671        .map(|l| stream.push(l))
672        .collect();
673        assert_eq!(
674            out,
675            concat!(
676                "{\"type\":\"run-begin\",\"suites\":1}\n",
677                "{\"type\":\"suite-begin\",\"name\":\"demo.m\",\"kind\":\"unit\",\"tests\":1}\n",
678                "{\"type\":\"case\",\"suite\":\"demo.m\",\"name\":\"one\",\"outcome\":\"pass\",\"tier\":\"unit\",\"durationMs\":0.25}\n",
679                "{\"type\":\"suite-end\",\"name\":\"demo.m\"}\n",
680                "{\"type\":\"run-end\",\"passed\":1,\"failed\":0}\n",
681            ),
682            "an unrecognised line is dropped, and `unmatched` is not part of the stream"
683        );
684        assert_eq!(stream.finish(""), "", "nothing closes a stream that ended");
685        assert!(stream.ended());
686    }
687
688    #[test]
689    fn skipped_cases_and_the_transport_close_a_remote_run() {
690        let mut stream = Stream::new(StreamContext {
691            skipped: vec![(
692                "demo.s".to_string(),
693                "advances".to_string(),
694                "advance Clock".to_string(),
695            )],
696            transport: Some("remote:staging".to_string()),
697            ..context()
698        });
699        assert_eq!(
700            stream.push(r#"{"type":"run-end","passed":2,"failed":0}"#),
701            concat!(
702                "{\"type\":\"case\",\"suite\":\"demo.s\",\"name\":\"advances\",\"outcome\":\"skipped\",\"message\":\"advance Clock\"}\n",
703                "{\"type\":\"run-end\",\"passed\":2,\"failed\":0,\"skipped\":1,\"transport\":\"remote:staging\"}\n",
704            )
705        );
706    }
707
708    #[test]
709    fn a_runner_that_died_is_an_error_event() {
710        let mut stream = Stream::new(context());
711        stream.push(r#"{"type":"run-begin","suites":1}"#);
712        assert_eq!(
713            stream.finish("boom\n"),
714            "{\"type\":\"error\",\"kind\":\"runtime\",\"message\":\"the test runner exited before completing\",\"stderr\":\"boom\"}\n"
715        );
716    }
717
718    #[test]
719    fn a_document_held_in_full_becomes_its_events() {
720        let compile = TestRun::compile_error(vec!["a.bynk:1:1: error[x]: no".to_string()]);
721        assert_eq!(
722            events_for(&compile),
723            "{\"type\":\"error\",\"kind\":\"compile\",\"diagnostics\":[\"a.bynk:1:1: error[x]: no\"]}\n"
724        );
725
726        let mut run = TestRun::empty();
727        run.suites = Some(vec![
728            Suite {
729                name: "demo.m".to_string(),
730                kind: "unit".to_string(),
731                cases: vec![case("one", "pass"), case("two", "skipped")],
732            },
733            Suite {
734                name: "demo.s".to_string(),
735                kind: "integration".to_string(),
736                cases: vec![case("advances", "skipped")],
737            },
738            Suite {
739                name: "demo.empty".to_string(),
740                kind: "unit".to_string(),
741                cases: Vec::new(),
742            },
743        ]);
744        run.passed = 1;
745        run.skipped = 2;
746        assert_eq!(
747            events_for(&run),
748            concat!(
749                "{\"type\":\"run-begin\",\"suites\":2}\n",
750                "{\"type\":\"suite-begin\",\"name\":\"demo.m\",\"kind\":\"unit\",\"tests\":1}\n",
751                "{\"type\":\"case\",\"suite\":\"demo.m\",\"name\":\"one\",\"outcome\":\"pass\"}\n",
752                "{\"type\":\"suite-end\",\"name\":\"demo.m\"}\n",
753                "{\"type\":\"suite-begin\",\"name\":\"demo.empty\",\"kind\":\"unit\",\"tests\":0}\n",
754                "{\"type\":\"suite-end\",\"name\":\"demo.empty\"}\n",
755                "{\"type\":\"case\",\"suite\":\"demo.m\",\"name\":\"two\",\"outcome\":\"skipped\"}\n",
756                "{\"type\":\"case\",\"suite\":\"demo.s\",\"name\":\"advances\",\"outcome\":\"skipped\"}\n",
757                "{\"type\":\"run-end\",\"passed\":1,\"failed\":0,\"skipped\":2}\n",
758            ),
759            "`tests` counts what the suite reports; a suite of only skipped cases has no block"
760        );
761    }
762
763    /// A sink that records when each write arrived.
764    struct Timed(Vec<(std::time::Instant, String)>);
765
766    impl Write for Timed {
767        fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
768            self.0.push((
769                std::time::Instant::now(),
770                String::from_utf8_lossy(buf).into_owned(),
771            ));
772            Ok(buf.len())
773        }
774        fn flush(&mut self) -> std::io::Result<()> {
775            Ok(())
776        }
777    }
778
779    /// An event reaches the consumer while the runner is still running, not when
780    /// it exits; an event split across two writes is still one event; a runner
781    /// that never says `run-end` ends the stream with an `error`.
782    #[cfg(unix)]
783    #[test]
784    fn events_are_forwarded_as_they_are_written() {
785        let mut cmd = Command::new("sh");
786        cmd.arg("-c").arg(
787            r#"printf '{"type":"run-begin","suites":1}\n{"type":"suite-be'; sleep 0.4;
788               printf 'gin","name":"s","kind":"unit","tests":0}\n'; sleep 0.4; echo oops >&2"#,
789        );
790        let mut stream = Stream::new(context());
791        let mut sink = Timed(Vec::new());
792        let started = std::time::Instant::now();
793        let status = forward(cmd, &mut stream, &mut sink, &[]).unwrap();
794        let finished = started.elapsed();
795        assert!(status.success());
796        assert!(
797            !stream.ended(),
798            "a runner that exits 0 without `run-end` has not ended the stream (#4000)"
799        );
800        let first = sink.0.first().expect("an event");
801        assert_eq!(first.1, "{\"type\":\"run-begin\",\"suites\":1}\n");
802        assert!(
803            first.0.duration_since(started) < finished - std::time::Duration::from_millis(500),
804            "the first event arrived well before the runner exited"
805        );
806        let all: String = sink.0.iter().map(|(_, t)| t.as_str()).collect();
807        assert_eq!(
808            all,
809            concat!(
810                "{\"type\":\"run-begin\",\"suites\":1}\n",
811                "{\"type\":\"suite-begin\",\"name\":\"s\",\"kind\":\"unit\",\"tests\":0}\n",
812                "{\"type\":\"error\",\"kind\":\"runtime\",\"message\":\"the test runner exited before completing\",\"stderr\":\"oops\"}\n",
813            ),
814            "a split event is one event, and the missing run-end is an error"
815        );
816    }
817}