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
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
//! Snapshot testing tools for [`Transcript`]s.
//!
//! # Examples
//!
//! Simple scenario in which the tested transcript calls to one or more Cargo binaries / examples
//! by their original names.
//!
//! ```
//! use term_transcript::{
//!     ShellOptions, Transcript,
//!     test::{MatchKind, TestConfig, TestOutputConfig},
//! };
//!
//! // Test configuration that can be shared across tests.
//! fn config() -> TestConfig {
//!     let shell_options = ShellOptions::default().with_cargo_path();
//!     TestConfig::new(shell_options)
//!         .with_match_kind(MatchKind::Precise)
//!         .with_output(TestOutputConfig::Verbose)
//! }
//!
//! // Usage in tests:
//! #[test]
//! fn help_command() {
//!     config().test("tests/__snapshots__/help.svg", &["my-command --help"]);
//! }
//! ```
//!
//! Use [`TestConfig::test_transcript()`] for more complex scenarios or increased control:
//!
//! ```
//! use term_transcript::{test::TestConfig, ShellOptions, Transcript, UserInput};
//! # use term_transcript::svg::{Template, TemplateOptions};
//! use std::io;
//!
//! fn read_svg_file() -> anyhow::Result<impl io::BufRead> {
//!     // snipped...
//! #   let transcript = Transcript::from_inputs(
//! #        &mut ShellOptions::default(),
//! #        vec![UserInput::command(r#"echo "Hello world!""#)],
//! #   )?;
//! #   let mut writer = vec![];
//! #   Template::new(TemplateOptions::default()).render(&transcript, &mut writer)?;
//! #   Ok(io::Cursor::new(writer))
//! }
//!
//! # fn main() -> anyhow::Result<()> {
//! let reader = read_svg_file()?;
//! let transcript = Transcript::from_svg(reader)?;
//! TestConfig::new(ShellOptions::default()).test_transcript(&transcript);
//! # Ok(())
//! # }
//! ```

use termcolor::{Color, ColorChoice, ColorSpec, NoColor, WriteColor};

#[cfg(feature = "svg")]
use std::ffi::OsStr;
use std::{
    env,
    fs::File,
    io::{self, BufReader, Write},
    path::Path,
    process::Command,
    str,
};

use crate::{traits::SpawnShell, Interaction, ShellOptions, TermError, Transcript};

mod color_diff;
mod parser;
mod utils;

pub use self::parser::Parsed;
use self::{
    color_diff::ColorSpan,
    utils::{ColorPrintlnWriter, IndentingWriter},
};
#[cfg(feature = "svg")]
use crate::svg::Template;
use crate::{test::color_diff::ColorDiff, UserInput};

/// Configuration of output produced during testing.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum TestOutputConfig {
    /// Do not output anything.
    Quiet,
    /// Output normal amount of details.
    Normal,
    /// Output more details.
    Verbose,
}

impl Default for TestOutputConfig {
    fn default() -> Self {
        Self::Normal
    }
}

/// Strategy for saving a new snapshot on a test failure within [`TestConfig::test()`] and
/// related methods.
#[derive(Debug, Clone, Copy, PartialEq, Hash)]
#[non_exhaustive]
#[cfg(feature = "svg")]
#[cfg_attr(docsrs, doc(cfg(feature = "svg")))]
pub enum UpdateMode {
    /// Never create a new snapshot on test failure.
    Never,
    /// Always create a new snapshot on test failure.
    Always,
}

