gobbler/categorize/match/match_test.go

107 lines
2.7 KiB
Go

package match
import (
"fmt"
"testing"
"github.com/stretchr/testify/assert"
)
func TestFindClosestString(t *testing.T) {
tt := []struct {
candidate string
index []string
expectedMatch string
}{
{
candidate: "hello",
index: []string{"goodbye", "howdy", "hoolo"},
expectedMatch: "hoolo",
},
{
candidate: "hello",
index: []string{"goodbye", "hello world"},
expectedMatch: "hello world",
},
{
candidate: "hello",
index: []string{"goodbye", "hello there!"},
// While this looks wrong, it demosntrates why this function on its own isn't always sufficient
expectedMatch: "goodbye",
},
{
candidate: "kitten",
index: []string{"sitting", "kitty", "dog"},
expectedMatch: "kitty",
},
}
for _, test := range tt {
testName := fmt.Sprintf("%s to %s", test.candidate, test.expectedMatch)
t.Run(testName, func(t *testing.T) {
match := FindClosestString(test.candidate, test.index)
assert.Equal(t, test.expectedMatch, match)
})
}
}
func TestFindBestMatch(t *testing.T) {
tt := []struct {
candidate string
index []string
expectedMatch string
expectedError error
}{
{
candidate: "hello",
index: []string{"goodbye", "hello there!"},
expectedMatch: "hello there!",
expectedError: nil,
},
{
candidate: "hello",
index: []string{"goodbye", "hello there!", "hello world"},
expectedMatch: "hello world",
expectedError: nil,
},
{
candidate: "oh no this won't match anything",
index: []string{"aaaaaaaaaaaaaaaaaa", "this is an awful situation!"},
expectedMatch: "",
expectedError: ErrNoMatches,
},
{
// This has the common prefix of "s" but we don't actually really care about a prefix like that
candidate: "super-weird",
index: []string{"something-odd", "nothing"},
expectedMatch: "",
expectedError: ErrNoMatches,
},
{
// two have a common prefix of "the-a" but really there should be no match
candidate: "the-amazing-gymnist",
index: []string{"the-athlete", "sitting-at-home", "the-show-about-nothing"},
expectedMatch: "",
expectedError: ErrNoMatches,
},
}
for _, test := range tt {
testName := fmt.Sprintf("%s to %s", test.candidate, test.expectedMatch)
if test.expectedError != nil {
testName = fmt.Sprintf("%s will not match anything in %v", test.candidate, test.index)
}
t.Run(testName, func(t *testing.T) {
match, err := FindBestMatch(test.candidate, test.index)
if test.expectedError != nil {
assert.ErrorIs(t, err, ErrNoMatches, fmt.Sprintf("got match %q and error %q", match, err))
} else {
assert.Nil(t, err)
assert.Equal(t, test.expectedMatch, match)
}
})
}
}