Skip to content
Permalink

Comparing changes

Choose two branches to see what’s changed or to start a new pull request. If you need to, you can also or learn more about diff comparisons.

Open a pull request

Create a new pull request by comparing changes across two branches. If you need to, you can also . Learn more about diff comparisons here.
base repository: mitsuhiko/insta
Failed to load repositories. Confirm that selected base ref is valid, then try again.
Loading
base: 1.8.0
Choose a base ref
...
head repository: mitsuhiko/insta
Failed to load repositories. Confirm that selected head ref is valid, then try again.
Loading
compare: 1.9.0
Choose a head ref
  • 14 commits
  • 19 files changed
  • 2 contributors

Commits on Sep 10, 2021

  1. Verified

    This commit was created on GitHub.com and signed with GitHub’s verified signature. The key has expired.
    Copy the full SHA
    baf6f8b View commit details

Commits on Sep 11, 2021

  1. Bump similar to 2.0.0

    mitsuhiko committed Sep 11, 2021
    Copy the full SHA
    a422a7b View commit details

Commits on Sep 12, 2021

  1. Copy the full SHA
    07d38b9 View commit details
  2. Copy the full SHA
    3baefe5 View commit details
  3. Copy the full SHA
    f4b1425 View commit details
  4. Copy the full SHA
    1a5cdec View commit details
  5. Verified

    This commit was created on GitHub.com and signed with GitHub’s verified signature. The key has expired.
    Copy the full SHA
    3dfc226 View commit details

Commits on Sep 13, 2021

  1. Fix a spelling error

    mitsuhiko committed Sep 13, 2021
    Copy the full SHA
    e976613 View commit details
  2. Move code around slightly

    mitsuhiko committed Sep 13, 2021
    Copy the full SHA
    163e66f View commit details

Commits on Oct 3, 2021

  1. Copy the full SHA
    d3195c1 View commit details

Commits on Dec 10, 2021

  1. Verified

    This commit was created on GitHub.com and signed with GitHub’s verified signature. The key has expired.
    Copy the full SHA
    2899990 View commit details

Commits on Dec 24, 2021

  1. Verified

    This commit was created on GitHub.com and signed with GitHub’s verified signature. The key has expired.
    Copy the full SHA
    e89781d View commit details
  2. 4

    Verified

    This commit was created on GitHub.com and signed with GitHub’s verified signature. The key has expired.
    Copy the full SHA
    966320e View commit details
  3. 1.9.0

    mitsuhiko committed Dec 24, 2021
    Copy the full SHA
    f5d695d View commit details
Showing with 1,071 additions and 870 deletions.
  1. +12 −0 CHANGELOG.md
  2. +2 −2 Cargo.toml
  3. +1 −1 README.md
  4. +4 −12 cargo-insta/Cargo.lock
  5. +2 −4 cargo-insta/Cargo.toml
  6. +2 −1 cargo-insta/src/cargo.rs
  7. +28 −8 cargo-insta/src/cli.rs
  8. +1 −1 cargo-insta/src/inline.rs
  9. +145 −0 src/env.rs
  10. +9 −4 src/lib.rs
  11. +204 −0 src/output.rs
  12. +6 −1 src/redaction.rs
  13. +275 −832 src/runtime.rs
  14. +1 −1 src/select_grammar.pest
  15. +1 −1 src/settings.rs
  16. +258 −1 src/snapshot.rs
  17. +76 −1 src/utils.rs
  18. +10 −0 tests/snapshots/test_redaction__map_key_redaction.snap
  19. +34 −0 tests/test_redaction.rs
12 changes: 12 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -2,6 +2,18 @@

All notable changes to insta and cargo-insta are documented here.

## 1.9.0

