nsh-cli 0.2.0

The nsh command line tool: build, package and run apps.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
//! `nsh test`: runs an app's test files (`*.test.tsx`, `*.test.ts`, which
//! import `nsh/test`) headless, each on an engine of its own, and says how
//! each test ended (`nsh-testing` runs them). Given an app's entry instead,
//! it opens the app as a test would and takes the steps standard input
//! gives (`await app.press("Add")`); `--trace` prints the mount batches of
//! the apps under their steps.
//!
//! An app this command line serves runs in its process. An app with Rust
//! crates of its own runs in the headless runner built with them
//! (`rust_app.rs`, `nsh_testing::runner`), which asks this process to build
//! each entry ([`RunnerMessage::Build`]): the runner links no bundler. On a
//! real platform (`--target`) the apps run in its hosts, built with the
//! app's crates (`test_host.rs`), and the test files in this process.

use std::{
    collections::HashMap,
    io::{BufRead as _, BufReader, IsTerminal as _, Read as _, Write as _},
    path::{Path, PathBuf},
    process::{Command, Stdio},
    sync::{Arc, Mutex},
    time::Instant,
};

use anyhow::{Context as _, bail};
use nsh_bundler::BundleOptions;
use nsh_core::ui::description::SetDescription;
use nsh_engine::Bundle;
use nsh_testing::{
    Built, Entry, Reply, RunnerMessage, TestRequest, TestResult, TestRun, TestStatus,
};

use crate::{build::BuildError, logger, rust_app::RustApp, ui};

/// How long the app runs after it opened before the steps of standard
/// input: long enough for the engine's idle collection (every second at
/// most), so what the app keeps alive shows in a trace.
const IDLE_MS: u32 = 1200;

/// Runs the tests `path` names, of the app whose entry is `entry`: a test
/// file, the test files in a directory (an app's), or an app's entry with
/// the steps standard input gives.
pub(crate) fn test(
    path: &Path,
    entry: &Path,
    filter: Option<String>,
    trace: bool,
    junit: Option<&Path>,
    target: Option<crate::run::Target>,
    browser: Option<&Path>,
) -> anyhow::Result<()> {
    let app_dir = entry.parent().unwrap_or(Path::new(".")).to_path_buf();
    let work_dir = app_dir.join(".nsh/test");
    let files = if is_test_file(path) {
        vec![path.to_owned()]
    } else if path.is_dir() {
        let mut files = Vec::new();
        find_tests(path, &mut files);
        files.sort();
        if files.is_empty() {
            bail!(
                "no test files in {}: tests are `*.test.tsx` / `*.test.ts` files importing nsh/test",
                ui::path(path)
            );
        }
        files
    } else {
        vec![steps_file(&work_dir, path)?]
    };
    // How the files are shown: an entry's steps by the entry.
    let shown = |file: &Path| {
        if file.starts_with(&work_dir) {
            ui::path(path)
        } else {
            ui::path(file)
        }
    };
    let start = Instant::now();
    let mut tally = Tally::default();
    if browser.is_some() && target.is_none() {
        bail!("--browser goes with --target web");
    }
    let host = target
        .map(|target| crate::test_host::starter(target, browser, &work_dir))
        .transpose()?;
    // On a real platform the apps run in hosts built with the app's crates:
    // the test files run here, whatever the app is.
    match crate::rust_app::current().filter(|_| host.is_none()) {
        Some(app) => {
            let request = TestRequest {
                protocol: nsh_testing::PROTOCOL,
                bytecode_version: nsh_js::BYTECODE_VERSION.to_owned(),
                files,
                work_dir: work_dir.clone(),
                filter,
                trace,
                verbose: ui::verbose(),
            };
            in_runner(&app, &request, &shown, &mut tally)?;
        }
        None => {
            let run = TestRun {
                ui_sets: crate::own_sets().to_vec(),
                compile: compiler(),
                work_dir: work_dir.clone(),
                filter,
                trace: trace.then(|| Arc::new(Mutex::new(Box::new(std::io::stdout()) as _))),
                host,
            };
            for file in &files {
                let shown = shown(file);
                let ran = nsh_testing::run_file(&run, file, &mut |result| {
                    tally.show(&shown, result);
                });
                if let Err(e) = ran {
                    tally.failed(&shown, &e);
                }
            }
        }
    }
    if let Some(report) = junit {
        std::fs::write(report, tally.junit(start.elapsed()))
            .with_context(|| format!("write {}", ui::path(report)))?;
    }
    let total = tally.passed + tally.failed + tally.skipped + tally.todo;
    let mut counts = format!("{} passed, {} failed", tally.passed, tally.failed);
    if tally.skipped > 0 {
        counts.push_str(&format!(", {} skipped", tally.skipped));
    }
    if tally.todo > 0 {
        counts.push_str(&format!(", {} todo", tally.todo));
    }
    let summary = format!(
        "{total} {}: {counts} {}",
        if total == 1 { "test" } else { "tests" },
        ui::dim(format!("({})", ui::duration(start.elapsed())))
    );
    if tally.failed > 0 {
        bail!(summary);
    }
    ui::done(summary);
    Ok(())
}