#[cfg(feature = "svg")]
impl UpdateMode {
    /// Reads the update mode from the `TERM_TRANSCRIPT_UPDATE` env variable.
    ///
    /// If the `TERM_TRANSCRIPT_UPDATE` variable is not set, the output depends on whether
    /// the executable is running in CI (which is detected by the presence of
    /// the `CI` env variable):
    ///
    /// - In CI, the method returns [`Self::Never`].
    /// - Otherwise, the method returns [`Self::Always`].
    ///
    /// # Panics
    ///
    /// If the `TERM_TRANSCRIPT_UPDATE` env variable is set to an unrecognized value
    /// (something other than `never` or `always`), this method will panic.
    pub fn from_env() -> Self {
        const ENV_VAR: &str = "TERM_TRANSCRIPT_UPDATE";

        match env::var_os(ENV_VAR) {
            Some(s) => Self::from_os_str(&s).unwrap_or_else(|| {
                panic!(
                    "Cannot read update mode from env variable {}: `{}` is not a valid value \
                     (use one of `never` or `always`)",
                    ENV_VAR,
                    s.to_string_lossy()
                );
            }),
            None => {
                if env::var_os("CI").is_some() {
                    Self::Never
                } else {
                    Self::Always
                }
            }
        }
    }

    fn from_os_str(s: &OsStr) -> Option<Self> {
        match s {
            s if s == "never" => Some(Self::Never),
            s if s == "always" => Some(Self::Always),
            _ => None,
        }
    }

    fn should_create_snapshot(self) -> bool {
        match self {
            Self::Always => true,
            Self::Never => false,
        }
    }
}

/// Testing configuration.
///
/// # Examples
///
/// See the [module docs](crate::test) for the examples of usage.
#[derive(Debug)]
pub struct TestConfig<Cmd = Command> {
    shell_options: ShellOptions<Cmd>,
    match_kind: MatchKind,
    output: TestOutputConfig,
    color_choice: ColorChoice,
    #[cfg(feature = "svg")]
    update_mode: UpdateMode,
    #[cfg(feature = "svg")]
    template: Template,
}

impl<Cmd: SpawnShell> TestConfig<Cmd> {
    /// Creates a new config.
    ///
    /// # Panics
    ///
    /// - Panics if the `svg` crate feature is enabled and the `TERM_TRANSCRIPT_UPDATE` variable
    ///   is set to an incorrect value. See [`UpdateMode::from_env()`] for more details.
    pub fn new(shell_options: ShellOptions<Cmd>) -> Self {
        Self {
            shell_options,
            match_kind: MatchKind::TextOnly,
            output: TestOutputConfig::Normal,
            color_choice: ColorChoice::Auto,
            #[cfg(feature = "svg")]
            update_mode: UpdateMode::from_env(),
            #[cfg(feature = "svg")]
            template: Template::default(),
        }
    }

    /// Sets the matching kind applied.
    pub fn with_match_kind(mut self, kind: MatchKind) -> Self {
        self.match_kind = kind;
        self
    }

    /// Sets coloring of the output.
    ///
    /// On Windows, `color_choice` has slightly different semantics than its usage
    /// in the `termcolor` crate. Namely, if colors can be used (stdout is a tty with
    /// color support), ANSI escape sequences will always be used.
    pub fn with_color_choice(mut self, color_choice: ColorChoice) -> Self {
        self.color_choice = color_choice;
        self
    }

    /// Configures test output.
    pub fn with_output(mut self, output: TestOutputConfig) -> Self {
        self.output = output;
        self
    }

    /// Sets the template for rendering new snapshots.
    #[cfg(feature = "svg")]
    #[cfg_attr(docsrs, doc(cfg(feature = "svg")))]
    pub fn with_template(mut self, template: Template) -> Self {
        self.template = template;
        self
    }

    /// Overrides the strategy for saving new snapshots for failed tests.
    ///
    /// By default, the strategy is determined from the execution environment
    /// using [`UpdateMode::from_env()`].
    #[cfg(feature = "svg")]
    #[cfg_attr(docsrs, doc(cfg(feature = "svg")))]
    pub fn with_update_mode(mut self, update_mode: UpdateMode) -> Self {
        self.update_mode = update_mode;
        self
    }

