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

Add some unit tests for find_best_match_for_name #54119

Merged
merged 1 commit into from
Sep 14, 2018
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 40 additions & 2 deletions src/libsyntax/util/lev_distance.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
use std::cmp;
use symbol::Symbol;

/// To find the Levenshtein distance between two strings
/// Find the Levenshtein distance between two strings
pub fn lev_distance(a: &str, b: &str) -> usize {
// cases which don't require further computation
if a.is_empty() {
Expand Down Expand Up @@ -41,10 +41,12 @@ pub fn lev_distance(a: &str, b: &str) -> usize {
} dcol[t_last + 1]
}

/// To find the best match for a given string from an iterator of names
/// Find the best match for a given word in the given iterator
///
/// As a loose rule to avoid the obviously incorrect suggestions, it takes
/// an optional limit for the maximum allowable edit distance, which defaults
/// to one-third of the given word.
///
/// Besides Levenshtein, we use case insensitive comparison to improve accuracy on an edge case with
/// a lower(upper)case letters mismatch.
pub fn find_best_match_for_name<'a, T>(iter_names: T,
Expand Down Expand Up @@ -105,3 +107,39 @@ fn test_lev_distance() {
assert_eq!(lev_distance(b, c), 1);
assert_eq!(lev_distance(c, b), 1);
}

#[test]
fn test_find_best_match_for_name() {
use with_globals;
with_globals(|| {
let input = vec![Symbol::intern("aaab"), Symbol::intern("aaabc")];
assert_eq!(
find_best_match_for_name(input.iter(), "aaaa", None),
Some(Symbol::intern("aaab"))
);

assert_eq!(
find_best_match_for_name(input.iter(), "1111111111", None),
None
);

let input = vec![Symbol::intern("aAAA")];
assert_eq!(
find_best_match_for_name(input.iter(), "AAAA", None),
Some(Symbol::intern("aAAA"))
);

let input = vec![Symbol::intern("AAAA")];
// Returns None because `lev_distance > max_dist / 3`
assert_eq!(
find_best_match_for_name(input.iter(), "aaaa", None),
None
);

let input = vec![Symbol::intern("AAAA")];
assert_eq!(
find_best_match_for_name(input.iter(), "aaaa", Some(4)),
Some(Symbol::intern("AAAA"))
);
})
}