- `cargo-insta` now correctly handles the package (`-p`) argument
on `test` when deleting unreferenced snapshots. (#201)

## 1.8.0

- Added the ability to redact into a key. (#192)
- Insta now memorizes assertion line numbers in snapshots. While these
will quickly be old, they are often useful when reviewing snapshots
immediately after creation with `cargo-insta`. (#191)

## 1.7.2

- Fixed an issue where selectors could not start with underscore. (#189)
4 changes: 2 additions & 2 deletions Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "insta"
version = "1.7.2"
version = "1.9.0"
license = "Apache-2.0"
authors = ["Armin Ronacher <armin.ronacher@active-4.com>"]
description = "A snapshot testing library for Rust"
@@ -47,7 +47,7 @@ toml = { version = "0.5.7", optional = true }
globset = { version = "0.4.6", optional = true }
walkdir = { version = "2.3.1", optional = true }
uuid = "0.8.1"
similar = { version = "1.3.0", features = ["inline"] }
similar = { version = "2.0.0", features = ["inline"] }

[dev-dependencies]
similar-asserts = "1.1.0"
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -31,7 +31,7 @@ fn test_hello_world() {

Curious? There is a screencast that shows the entire workflow: [watch the insta
introduction screencast](https://www.youtube.com/watch?v=rCHrMqE4JOY&feature=youtu.be).
Or if you're not into videos, read the [one minute introduction](#introduction).
Or if you're not into videos, read the [5 minute introduction](https://insta.rs/docs/quickstart/).

Insta also supports inline snapshots which are stored right in your source file
instead of separate files. This is accomplished by the companion
16 changes: 4 additions & 12 deletions cargo-insta/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 2 additions & 4 deletions cargo-insta/Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "cargo-insta"
version = "1.7.2"
version = "1.9.0"
license = "Apache-2.0"
authors = ["Armin Ronacher <armin.ronacher@active-4.com>"]
description = "A review tool for the insta snapshot testing library for Rust"
@@ -12,10 +12,8 @@ edition = "2018"
readme = "README.md"

[dependencies]
insta = { version = "1.7.2", path = "..", features = ["redactions"] }
insta = { version = "1.9.0", path = "..", features = ["redactions"] }
console = "0.14.0"
clap = { version = "2.33.3", default-features = false }
difference = "2.0.0"
structopt = "0.3.20"
serde = { version = "1.0.117", features = ["derive"] }
serde_json = "1.0.59"
3 changes: 2 additions & 1 deletion cargo-insta/src/cargo.rs
Original file line number Diff line number Diff line change
@@ -7,7 +7,8 @@ use std::process;

use ignore::overrides::OverrideBuilder;
use ignore::{DirEntry, WalkBuilder};
use insta::{PendingInlineSnapshot, Snapshot};
use insta::Snapshot;
use insta::_cargo_insta_support::PendingInlineSnapshot;
use serde::Deserialize;

use crate::inline::FilePatcher;
36 changes: 28 additions & 8 deletions cargo-insta/src/cli.rs
Original file line number Diff line number Diff line change
@@ -3,12 +3,13 @@ use std::collections::HashSet;
use std::error::Error;
use std::ffi::OsStr;
use std::path::{Path, PathBuf};
use std::process;
use std::{env, fs};
use std::{io, process};

use console::{set_colors_enabled, style, Key, Term};
use ignore::{Walk, WalkBuilder};
use insta::{print_snapshot_diff, Snapshot};
use insta::Snapshot;
use insta::_cargo_insta_support::print_snapshot_diff;
use serde::Serialize;
use structopt::clap::AppSettings;
use structopt::StructOpt;
@@ -415,11 +416,19 @@ fn process_snapshots(cmd: ProcessCommand, op: Option<Operation>) -> Result<(), B
Ok(())
}

fn make_deletion_walker(loc: &LocationInfo) -> Walk {
fn make_deletion_walker(loc: &LocationInfo, package: Option<&str>) -> Walk {
let roots: HashSet<_> = match loc.packages {
Some(ref packages) => packages
.iter()
.filter_map(|x| x.manifest_path().parent().unwrap().canonicalize().ok())
.filter_map(|x| {
// filter out packages we did not ask for.
if let Some(only_package) = package {
if x.name() != only_package {
return None;
}
}
x.manifest_path().parent().unwrap().canonicalize().ok()
})
.collect(),
None => {
let mut hs = HashSet::new();
@@ -582,15 +591,26 @@ fn test_run(mut cmd: TestCommand, color: &str) -> Result<(), Box<dyn Error>> {
// delete unreferenced snapshots if we were instructed to do so
if let Some(ref path) = snapshot_ref_file {
let mut files = HashSet::new();
for line in fs::read_to_string(path).unwrap().lines() {
if let Ok(path) = fs::canonicalize(line) {
files.insert(path);
match fs::read_to_string(path) {
Ok(s) => {
for line in s.lines() {
if let Ok(path) = fs::canonicalize(line) {
files.insert(path);
}
}
}
Err(err) => {
// if the file was not created, no test referenced
// snapshots.
if err.kind() != io::ErrorKind::NotFound {
return Err(err.into());
}
}
}

if let Ok(loc) = handle_target_args(&cmd.target_args) {
let mut deleted_any = false;
for entry in make_deletion_walker(&loc) {
for entry in make_deletion_walker(&loc, cmd.package.as_deref()) {
let rel_path = match entry {
Ok(ref entry) => entry.path(),
_ => continue,
2 changes: 1 addition & 1 deletion cargo-insta/src/inline.rs
Original file line number Diff line number Diff line change
@@ -4,7 +4,7 @@ use std::fs;
use std::io::Write;
use std::path::{Path, PathBuf};

use insta::SnapshotContents;
use insta::_cargo_insta_support::SnapshotContents;
use proc_macro2::TokenTree;
use syn;
use syn::spanned::Spanned;
145 changes: 145 additions & 0 deletions src/env.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,145 @@
use std::collections::BTreeMap;
use std::io::Write;
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex};
use std::{env, fs};

use lazy_static::lazy_static;
use serde::Deserialize;

use crate::utils::is_ci;

lazy_static! {
static ref WORKSPACES: Mutex<BTreeMap<String, Arc<PathBuf>>> = Mutex::new(BTreeMap::new());
}

/// How snapshots are supposed to be updated
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum SnapshotUpdate {
/// Snapshots are updated in-place
InPlace,
/// Snapshots are placed in a new file with a .new suffix
NewFile,
/// Snapshots are not updated at all.
NoUpdate,
}

/// Controls how information is supposed to be displayed.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum OutputBehavior {
/// Diff only
Diff,
/// Short summary
Summary,
/// The most minimal output
Minimal,
/// No output at all
Nothing,
}

/// Is insta told to force update snapshots?
pub fn force_update_snapshots() -> bool {
match env::var("INSTA_FORCE_UPDATE_SNAPSHOTS").ok().as_deref() {
None | Some("") | Some("0") => false,
Some("1") => true,
_ => panic!("invalid value for INSTA_FORCE_UPDATE_SNAPSHOTS"),
}
}

/// Is insta instructed to fail in tests?
pub fn force_pass() -> bool {
match env::var("INSTA_FORCE_PASS").ok().as_deref() {
None | Some("") | Some("0") => false,
Some("1") => true,
_ => panic!("invalid value for INSTA_FORCE_PASS"),
}
}

/// Returns the intended output behavior for insta.
pub fn get_output_behavior() -> OutputBehavior {
match env::var("INSTA_OUTPUT").ok().as_deref() {
None | Some("") | Some("diff") => OutputBehavior::Diff,
Some("summary") => OutputBehavior::Summary,
Some("minimal") => OutputBehavior::Minimal,
Some("none") => OutputBehavior::Nothing,
_ => panic!("invalid value for INSTA_OUTPUT"),
}
}

/// Returns the intended snapshot update behavior.
pub fn get_snapshot_update_behavior(unseen: bool) -> SnapshotUpdate {
match env::var("INSTA_UPDATE").ok().as_deref() {
None | Some("") | Some("auto") => {
if is_ci() {
SnapshotUpdate::NoUpdate
} else {
SnapshotUpdate::NewFile
}
}
Some("always") | Some("1") => SnapshotUpdate::InPlace,
Some("new") => SnapshotUpdate::NewFile,
Some("unseen") => {
if unseen {
SnapshotUpdate::NewFile
} else {
SnapshotUpdate::InPlace
}
}
Some("no") => SnapshotUpdate::NoUpdate,
_ => panic!("invalid value for INSTA_UPDATE"),
}
}

/// Returns the cargo workspace for a manifest
pub fn get_cargo_workspace(manifest_dir: &str) -> Arc<PathBuf> {
// we really do not care about poisoning here.
let mut workspaces = WORKSPACES.lock().unwrap_or_else(|x| x.into_inner());
if let Some(rv) = workspaces.get(manifest_dir) {
rv.clone()
} else {
// If INSTA_WORKSPACE_ROOT environment variable is set, use the value
// as-is. This is useful for those users where the compiled in
// CARGO_MANIFEST_DIR points to some transient location. This can easily
// happen if the user builds the test in one directory but then tries to
// run it in another: even if sources are available in the new
// directory, in the past we would always go with the compiled-in value.
// The compiled-in directory may not even exist anymore.
let path = if let Ok(workspace_root) = std::env::var("INSTA_WORKSPACE_ROOT") {
Arc::new(PathBuf::from(workspace_root))
} else {
#[derive(Deserialize)]
struct Manifest {
workspace_root: PathBuf,
}
let output = std::process::Command::new(
env::var("CARGO")
.ok()
.unwrap_or_else(|| "cargo".to_string()),
)
.arg("metadata")
.arg("--format-version=1")
.arg("--no-deps")
.current_dir(manifest_dir)
.output()
.unwrap();
let manifest: Manifest = serde_json::from_slice(&output.stdout).unwrap();
Arc::new(manifest.workspace_root)
};
workspaces.insert(manifest_dir.to_string(), path.clone());
path
}
}

/// Memoizes a snapshot file in the reference file.
pub fn memoize_snapshot_file(snapshot_file: &Path) {
if let Ok(path) = env::var("INSTA_SNAPSHOT_REFERENCES_FILE") {
let mut f = fs::OpenOptions::new()
.write(true)
.append(true)
.create(true)
.open(path)
.unwrap();
f.write_all(format!("{}\n", snapshot_file.display()).as_bytes())
.unwrap();
}
}
13 changes: 9 additions & 4 deletions src/lib.rs
Original file line number Diff line number Diff line change
@@ -150,6 +150,8 @@
#[macro_use]
mod macros;
mod content;
mod env;
mod output;
mod runtime;
mod serialization;
mod settings;
@@ -185,9 +187,11 @@ pub mod internals {

// exported for cargo-insta only
#[doc(hidden)]
pub use crate::{
runtime::print_snapshot_diff, snapshot::PendingInlineSnapshot, snapshot::SnapshotContents,
};
pub mod _cargo_insta_support {
pub use crate::{
output::print_snapshot_diff, snapshot::PendingInlineSnapshot, snapshot::SnapshotContents,
};
}

// useful for redactions
#[cfg(feature = "redactions")]
@@ -197,7 +201,8 @@ pub use crate::redaction::dynamic_redaction;
#[doc(hidden)]
pub mod _macro_support {
pub use crate::content::Content;
pub use crate::runtime::{assert_snapshot, get_cargo_workspace, AutoName, ReferenceValue};
pub use crate::env::get_cargo_workspace;
pub use crate::runtime::{assert_snapshot, AutoName, ReferenceValue};
pub use crate::serialization::{serialize_value, SerializationFormat, SnapshotLocation};

#[cfg(feature = "glob")]
Loading