    /// Tests a snapshot at the specified path with the provided inputs.
    ///
    /// If the path is relative, it is resolved relative to the current working dir,
    /// which in the case of tests is the root directory of the including crate (i.e., the dir
    /// where the crate manifest is located). You may specify an absolute path
    /// using env vars that Cargo sets during build, such as [`env!("CARGO_MANIFEST_DIR")`].
    ///
    /// Similar to other kinds of snapshot testing, a new snapshot will be generated if
    /// there is no existing snapshot or there are mismatches between inputs or outputs
    /// in the original and reproduced transcripts. This new snapshot will have the same path
    /// as the original snapshot, but with the `.new.svg` extension. As an example,
    /// if the snapshot at `snapshots/help.svg` is tested, the new snapshot will be saved at
    /// `snapshots/help.new.svg`.
    ///
    /// Generation of new snapshots will only happen if the `svg` crate feature is enabled
    /// (which it is by default), and if the [update mode](Self::with_update_mode())
    /// is not [`UpdateMode::Never`], either because it was set explicitly or
    /// [inferred](UpdateMode::from_env()) from the execution environment.
    ///
    /// The snapshot template can be customized via [`Self::with_template()`].
    ///
    /// # Panics
    ///
    /// - Panics if there is no snapshot at the specified path, or if the path points
    ///   to a directory.
    /// - Panics if an error occurs during reproducing the transcript or processing
    ///   its output.
    /// - Panics if there are mismatches between inputs or outputs in the original and reproduced
    ///   transcripts.
    ///
    /// [`env!("CARGO_MANIFEST_DIR")`]: https://doc.rust-lang.org/cargo/reference/environment-variables.html#environment-variables-cargo-sets-for-crates
    pub fn test<I: Into<UserInput>>(
        &mut self,
        snapshot_path: impl AsRef<Path>,
        inputs: impl IntoIterator<Item = I>,
    ) {
        let inputs = inputs.into_iter().map(Into::into);
        let snapshot_path = snapshot_path.as_ref();

        if snapshot_path.is_file() {
            let snapshot = File::open(snapshot_path).unwrap_or_else(|err| {
                panic!("Cannot open `{:?}`: {}", snapshot_path, err);
            });
            let snapshot = BufReader::new(snapshot);
            let transcript = Transcript::from_svg(snapshot).unwrap_or_else(|err| {
                panic!("Cannot parse snapshot from `{:?}`: {}", snapshot_path, err);
            });
            self.compare_and_test_transcript(
                snapshot_path,
                &transcript,
                &inputs.collect::<Vec<_>>(),
            );
        } else if snapshot_path.exists() {
            panic!(
                "Snapshot path `{:?}` exists, but is not a file",
                snapshot_path
            );
        } else {
            let new_snapshot_message = self.create_and_write_new_snapshot(snapshot_path, inputs);
            panic!(
                "Snapshot `{:?}` is missing\n{}",
                snapshot_path, new_snapshot_message
            );
        }
    }

    fn compare_and_test_transcript(
        &mut self,
        snapshot_path: &Path,
        transcript: &Transcript<Parsed>,
        expected_inputs: &[UserInput],
    ) {
        let actual_inputs: Vec<_> = transcript
            .interactions()
            .iter()
            .map(Interaction::input)
            .collect();

        if !actual_inputs.iter().copied().eq(expected_inputs) {
            let new_snapshot_message =
                self.create_and_write_new_snapshot(snapshot_path, expected_inputs.iter().cloned());
            panic!(
                "Unexpected user inputs in parsed snapshot: expected {exp:?}, got {act:?}\n{msg}",
                exp = expected_inputs,
                act = actual_inputs,
                msg = new_snapshot_message
            );
        }

        let (stats, reproduced) = self
            .test_transcript_for_stats(transcript)
            .unwrap_or_else(|err| panic!("{}", err));
        if stats.errors(self.match_kind) > 0 {
            let new_snapshot_message = self.write_new_snapshot(snapshot_path, &reproduced);
            panic!("There were test failures\n{}", new_snapshot_message);
        }
    }

