Skip to main content

Snapshot

Struct Snapshot 

Source
pub struct Snapshot { /* private fields */ }
Expand description

A normalized, comparable rendering of some compiler output.

Snapshots normalize three things so that byte-for-byte equality is not required for a test to pass:

  • Line endings. \r\n and lone \r both become \n.
  • Trailing whitespace. Spaces and tabs at the end of each line are stripped, so an editor that trims (or fails to trim) lines does not break a test.
  • Trailing blank lines. A trailing newline — or several — is removed, so the expected text can be written with or without one.

Interior blank lines and leading whitespace are preserved: they are usually significant (indentation in a pretty-printed tree, for example).

§Examples

Capture a value that implements Display:

use test_lang::Snapshot;

let snap = Snapshot::display(&42);
assert_eq!(snap.as_str(), "42");

Capture a token stream, one item per line:

use test_lang::Snapshot;

let tokens = ["let", "x", "=", "1"];
let snap = Snapshot::per_line(tokens);
assert_eq!(snap.as_str(), "let\nx\n=\n1");

Implementations§

Source§

impl Snapshot

Source

pub fn new(text: impl AsRef<str>) -> Self

Build a snapshot from an already-rendered block of text.

The input is normalized (see the type-level docs). Use this when the stage under test already hands you a String.

§Examples
use test_lang::Snapshot;

// Trailing whitespace and CRLF endings are normalized away.
let snap = Snapshot::new("a  \r\nb\n");
assert_eq!(snap.as_str(), "a\nb");
Source

pub fn display(value: &impl Display) -> Self

Build a snapshot by rendering a value through its Display implementation.

This is the natural entry point for a value that already knows how to print itself the way a test should read it — a formatted diagnostic, a single token, a pretty-printed tree.

§Examples
use core::fmt;
use test_lang::Snapshot;

struct Diagnostic;
impl fmt::Display for Diagnostic {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "error: unexpected token")
    }
}

let snap = Snapshot::display(&Diagnostic);
assert_eq!(snap.as_str(), "error: unexpected token");
Source

pub fn debug(value: &impl Debug) -> Self

Build a snapshot by rendering a value through its Debug implementation, using the alternate ({:#?}) pretty form.

Most syntax-tree node types derive Debug but not Display; this captures the multi-line pretty-printed tree without requiring the node to implement a display format of its own.

§Examples
use test_lang::Snapshot;

#[derive(Debug)]
struct Binary { op: char }

let snap = Snapshot::debug(&Binary { op: '+' });
assert!(snap.as_str().contains("op: '+'"));
Source

pub fn per_line<I>(items: I) -> Self
where I: IntoIterator, I::Item: Display,

Build a snapshot from a sequence of values, rendering each on its own line through Display.

This is the idiomatic way to snapshot a token stream: one token per line makes the diff on failure point at the exact token that changed.

§Examples
use test_lang::Snapshot;

let kinds = ["Ident(x)", "Eq", "Int(1)"];
let snap = Snapshot::per_line(kinds);
assert_eq!(snap.as_str(), "Ident(x)\nEq\nInt(1)");

An empty sequence yields an empty snapshot:

use test_lang::Snapshot;

let empty: [&str; 0] = [];
assert_eq!(Snapshot::per_line(empty).as_str(), "");
Source

pub fn as_str(&self) -> &str

The normalized snapshot text.

This is what check compares, and what you paste back into a test as the expected value when accepting a new snapshot.

Source

pub fn check(&self, expected: impl AsRef<str>) -> Result<(), Mismatch>

Compare the snapshot against the expected text.

The expected text is normalized the same way the snapshot was, so it can be written inline in a test as a plain string literal without worrying about trailing newlines or platform line endings. Returns Ok(()) on a match, or a Mismatch carrying the diff otherwise.

§Errors

Returns Mismatch when the normalized snapshot differs from the normalized expected text. The error’s Display renders a unified diff; Mismatch::diff exposes it programmatically.

§Examples

A matching snapshot:

use test_lang::Snapshot;

let snap = Snapshot::per_line(["a", "b"]);
assert!(snap.check("a\nb").is_ok());

A mismatch carries a diff you can print or inspect:

use test_lang::Snapshot;

let snap = Snapshot::per_line(["a", "b"]);
let err = snap.check("a\nc").unwrap_err();
assert!(err.to_string().contains("-c"));  // expected `c`, was missing
assert!(err.to_string().contains("+b"));  // `b` was produced instead

Trait Implementations§

Source§

impl Clone for Snapshot

Source§

fn clone(&self) -> Snapshot

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Snapshot

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Display for Snapshot

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Eq for Snapshot

Source§

impl Hash for Snapshot

Source§

fn hash<__H: Hasher>(&self, state: &mut __H)

Feeds this value into the given Hasher. Read more
1.3.0 · Source§

fn hash_slice<H>(data: &[Self], state: &mut H)
where H: Hasher, Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
Source§

impl PartialEq for Snapshot

Source§

fn eq(&self, other: &Snapshot) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 (const: unstable) · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl StructuralPartialEq for Snapshot

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T> ToString for T
where T: Display + ?Sized,

Source§

fn to_string(&self) -> String

Converts the given value to a String. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.