/// How the tests ended so far, by file.
#[derive(Default)]
struct Tally {
    passed: usize,
    failed: usize,
    skipped: usize,
    todo: usize,
    /// The files shown, in order, with their results, or why one could not
    /// run.
    files: Vec<(String, Vec<TestResult>, Option<String>)>,
}

impl Tally {
    /// Shows how a test of the file shown as `file` ended, and counts it.
    fn show(&mut self, file: &str, result: &TestResult) {
        show(file, result);
        match result.status {
            TestStatus::Passed => self.passed += 1,
            TestStatus::Skipped => self.skipped += 1,
            TestStatus::Todo => self.todo += 1,
            TestStatus::Failed => self.failed += 1,
        }
        self.file(file).1.push(result.clone());
    }

    /// The test file shown as `file` could not run: it counts as a failure.
    fn failed(&mut self, file: &str, message: &str) {
        self.failed += 1;
        ui::error(format!("{file}: {message}"));
        self.file(file).2 = Some(message.to_owned());
    }

    fn file(&mut self, file: &str) -> &mut (String, Vec<TestResult>, Option<String>) {
        let at = match self.files.iter().position(|(f, ..)| f == file) {
            Some(at) => at,
            None => {
                self.files.push((file.to_owned(), Vec::new(), None));
                self.files.len() - 1
            }
        };
        &mut self.files[at]
    }

    /// The results as a JUnit XML report: a `testsuite` per file, a
    /// `testcase` per test, a file that could not run as an `error`.
    fn junit(&self, elapsed: std::time::Duration) -> String {
        use std::fmt::Write as _;
        let seconds = |d: std::time::Duration| format!("{:.3}", d.as_secs_f64());
        let mut suites = String::new();
        let (mut tests, mut failures, mut errors, mut skipped) = (0, 0, 0, 0);
        for (file, results, error) in &self.files {
            let failed = results
                .iter()
                .filter(|r| r.status == TestStatus::Failed)
                .count();
            let skips = results
                .iter()
                .filter(|r| matches!(r.status, TestStatus::Skipped | TestStatus::Todo))
                .count();
            let errs = usize::from(error.is_some());
            let time: std::time::Duration = results.iter().map(|r| r.elapsed).sum();
            tests += results.len() + errs;
            failures += failed;
            errors += errs;
            skipped += skips;
            let file = xml(file);
            let _ = writeln!(
                suites,
                "  <testsuite name=\"{file}\" tests=\"{}\" failures=\"{failed}\" errors=\"{errs}\" \
                 skipped=\"{skips}\" time=\"{}\">",
                results.len() + errs,
                seconds(time)
            );
            for result in results {
                let _ = write!(
                    suites,
                    "    <testcase classname=\"{file}\" name=\"{}\" time=\"{}\"",
                    xml(&result.name),
                    seconds(result.elapsed)
                );
                match (&result.status, &result.failure) {
                    (TestStatus::Skipped, _) => {
                        suites.push_str(">\n      <skipped/>\n    </testcase>\n")
                    }
                    (TestStatus::Todo, _) => {
                        suites.push_str(">\n      <skipped message=\"todo\"/>\n    </testcase>\n");
                    }
                    (_, Some(failure)) => {
                        let mut text = failure.message.clone();
                        if let Some(stack) = &failure.stack {
                            text.push('\n');
                            text.push_str(stack);
                        }
                        if let Some(screen) = &failure.screen {
                            let texts: Vec<String> =
                                screen.iter().map(|t| format!("{t:?}")).collect();
                            text.push_str(&format!("\non screen: {}", texts.join(", ")));
                        }
                        let message = failure.message.lines().next().unwrap_or_default();
                        let _ = write!(
                            suites,
                            ">\n      <failure message=\"{}\">{}</failure>\n    </testcase>\n",
                            xml(message),
                            xml(&text)
                        );
                    }
                    _ => suites.push_str("/>\n"),
                }
            }
            if let Some(error) = error {
                let _ = write!(
                    suites,
                    "    <testcase classname=\"{file}\" name=\"{file}\" time=\"0.000\">\n      \
                     <error message=\"{}\">{}</error>\n    </testcase>\n",
                    xml(error.lines().next().unwrap_or_default()),
                    xml(error)
                );
            }
            suites.push_str("  </testsuite>\n");
        }
        format!(
            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n\
             <testsuites name=\"nsh test\" tests=\"{tests}\" failures=\"{failures}\" errors=\"{errors}\" \
             skipped=\"{skipped}\" time=\"{}\">\n{suites}</testsuites>\n",
            seconds(elapsed)
        )
    }
}