    #[cfg(feature = "svg")]
    fn create_and_write_new_snapshot(
        &mut self,
        path: &Path,
        inputs: impl Iterator<Item = UserInput>,
    ) -> String {
        let reproduced =
            Transcript::from_inputs(&mut self.shell_options, inputs).unwrap_or_else(|err| {
                panic!("Cannot create a snapshot `{:?}`: {}", path, err);
            });
        self.write_new_snapshot(path, &reproduced)
    }

    /// Returns a message to be appended to the panic message.
    #[cfg(feature = "svg")]
    fn write_new_snapshot(&self, path: &Path, transcript: &Transcript) -> String {
        if !self.update_mode.should_create_snapshot() {
            return format!("Skipped writing new snapshot `{:?}` per test config", path);
        }

        let mut new_path = path.to_owned();
        new_path.set_extension("new.svg");
        let new_snapshot = File::create(&new_path).unwrap_or_else(|err| {
            panic!(
                "Cannot create file for new snapshot `{:?}`: {}",
                new_path, err
            );
        });
        self.template
            .render(transcript, &mut io::BufWriter::new(new_snapshot))
            .unwrap_or_else(|err| {
                panic!("Cannot render snapshot `{:?}`: {}", new_path, err);
            });
        format!("A new snapshot was saved to `{:?}`", new_path)
    }

    #[cfg(not(feature = "svg"))]
    #[allow(clippy::unused_self)] // necessary for uniformity
    fn write_new_snapshot(&self, _: &Path, _: &Transcript) -> String {
        format!(
            "Not writing a new snapshot since `{}/svg` feature is not enabled",
            env!("CARGO_CRATE_NAME")
        )
    }

    #[cfg(not(feature = "svg"))]
    #[allow(clippy::unused_self)] // necessary for uniformity
    fn create_and_write_new_snapshot(
        &mut self,
        _: &Path,
        _: impl Iterator<Item = UserInput>,
    ) -> String {
        format!(
            "Not writing a new snapshot since `{}/svg` feature is not enabled",
            env!("CARGO_CRATE_NAME")
        )
    }

    /// Tests the `transcript`. This is a lower-level alternative to [`Self::test()`].
    ///
    /// # Panics
    ///
    /// - Panics if an error occurs during reproducing the transcript or processing
    ///   its output.
    /// - Panics if there are mismatches between outputs in the original and reproduced
    ///   transcripts.
    pub fn test_transcript(&mut self, transcript: &Transcript<Parsed>) {
        let (stats, _) = self
            .test_transcript_for_stats(transcript)
            .unwrap_or_else(|err| panic!("{}", err));
        stats.assert_no_errors(self.match_kind);
    }

    /// Tests the `transcript` and returns testing stats together with
    /// the reproduced [`Transcript`]. This is a lower-level alternative to [`Self::test()`].
    ///
    /// # Errors
    ///
    /// - Returns an error if an error occurs during reproducing the transcript or processing
    ///   its output.
    pub fn test_transcript_for_stats(
        &mut self,
        transcript: &Transcript<Parsed>,
    ) -> io::Result<(TestStats, Transcript)> {
        if self.output == TestOutputConfig::Quiet {
            let mut out = NoColor::new(io::sink());
            self.test_transcript_inner(&mut out, transcript)
        } else {
            let mut out = ColorPrintlnWriter::new(self.color_choice);
            self.test_transcript_inner(&mut out, transcript)
        }
    }

    fn test_transcript_inner(
        &mut self,
        out: &mut impl WriteColor,
        transcript: &Transcript<Parsed>,
    ) -> io::Result<(TestStats, Transcript)> {
        let inputs = transcript
            .interactions()
            .iter()
            .map(|interaction| interaction.input().clone());
        let reproduced = Transcript::from_inputs(&mut self.shell_options, inputs)?;

        let stats = self.compare_transcripts(out, transcript, &reproduced)?;
        Ok((stats, reproduced))
    }

