Skip to content

Commit

Permalink
Merge pull request #252 from epage/dup
Browse files Browse the repository at this point in the history
fix(snap): Allow multiple values map to a variable
  • Loading branch information
epage authored Feb 14, 2024
2 parents 6736b8b + 5fa9846 commit 7d33f87
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 5 deletions.
18 changes: 14 additions & 4 deletions crates/snapbox/src/substitutions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ use std::borrow::Cow;
/// - `[..]`: match multiple characters within a line
#[derive(Default, Clone, Debug, PartialEq, Eq)]
pub struct Substitutions {
vars: std::collections::BTreeMap<&'static str, Cow<'static, str>>,
vars: std::collections::BTreeMap<&'static str, std::collections::BTreeSet<Cow<'static, str>>>,
unused: std::collections::BTreeSet<&'static str>,
}

Expand Down Expand Up @@ -43,7 +43,9 @@ impl Substitutions {
self.unused.insert(key);
} else {
self.vars
.insert(key, crate::utils::normalize_text(value.as_ref()).into());
.entry(key)
.or_default()
.insert(crate::utils::normalize_text(value.as_ref()).into());
}
Ok(())
}
Expand All @@ -61,6 +63,12 @@ impl Substitutions {
Ok(())
}

pub fn remove(&mut self, key: &'static str) -> Result<(), crate::Error> {
let key = validate_key(key)?;
self.vars.remove(key);
Ok(())
}

/// Apply match pattern to `input`
///
/// If `pattern` matches `input`, then `pattern` is returned.
Expand All @@ -79,8 +87,10 @@ impl Substitutions {
fn substitute<'v>(&self, value: &'v str) -> Cow<'v, str> {
let mut value = Cow::Borrowed(value);
for (var, replace) in self.vars.iter() {
debug_assert!(!replace.is_empty());
value = Cow::Owned(value.replace(replace.as_ref(), var));
for replace in replace {
debug_assert!(!replace.is_empty());
value = Cow::Owned(value.replace(replace.as_ref(), var));
}
}
value
}
Expand Down
10 changes: 9 additions & 1 deletion src/cases.rs
Original file line number Diff line number Diff line change
Expand Up @@ -143,7 +143,7 @@ impl TestCases {

/// Batch add variables for normalizing output
///
/// See `insert_var`.
/// See [`TestCases::insert_var`].
pub fn extend_vars(
&self,
vars: impl IntoIterator<Item = (&'static str, impl Into<Cow<'static, str>>)>,
Expand All @@ -152,6 +152,14 @@ impl TestCases {
Ok(self)
}

/// Remove an existing var values
///
/// See [`TestCases::insert_var`].
pub fn clear_var(&self, var: &'static str) -> Result<&Self, crate::Error> {
self.substitutions.borrow_mut().remove(var)?;
Ok(self)
}

/// Run tests
///
/// This will happen on `drop` if not done explicitly
Expand Down

0 comments on commit 7d33f87

Please sign in to comment.