/// `text` as XML text or an attribute's value: escaped, without the
/// control characters XML 1.0 refuses.
fn xml(text: &str) -> String {
    let mut out = String::with_capacity(text.len());
    for c in text.chars() {
        match c {
            '&' => out.push_str("&amp;"),
            '<' => out.push_str("&lt;"),
            '>' => out.push_str("&gt;"),
            '"' => out.push_str("&quot;"),
            '\'' => out.push_str("&apos;"),
            '\n' => out.push_str("&#10;"),
            '\t' | '\r' => out.push(c),
            c if (c as u32) < 0x20 => {}
            c => out.push(c),
        }
    }
    out
}

/// Runs `request` in the headless runner of the app with Rust crates
/// `app`: builds the entries it asks for, shows its results and its log.
fn in_runner(
    app: &RustApp,
    request: &TestRequest,
    shown: &dyn Fn(&Path) -> String,
    tally: &mut Tally,
) -> anyhow::Result<()> {
    let runner = app.test_runner()?;
    let mut child = Command::new(&runner)
        .arg(serde_json::to_string(request)?)
        .stdin(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()
        .with_context(|| format!("run {}", runner.display()))?;
    let mut input = child.stdin.take().context("the runner's standard input")?;
    let stderr = child.stderr.take().context("the runner's standard error")?;
    let mut builds = 0;
    for line in BufReader::new(stderr).lines() {
        let line = line?;
        match RunnerMessage::parse(&line) {
            Some(RunnerMessage::Log {
                level,
                target,
                message,
            }) => {
                let level = level.parse().unwrap_or(log::Level::Info);
                logger::forward(level, &target, &message);
            }
            Some(RunnerMessage::Build { entry, kind }) => {
                builds += 1;
                let reply = build_for_runner(&entry, kind, &request.work_dir, builds);
                writeln!(input, "{}", serde_json::to_string(&reply)?)
                    .context("answer the runner")?;
            }
            Some(RunnerMessage::Result { file, result }) => tally.show(&shown(&file), &result),
            Some(RunnerMessage::Failed { file, message }) => {
                tally.failed(&shown(&file), &message);
            }
            None => ui::plain(line),
        }
    }
    let status = child.wait()?;
    if !status.success() {
        bail!(
            "the headless runner {} exited with {status}",
            ui::path(&runner)
        );
    }
    Ok(())
}

/// Builds `entry` for the app's runner, the `n`th build of the run: its
/// files in `work_dir`, or the app's root.
fn build_for_runner(entry: &Path, kind: Entry, work_dir: &Path, n: usize) -> Reply {
    let built = (|| -> anyhow::Result<Reply> {
        let (bytecode, map) = match kind {
            Entry::TestFile => test_file_bytecode(entry)?,
            Entry::App => {
                let entry = crate::entry::resolve(entry)?;
                if crate::rust_app::is_root(&entry) {
                    return Ok(Reply::Root);
                }
                bytecode_of(&entry, &crate::ui_sets(), true)?
            }
        };
        let dir = work_dir.join("build");
        std::fs::create_dir_all(&dir).with_context(|| format!("{}", dir.display()))?;
        let file = dir.join(format!("{n}.nshc"));
        std::fs::write(&file, bytecode).with_context(|| format!("write {}", file.display()))?;
        let source_map = match map {
            Some(map) => {
                let path = dir.join(format!("{n}.js.map"));
                std::fs::write(&path, map).with_context(|| format!("write {}", path.display()))?;
                Some(path)
            }
            None => None,
        };
        Ok(Reply::Js {
            bytecode: file,
            source_map,
        })
    })();
    built.unwrap_or_else(|e| Reply::Failed {
        message: format!("{e:#}"),
    })
}

/// The entry made for a test file, bundled against the app's sets and
/// `nsh/test`, and compiled.
fn test_file_bytecode(entry: &Path) -> anyhow::Result<(Vec<u8>, Option<String>)> {
    let mut sets = crate::ui_sets().to_vec();
    sets.extend(nsh_testing::test_sets().iter().map(SetDescription::from));
    bytecode_of(entry, &sets, false)
}

/// `entry` bundled against `sets` and compiled to bytecode, with its
/// source map; `announce`: saying so.
fn bytecode_of(
    entry: &Path,
    sets: &[SetDescription],
    announce: bool,
) -> anyhow::Result<(Vec<u8>, Option<String>)> {
    let bundle = nsh_bundler::bundle(&BundleOptions {
        entry: entry.to_path_buf(),
        minify: false,
        split: false,
        ui_sets: sets.to_vec(),
    })
    .map_err(|e| BuildError::from(e).into_error(entry))?;
    if announce {
        ui::done(format!(
            "bundled {} {}",
            ui::path(entry),
            ui::dim(format!(
                "({} B in {:.1} ms)",
                bundle.code.len(),
                bundle.elapsed_ms
            ))
        ));
    }
    let bytecode = nsh_js::compile_bytecode_with(&bundle.code, false, sets)?;
    Ok((bytecode, bundle.source_map))
}

/// Prints how a test of the file shown as `file` ended: a line, and for a
/// failure what was thrown, where, and what was on screen.
fn show(file: &str, result: &TestResult) {
    let line = format!(
        "{file} › {} {}",
        result.name,
        ui::dim(format!("({})", ui::duration(result.elapsed)))
    );
    let failure = match (result.status, &result.failure) {
        (TestStatus::Skipped, _) => {
            ui::plain(format!("{} {line} {}", ui::dim("○"), ui::dim("skipped")));
            return;
        }
        (TestStatus::Todo, _) => {
            ui::plain(format!(
                "{} {file} › {} {}",
                ui::yellow("✎"),
                result.name,
                ui::yellow("todo")
            ));
            return;
        }
        (_, Some(failure)) => failure,
        (_, None) => {
            ui::done(line);
            return;
        }
    };
    ui::plain(format!("{} {line}", ui::red("✗")));
    for text in failure.message.lines() {
        ui::detail(format!("  {text}"));
    }
    if let Some(stack) = &failure.stack {
        // The frames in the test file: the runtime's own say nothing.
        for frame in stack.lines().filter(|l| !l.contains("(native)")) {
            ui::detail(ui::dim(format!("  {}", frame.trim_start())));
        }
    }
    // A step's error says what is on screen already.
    if let Some(screen) = failure
        .screen
        .as_ref()
        .filter(|_| !failure.message.contains("on screen: "))
    {
        let texts: Vec<String> = screen.iter().map(|t| format!("{t:?}")).collect();
        ui::detail(format!("  on screen: {}", texts.join(", ")));
    }
}

/// The entry of the app `path` is part of: a directory's, a test file's
/// (the nearest directory up with an app), or `path` itself.
pub(crate) fn app_entry(path: &Path) -> anyhow::Result<PathBuf> {
    if path.is_dir() {
        return crate::entry::resolve(path);
    }
    if !is_test_file(path) {
        return Ok(path.to_owned());
    }
    let mut dir = path.parent();
    while let Some(d) = dir {
        if d.join("nsh.json").is_file() || crate::entry::resolve(d).is_ok() {
            return crate::entry::resolve(d);
        }
        dir = d.parent();
    }
    bail!(
        "{}: no app around it (an App.tsx or nsh.json)",
        ui::path(path)
    )
}

fn is_test_file(path: &Path) -> bool {
    path.is_file()
        && path
            .file_name()
            .and_then(|n| n.to_str())
            .is_some_and(|n| n.ends_with(".test.tsx") || n.ends_with(".test.ts"))
}

/// Adds the test files under `dir` to `out`, outside hidden directories
/// (`.nsh`), `node_modules` and `target`.
fn find_tests(dir: &Path, out: &mut Vec<PathBuf>) {
    let Ok(entries) = std::fs::read_dir(dir) else {
        return;
    };
    for entry in entries.flatten() {
        let path = entry.path();
        let name = entry.file_name();
        let name = name.to_string_lossy();
        if path.is_dir() {
            if !name.starts_with('.') && name != "node_modules" && name != "target" {
                find_tests(&path, out);
            }
        } else if is_test_file(&path) {
            out.push(path);
        }
    }
}

/// A test file that opens the app at `entry` on the network, lets it run
/// for a while, then takes the steps standard input gives (none from a
/// terminal), with `app` the app.
fn steps_file(work_dir: &Path, entry: &Path) -> anyhow::Result<PathBuf> {
    let mut steps = String::new();
    let stdin = std::io::stdin();
    if !stdin.is_terminal() {
        stdin
            .lock()
            .read_to_string(&mut steps)
            .context("read the steps from standard input")?;
    }
    let name = entry
        .file_name()
        .map_or("app".into(), |n| n.to_string_lossy().into_owned());
    let entry_js = serde_json::to_string(&entry.to_string_lossy().replace('\\', "/"))?;
    let code = format!(
        "// Made by `nsh test {name}`: the steps of standard input.\n\
         import {{ expect, open, test }} from \"nsh/test\";\n\n\
         test(\"steps\", async () => {{\n\
         const app = await open({entry_js}, {{ network: \"live\" }});\n\
         await app.wait({IDLE_MS});\n\
         {steps}\n\
         }});\n"
    );
    std::fs::create_dir_all(work_dir).with_context(|| format!("{}", work_dir.display()))?;
    let file = work_dir.join(format!("{name}.steps.test.ts"));
    std::fs::write(&file, code).with_context(|| format!("write {}", file.display()))?;
    Ok(file)
}

/// Builds the apps tests open against the UI sets this command line
/// serves (each entry once), and the entries made for test files against
/// them and `nsh/test`, in this process.
fn compiler() -> nsh_testing::Compile {
    type Bytecode = (Vec<u8>, Option<String>);
    let built: Mutex<HashMap<PathBuf, Bytecode>> = Mutex::new(HashMap::new());
    Arc::new(move |entry: &Path, kind: Entry| {
        let (bytecode, map) = match kind {
            Entry::App => {
                let entry = crate::entry::resolve(entry).map_err(|e| format!("{e:#}"))?;
                let cached = built
                    .lock()
                    .unwrap_or_else(|e| e.into_inner())
                    .get(&entry)
                    .cloned();
                match cached {
                    Some(built) => built,
                    None => {
                        let out = bytecode_of(&entry, &crate::ui_sets(), true)
                            .map_err(|e| format!("{e:#}"))?;
                        built
                            .lock()
                            .unwrap_or_else(|e| e.into_inner())
                            .insert(entry, out.clone());
                        out
                    }
                }
            }
            Entry::TestFile => test_file_bytecode(entry).map_err(|e| format!("{e:#}"))?,
        };
        // SAFETY: compiled just now by this runtime.
        Ok(Built::Js(
            Box::new(unsafe { Bundle::bytecode(bytecode) }),
            map,
        ))
    })
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_files_are_found_where_the_app_keeps_them_and_know_their_app() {
        let dir = std::env::temp_dir().join(format!("nsh-test-files-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        for file in [
            "App.tsx",
            "App.test.tsx",
            "src/cart/Cart.test.ts",
            "src/cart/Cart.tsx",
            ".nsh/test/App.test.tsx.run.js",
            ".nsh/test/Old.test.ts",
            "node_modules/x/x.test.ts",
        ] {
            let path = dir.join(file);
            std::fs::create_dir_all(path.parent().unwrap()).unwrap();
            std::fs::write(&path, "").unwrap();
        }
        let dir = dunce::canonicalize(&dir).unwrap();
        let mut found = Vec::new();
        find_tests(&dir, &mut found);
        found.sort();
        assert_eq!(
            found,
            [dir.join("App.test.tsx"), dir.join("src/cart/Cart.test.ts")]
        );
        // A test file's app is the nearest one up; a directory's is its own;
        // any other file is an entry.
        let entry = dir.join("App.tsx");
        assert_eq!(
            app_entry(&dir.join("src/cart/Cart.test.ts")).unwrap(),
            entry
        );
        assert_eq!(app_entry(&dir).unwrap(), entry);
        assert_eq!(
            app_entry(&dir.join("src/cart/Cart.tsx")).unwrap(),
            dir.join("src/cart/Cart.tsx")
        );
        std::fs::remove_dir_all(&dir).unwrap();
    }

    #[test]
    fn a_junit_report_has_a_suite_per_file_and_says_how_each_test_ended() {
        let result =
            |json: serde_json::Value| -> TestResult { serde_json::from_value(json).unwrap() };
        let elapsed = serde_json::json!({ "secs": 0, "nanos": 250_000_000 });
        let mut tally = Tally::default();
        tally.show(
            "App.test.tsx",
            &result(serde_json::json!({ "name": "cart › adds", "elapsed": elapsed, "status": "Passed", "failure": null })),
        );
        tally.show(
            "App.test.tsx",
            &result(serde_json::json!({
                "name": "shows <b>",
                "elapsed": elapsed,
                "status": "Failed",
                "failure": { "message": "expected \"a\" to be \"b\"\nmore", "stack": "at (App.test.tsx:3:5)", "screen": ["a"] },
            })),
        );
        tally.show(
            "App.test.tsx",
            &result(serde_json::json!({ "name": "later", "elapsed": elapsed, "status": "Skipped", "failure": null })),
        );
        tally.show(
            "App.test.tsx",
            &result(serde_json::json!({ "name": "someday", "elapsed": elapsed, "status": "Todo", "failure": null })),
        );
        tally.failed("Broken.test.ts", "the file is broken");
        assert_eq!(
            (tally.passed, tally.failed, tally.skipped, tally.todo),
            (1, 2, 1, 1)
        );
        let report = tally.junit(std::time::Duration::from_secs(2));
        assert_eq!(
            report,
            r#"<?xml version="1.0" encoding="UTF-8"?>
<testsuites name="nsh test" tests="5" failures="1" errors="1" skipped="2" time="2.000">
  <testsuite name="App.test.tsx" tests="4" failures="1" errors="0" skipped="2" time="1.000">
    <testcase classname="App.test.tsx" name="cart › adds" time="0.250"/>
    <testcase classname="App.test.tsx" name="shows &lt;b&gt;" time="0.250">
      <failure message="expected &quot;a&quot; to be &quot;b&quot;">expected &quot;a&quot; to be &quot;b&quot;&#10;more&#10;at (App.test.tsx:3:5)&#10;on screen: &quot;a&quot;</failure>
    </testcase>
    <testcase classname="App.test.tsx" name="later" time="0.250">
      <skipped/>
    </testcase>
    <testcase classname="App.test.tsx" name="someday" time="0.250">
      <skipped message="todo"/>
    </testcase>
  </testsuite>
  <testsuite name="Broken.test.ts" tests="1" failures="0" errors="1" skipped="0" time="0.000">
    <testcase classname="Broken.test.ts" name="Broken.test.ts" time="0.000">
      <error message="the file is broken">the file is broken</error>
    </testcase>
  </testsuite>
</testsuites>
"#
        );
    }
}