Skip to content

Commit

Permalink
Fix snapshot & module name extraction (#483)
Browse files Browse the repository at this point in the history
  • Loading branch information
max-sixty committed May 15, 2024
1 parent 7e9998d commit d4fc16f
Showing 1 changed file with 49 additions and 22 deletions.
71 changes: 49 additions & 22 deletions insta/src/snapshot.rs
Original file line number Diff line number Diff line change
Expand Up @@ -323,31 +323,11 @@ impl Snapshot {
buf.push_str(&line);
}

let module_name = p
.file_name()
.unwrap()
.to_str()
.unwrap_or("")
.split("__")
.next()
.unwrap_or("<unknown>")
.to_string();

let snapshot_name = p
.file_name()
.unwrap()
.to_str()
.unwrap_or("")
.split('.')
.next()
.unwrap_or("")
.splitn(2, "__")
.nth(1)
.map(|x| x.to_string());
let (snapshot_name, module_name) = names_of_path(p);

Ok(Snapshot::from_components(
module_name,
snapshot_name,
Some(snapshot_name),
metadata,
buf.into(),
))
Expand Down Expand Up @@ -630,6 +610,53 @@ fn normalize_inline_snapshot(snapshot: &str) -> String {
.join("\n")
}

/// Extracts the module and snapshot name from a snapshot path
fn names_of_path(path: &Path) -> (String, String) {
// The final part of the snapshot file name is the test name; the
// initial parts are the module name
let parts: Vec<&str> = path
.file_stem()
.unwrap()
.to_str()
.unwrap_or("")
.rsplitn(2, "__")
.collect();

match parts.as_slice() {
[snapshot_name, module_name] => (snapshot_name.to_string(), module_name.to_string()),
[snapshot_name] => (snapshot_name.to_string(), String::new()),
_ => (String::new(), "<unknown>".to_string()),
}
}

#[test]
fn test_names_of_path() {
assert_debug_snapshot!(
names_of_path(Path::new("/src/snapshots/insta_tests__tests__name_foo.snap")), @r###"
(
"name_foo",
"insta_tests__tests",
)
"###
);
assert_debug_snapshot!(
names_of_path(Path::new("/src/snapshots/name_foo.snap")), @r###"
(
"name_foo",
"",
)
"###
);
assert_debug_snapshot!(
names_of_path(Path::new("foo/src/snapshots/go1.20.5.snap")), @r###"
(
"go1.20.5",
"",
)
"###
);
}

/// Helper function that returns the real inline snapshot value from a given
/// frozen value string. If the string starts with the '⋮' character
/// (optionally prefixed by whitespace) the alternative serialization format
Expand Down

0 comments on commit d4fc16f

Please sign in to comment.