    fn compare_transcripts(
        &self,
        out: &mut impl WriteColor,
        parsed: &Transcript<Parsed>,
        reproduced: &Transcript,
    ) -> io::Result<TestStats> {
        let it = parsed
            .interactions()
            .iter()
            .zip(reproduced.interactions().iter().map(Interaction::output));

        let mut stats = TestStats {
            matches: Vec::with_capacity(parsed.interactions().len()),
        };
        for (original, reproduced) in it {
            write!(out, "  ")?;
            out.set_color(ColorSpec::new().set_intense(true))?;
            write!(out, "[")?;

            // First, process text only.
            let original_text = original.output().plaintext();
            let reproduced_text = reproduced
                .to_plaintext()
                .map_err(|err| io::Error::new(io::ErrorKind::InvalidInput, err))?;
            let mut actual_match = if original_text == reproduced_text {
                Some(MatchKind::TextOnly)
            } else {
                None
            };

            // If we do precise matching, check it as well.
            let color_diff = if self.match_kind == MatchKind::Precise && actual_match.is_some() {
                let original_spans = &original.output().color_spans;
                let reproduced_spans =
                    ColorSpan::parse(reproduced.as_ref()).map_err(|err| match err {
                        TermError::Io(err) => err,
                        other => io::Error::new(io::ErrorKind::InvalidInput, other),
                    })?;

                let diff = ColorDiff::new(original_spans, &reproduced_spans);
                if diff.is_empty() {
                    actual_match = Some(MatchKind::Precise);
                    None
                } else {
                    Some(diff)
                }
            } else {
                None
            };

            stats.matches.push(actual_match);
            if actual_match >= Some(self.match_kind) {
                out.set_color(ColorSpec::new().set_reset(false).set_fg(Some(Color::Green)))?;
                write!(out, "+")?;
            } else {
                out.set_color(ColorSpec::new().set_reset(false).set_fg(Some(Color::Red)))?;
                if color_diff.is_some() {
                    write!(out, "#")?;
                } else {
                    write!(out, "-")?;
                }
            }
            out.set_color(ColorSpec::new().set_intense(true))?;
            write!(out, "]")?;
            out.reset()?;
            writeln!(out, " Input: {}", original.input().as_ref())?;

            if let Some(diff) = color_diff {
                let original_spans = &original.output().color_spans;
                diff.highlight_text(out, original_text, original_spans)?;
                diff.write_as_table(out)?;
            } else if actual_match.is_none() {
                Self::write_diff(out, original_text, &reproduced_text)?;
            } else if self.output == TestOutputConfig::Verbose {
                out.set_color(ColorSpec::new().set_fg(Some(Color::Ansi256(244))))?;
                let mut out_with_indents = IndentingWriter::new(&mut *out, b"    ");
                writeln!(out_with_indents, "{}", original.output().plaintext())?;
                out.reset()?;
            }
        }

        Ok(stats)
    }

    #[cfg(feature = "pretty_assertions")]
    fn write_diff(out: &mut impl Write, original: &str, reproduced: &str) -> io::Result<()> {
        use pretty_assertions::Comparison;
        use std::fmt;

        // Since `Comparison` uses `fmt::Debug`, we define this simple wrapper
        // to switch to `fmt::Display`.
        struct DebugStr<'a>(&'a str);

        impl fmt::Debug for DebugStr<'_> {
            fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
                // Align output with verbose term output. Since `Comparison` adds one space,
                // we need to add 3 spaces instead of 4.
                for line in self.0.lines() {
                    writeln!(formatter, "   {}", line)?;
                }
                Ok(())
            }
        }

        write!(
            out,
            "    {}",
            Comparison::new(&DebugStr(original), &DebugStr(reproduced))
        )
    }

    #[cfg(not(feature = "pretty_assertions"))]
    fn write_diff(out: &mut impl Write, original: &str, reproduced: &str) -> io::Result<()> {
        writeln!(out, "  Original:")?;
        for line in original.lines() {
            writeln!(out, "    {}", line)?;
        }
        writeln!(out, "  Reproduced:")?;
        for line in reproduced.lines() {
            writeln!(out, "    {}", line)?;
        }
        Ok(())
    }
}

