Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix snapshot & module name extraction #483

Merged
merged 3 commits into from
May 15, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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