Skip to content

Commit

Permalink
Improved handling of control characters in inline snapshots
Browse files Browse the repository at this point in the history
Fixes at least some of #712 (not confident it fixes all of it, but wanted to get it out quickly)
  • Loading branch information
max-sixty committed Jan 23, 2025
1 parent f778d29 commit 84cb990
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 2 deletions.
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,10 @@

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

## 1.42.1

- Improved handling of control characters in inline snapshots. #713

## 1.42.0

- Text snapshots no longer contain `snapshot_type: text` in their metadata. For
Expand Down
13 changes: 11 additions & 2 deletions insta/src/snapshot.rs
Original file line number Diff line number Diff line change
Expand Up @@ -689,8 +689,11 @@ impl TextSnapshotContents {
let contents = self.normalize();
let mut out = String::new();

// We don't technically need to escape on newlines, but it reduces diffs
let is_escape = contents.contains(['\\', '"', '\n']);
// We don't technically need to escape on newlines, but it reduces
// diffs (and is included in `is_control`).
let is_escape = contents
.chars()
.any(|c| matches!(c, '"' | '\\') || c.is_control());
// Escape the string if needed, with `r#`, using the required number of `#`s
let delimiter = if is_escape {
out.push('r');
Expand Down Expand Up @@ -796,6 +799,12 @@ fn test_required_hashes() {
assert_snapshot!(required_hashes("####"), @"0");
assert_snapshot!(required_hashes(r###"\"\"##\"\""###), @"3");
assert_snapshot!(required_hashes(r###"r"#"Raw string"#""###), @"2");
assert_snapshot!(required_hashes("foo\rbar"), @"0");
assert_snapshot!(required_hashes("foo\tbar"), @"0");
assert_snapshot!(required_hashes("foo\0bar"), @"0");
assert_snapshot!(required_hashes("foo\x1bbar"), @"0"); // ESC character
assert_snapshot!(required_hashes("foo\u{1234}bar"), @"0");
assert_snapshot!(required_hashes("foo\nbar"), @"0");
}

fn count_leading_spaces(value: &str) -> usize {
Expand Down

0 comments on commit 84cb990

Please sign in to comment.