/// Kind of terminal output matching.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[non_exhaustive]
pub enum MatchKind {
    /// Relaxed matching: compare only output text, but not coloring.
    TextOnly,
    /// Precise matching: compare output together with colors.
    Precise,
}

/// Stats of a single snapshot test output by [`TestConfig::test_transcript_for_stats()`].
#[derive(Debug, Clone)]
pub struct TestStats {
    // Match kind per each user input.
    matches: Vec<Option<MatchKind>>,
}

impl TestStats {
    /// Returns the number of successfully matched user inputs with at least the specified
    /// `match_level`.
    pub fn passed(&self, match_level: MatchKind) -> usize {
        self.matches
            .iter()
            .filter(|&&kind| kind >= Some(match_level))
            .count()
    }

    /// Returns the number of user inputs that do not match with at least the specified
    /// `match_level`.
    pub fn errors(&self, match_level: MatchKind) -> usize {
        self.matches.len() - self.passed(match_level)
    }

    /// Returns match kinds per each user input of the tested [`Transcript`]. `None` values
    /// mean no match.
    pub fn matches(&self) -> &[Option<MatchKind>] {
        &self.matches
    }

    /// Panics if these stats contain errors.
    #[allow(clippy::missing_panics_doc)]
    pub fn assert_no_errors(&self, match_level: MatchKind) {
        assert_eq!(self.errors(match_level), 0, "There were test errors");
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{
        svg::{Template, TemplateOptions},
        Captured, UserInput,
    };

    fn test_snapshot_testing(test_config: &mut TestConfig) -> anyhow::Result<()> {
        let transcript = Transcript::from_inputs(
            &mut ShellOptions::default(),
            vec![UserInput::command("echo \"Hello, world!\"")],
        )?;

        let mut svg_buffer = vec![];
        Template::new(TemplateOptions::default()).render(&transcript, &mut svg_buffer)?;

        let parsed = Transcript::from_svg(svg_buffer.as_slice())?;
        test_config.test_transcript(&parsed);
        Ok(())
    }

    #[test]
    fn snapshot_testing_with_default_params() -> anyhow::Result<()> {
        let mut test_config = TestConfig::new(ShellOptions::default());
        test_snapshot_testing(&mut test_config)
    }

    #[test]
    fn snapshot_testing_with_exact_match() -> anyhow::Result<()> {
        let test_config = TestConfig::new(ShellOptions::default());
        test_snapshot_testing(&mut test_config.with_match_kind(MatchKind::Precise))
    }

    fn test_negative_snapshot_testing(
        out: &mut Vec<u8>,
        test_config: &mut TestConfig,
    ) -> anyhow::Result<()> {
        let mut transcript = Transcript::from_inputs(
            &mut ShellOptions::default(),
            vec![UserInput::command("echo \"Hello, world!\"")],
        )?;
        transcript.add_interaction(UserInput::command("echo \"Sup?\""), "Nah");

        let mut svg_buffer = vec![];
        Template::new(TemplateOptions::default()).render(&transcript, &mut svg_buffer)?;

        let parsed = Transcript::from_svg(svg_buffer.as_slice())?;
        let (stats, _) = test_config.test_transcript_inner(&mut NoColor::new(out), &parsed)?;
        assert_eq!(stats.errors(MatchKind::TextOnly), 1);
        Ok(())
    }

    #[test]
    fn negative_snapshot_testing_with_default_output() {
        let mut out = vec![];
        let mut test_config =
            TestConfig::new(ShellOptions::default()).with_color_choice(ColorChoice::Never);
        test_negative_snapshot_testing(&mut out, &mut test_config).unwrap();

        let out = String::from_utf8(out).unwrap();
        assert!(out.contains("[+] Input: echo \"Hello, world!\""), "{}", out);
        assert_eq!(out.matches("Hello, world!").count(), 1, "{}", out);
        // ^ output for successful interactions should not be included
        assert!(out.contains("[-] Input: echo \"Sup?\""), "{}", out);
        assert!(out.contains("Nah"), "{}", out);
    }

    #[test]
    fn negative_snapshot_testing_with_verbose_output() {
        let mut out = vec![];
        let mut test_config = TestConfig::new(ShellOptions::default())
            .with_output(TestOutputConfig::Verbose)
            .with_color_choice(ColorChoice::Never);
        test_negative_snapshot_testing(&mut out, &mut test_config).unwrap();

        let out = String::from_utf8(out).unwrap();
        assert!(out.contains("[+] Input: echo \"Hello, world!\""), "{}", out);
        assert_eq!(out.matches("Hello, world!").count(), 2, "{}", out);
        // ^ output for successful interactions should be included
        assert!(out.contains("[-] Input: echo \"Sup?\""), "{}", out);
        assert!(out.contains("Nah"), "{}", out);
    }

    fn diff_snapshot_with_color(
        expected_capture: &str,
        actual_capture: &str,
    ) -> (TestStats, String) {
        let expected_capture = Captured::new(expected_capture.to_owned());
        let parsed = Transcript {
            interactions: vec![Interaction {
                input: UserInput::command("test"),
                output: Parsed {
                    plaintext: expected_capture.to_plaintext().unwrap(),
                    color_spans: ColorSpan::parse(expected_capture.as_ref()).unwrap(),
                    html: expected_capture.to_html().unwrap(),
                },
            }],
        };

        let mut reproduced = Transcript::new();
        reproduced.add_interaction(UserInput::command("test"), actual_capture);

        let mut out: Vec<u8> = vec![];
        let stats = TestConfig::new(ShellOptions::default())
            .with_match_kind(MatchKind::Precise)
            .compare_transcripts(&mut NoColor::new(&mut out), &parsed, &reproduced)
            .unwrap();
        (stats, String::from_utf8(out).unwrap())
    }

    #[test]
    fn snapshot_testing_with_color_diff() {
        let (stats, out) = diff_snapshot_with_color(
            "Apr 18 12:54 \u{1b}[0m\u{1b}[34m.\u{1b}[0m",
            "Apr 18 12:54 \u{1b}[0m\u{1b}[34m.\u{1b}[0m",
        );

        assert_eq!(stats.matches(), [Some(MatchKind::Precise)]);
        assert!(out.contains("[+] Input: test"), "{}", out);
    }

    #[test]
    fn no_match_for_snapshot_testing_with_color_diff() {
        let (stats, out) = diff_snapshot_with_color(
            "Apr 18 12:54 \u{1b}[0m\u{1b}[33m.\u{1b}[0m",
            "Apr 19 12:54 \u{1b}[0m\u{1b}[33m.\u{1b}[0m",
        );

        assert_eq!(stats.matches(), [None]);
        assert!(out.contains("[-] Input: test"), "{}", out);
    }

    #[test]
    fn text_match_for_snapshot_testing_with_color_diff() {
        let (stats, out) = diff_snapshot_with_color(
            "Apr 18 12:54 \u{1b}[0m\u{1b}[33m.\u{1b}[0m",
            "Apr 18 12:54 \u{1b}[0m\u{1b}[34m.\u{1b}[0m",
        );

        assert_eq!(stats.matches(), [Some(MatchKind::TextOnly)]);
        assert!(out.contains("[#] Input: test"), "{}", out);
        assert!(out.contains("13..14 ----   yellow/(none)   ----     blue/(none)"));
    }
}