Skip to content
Myr

algo_test.go

This file

Path

src/algo/algo_test.go

315 lines · 12.8 KiB · Go

Last changed by

Add fast path for two-character patterns in FuzzyMatchV2Junegunn Choibefore adoptionf779e6a

History of this file

Take it

1package algo23import (4	"math"5	"sort"6	"strings"7	"testing"89	"github.com/junegunn/fzf/src/util"10)1112func init() {13	Init("default")14}1516func assertMatch(t *testing.T, fun Algo, caseSensitive, forward bool, input, pattern string, sidx int, eidx int, score int) {17	assertMatch2(t, fun, caseSensitive, false, forward, input, pattern, sidx, eidx, score)18}1920func assertMatch2(t *testing.T, fun Algo, caseSensitive, normalize, forward bool, input, pattern string, sidx int, eidx int, score int) {21	if !caseSensitive {22		pattern = strings.ToLower(pattern)23	}24	chars := util.ToChars([]byte(input))25	res, pos := fun(caseSensitive, normalize, forward, &chars, []rune(pattern), true, nil)26	var start, end int27	if pos == nil || len(*pos) == 0 {28		start = res.Start29		end = res.End30	} else {31		sort.Ints(*pos)32		start = (*pos)[0]33		end = (*pos)[len(*pos)-1] + 134	}35	if start != sidx {36		t.Errorf("Invalid start index: %d (expected: %d, %s / %s)", start, sidx, input, pattern)37	}38	if end != eidx {39		t.Errorf("Invalid end index: %d (expected: %d, %s / %s)", end, eidx, input, pattern)40	}41	if res.Score != score {42		t.Errorf("Invalid score: %d (expected: %d, %s / %s)", res.Score, score, input, pattern)43	}44}4546func TestFuzzyMatch(t *testing.T) {47	for _, fn := range []Algo{FuzzyMatchV1, FuzzyMatchV2} {48		for _, forward := range []bool{true, false} {49			assertMatch(t, fn, false, forward, "fooBarbaz1", "oBZ", 2, 9,50				scoreMatch*3+bonusCamel123+scoreGapStart+scoreGapExtension*3)51			assertMatch(t, fn, false, forward, "foo bar baz", "fbb", 0, 9,52				scoreMatch*3+int(bonusBoundaryWhite)*bonusFirstCharMultiplier+53					int(bonusBoundaryWhite)*2+2*scoreGapStart+4*scoreGapExtension)54			assertMatch(t, fn, false, forward, "/AutomatorDocument.icns", "rdoc", 9, 13,55				scoreMatch*4+bonusCamel123+bonusConsecutive*2)56			assertMatch(t, fn, false, forward, "/man1/zshcompctl.1", "zshc", 6, 10,57				scoreMatch*4+int(bonusBoundaryDelimiter)*bonusFirstCharMultiplier+int(bonusBoundaryDelimiter)*3)58			assertMatch(t, fn, false, forward, "/.oh-my-zsh/cache", "zshc", 8, 13,59				scoreMatch*4+bonusBoundary*bonusFirstCharMultiplier+bonusBoundary*2+scoreGapStart+int(bonusBoundaryDelimiter))60			// Non-word character at start of input is treated as a strong boundary61			assertMatch(t, fn, false, forward, ".vimrc", ".vimrc", 0, 6,62				scoreMatch*6+int(bonusBoundaryWhite)*(bonusFirstCharMultiplier+5))63			// Non-word character right after a delimiter inherits the delimiter boundary64			assertMatch(t, fn, false, forward, "/.vimrc", ".vimrc", 1, 7,65				scoreMatch*6+int(bonusBoundaryDelimiter)*(bonusFirstCharMultiplier+5))66			// Non-word character in the middle of a word stays at bonusNonWord67			assertMatch(t, fn, false, forward, "a.vimrc", ".vimrc", 1, 7,68				scoreMatch*6+bonusBoundary*(bonusFirstCharMultiplier+5))69			assertMatch(t, fn, false, forward, "ab0123 456", "12356", 3, 10,70				scoreMatch*5+bonusConsecutive*3+scoreGapStart+scoreGapExtension)71			assertMatch(t, fn, false, forward, "abc123 456", "12356", 3, 10,72				scoreMatch*5+bonusCamel123*bonusFirstCharMultiplier+bonusCamel123*2+bonusConsecutive+scoreGapStart+scoreGapExtension)73			assertMatch(t, fn, false, forward, "foo/bar/baz", "fbb", 0, 9,74				scoreMatch*3+int(bonusBoundaryWhite)*bonusFirstCharMultiplier+75					int(bonusBoundaryDelimiter)*2+2*scoreGapStart+4*scoreGapExtension)76			assertMatch(t, fn, false, forward, "fooBarBaz", "fbb", 0, 7,77				scoreMatch*3+int(bonusBoundaryWhite)*bonusFirstCharMultiplier+78					bonusCamel123*2+2*scoreGapStart+2*scoreGapExtension)79			assertMatch(t, fn, false, forward, "foo barbaz", "fbb", 0, 8,80				scoreMatch*3+int(bonusBoundaryWhite)*bonusFirstCharMultiplier+int(bonusBoundaryWhite)+81					scoreGapStart*2+scoreGapExtension*3)82			assertMatch(t, fn, false, forward, "fooBar Baz", "foob", 0, 4,83				scoreMatch*4+int(bonusBoundaryWhite)*bonusFirstCharMultiplier+int(bonusBoundaryWhite)*3)84			assertMatch(t, fn, false, forward, "xFoo-Bar Baz", "foo-b", 1, 6,85				scoreMatch*5+bonusCamel123*bonusFirstCharMultiplier+bonusCamel123*2+86					bonusNonWord+bonusBoundary)8788			assertMatch(t, fn, true, forward, "fooBarbaz", "oBz", 2, 9,89				scoreMatch*3+bonusCamel123+scoreGapStart+scoreGapExtension*3)90			assertMatch(t, fn, true, forward, "Foo/Bar/Baz", "FBB", 0, 9,91				scoreMatch*3+int(bonusBoundaryWhite)*bonusFirstCharMultiplier+int(bonusBoundaryDelimiter)*2+92					scoreGapStart*2+scoreGapExtension*4)93			assertMatch(t, fn, true, forward, "FooBarBaz", "FBB", 0, 7,94				scoreMatch*3+int(bonusBoundaryWhite)*bonusFirstCharMultiplier+bonusCamel123*2+95					scoreGapStart*2+scoreGapExtension*2)96			assertMatch(t, fn, true, forward, "FooBar Baz", "FooB", 0, 4,97				scoreMatch*4+int(bonusBoundaryWhite)*bonusFirstCharMultiplier+int(bonusBoundaryWhite)*2+98					max(bonusCamel123, int(bonusBoundaryWhite)))99100			// Consecutive bonus updated101			assertMatch(t, fn, true, forward, "foo-bar", "o-ba", 2, 6,102				scoreMatch*4+bonusBoundary*3)103104			// Non-match105			assertMatch(t, fn, true, forward, "fooBarbaz", "oBZ", -1, -1, 0)106			assertMatch(t, fn, true, forward, "Foo Bar Baz", "fbb", -1, -1, 0)107			assertMatch(t, fn, true, forward, "fooBarbaz", "fooBarbazz", -1, -1, 0)108		}109	}110}111112func TestFuzzyMatchBackward(t *testing.T) {113	assertMatch(t, FuzzyMatchV1, false, true, "foobar fb", "fb", 0, 4,114		scoreMatch*2+int(bonusBoundaryWhite)*bonusFirstCharMultiplier+115			scoreGapStart+scoreGapExtension)116	assertMatch(t, FuzzyMatchV1, false, false, "foobar fb", "fb", 7, 9,117		scoreMatch*2+int(bonusBoundaryWhite)*bonusFirstCharMultiplier+int(bonusBoundaryWhite))118}119120func TestExactMatchNaive(t *testing.T) {121	for _, dir := range []bool{true, false} {122		assertMatch(t, ExactMatchNaive, true, dir, "fooBarbaz", "oBA", -1, -1, 0)123		assertMatch(t, ExactMatchNaive, true, dir, "fooBarbaz", "fooBarbazz", -1, -1, 0)124125		assertMatch(t, ExactMatchNaive, false, dir, "fooBarbaz", "oBA", 2, 5,126			scoreMatch*3+bonusCamel123+bonusConsecutive)127		assertMatch(t, ExactMatchNaive, false, dir, "/AutomatorDocument.icns", "rdoc", 9, 13,128			scoreMatch*4+bonusCamel123+bonusConsecutive*2)129		assertMatch(t, ExactMatchNaive, false, dir, "/man1/zshcompctl.1", "zshc", 6, 10,130			scoreMatch*4+int(bonusBoundaryDelimiter)*(bonusFirstCharMultiplier+3))131		assertMatch(t, ExactMatchNaive, false, dir, "/.oh-my-zsh/cache", "zsh/c", 8, 13,132			scoreMatch*5+bonusBoundary*(bonusFirstCharMultiplier+3)+int(bonusBoundaryDelimiter))133	}134}135136func TestExactMatchNaiveBackward(t *testing.T) {137	assertMatch(t, ExactMatchNaive, false, true, "foobar foob", "oo", 1, 3,138		scoreMatch*2+bonusConsecutive)139	assertMatch(t, ExactMatchNaive, false, false, "foobar foob", "oo", 8, 10,140		scoreMatch*2+bonusConsecutive)141}142143func TestPrefixMatch(t *testing.T) {144	score := scoreMatch*3 + int(bonusBoundaryWhite)*bonusFirstCharMultiplier + int(bonusBoundaryWhite)*2145146	for _, dir := range []bool{true, false} {147		assertMatch(t, PrefixMatch, true, dir, "fooBarbaz", "Foo", -1, -1, 0)148		assertMatch(t, PrefixMatch, false, dir, "fooBarBaz", "baz", -1, -1, 0)149		assertMatch(t, PrefixMatch, false, dir, "fooBarbaz", "Foo", 0, 3, score)150		assertMatch(t, PrefixMatch, false, dir, "foOBarBaZ", "foo", 0, 3, score)151		assertMatch(t, PrefixMatch, false, dir, "f-oBarbaz", "f-o", 0, 3, score)152153		assertMatch(t, PrefixMatch, false, dir, " fooBar", "foo", 1, 4, score)154		assertMatch(t, PrefixMatch, false, dir, " fooBar", " fo", 0, 3, score)155		assertMatch(t, PrefixMatch, false, dir, "     fo", "foo", -1, -1, 0)156	}157}158159func TestSuffixMatch(t *testing.T) {160	for _, dir := range []bool{true, false} {161		assertMatch(t, SuffixMatch, true, dir, "fooBarbaz", "Baz", -1, -1, 0)162		assertMatch(t, SuffixMatch, false, dir, "fooBarbaz", "Foo", -1, -1, 0)163164		assertMatch(t, SuffixMatch, false, dir, "fooBarbaz", "baz", 6, 9,165			scoreMatch*3+bonusConsecutive*2)166		assertMatch(t, SuffixMatch, false, dir, "fooBarBaZ", "baz", 6, 9,167			(scoreMatch+bonusCamel123)*3+bonusCamel123*(bonusFirstCharMultiplier-1))168169		// Strip trailing white space from the string170		assertMatch(t, SuffixMatch, false, dir, "fooBarbaz ", "baz", 6, 9,171			scoreMatch*3+bonusConsecutive*2)172173		// Only when the pattern doesn't end with a space174		assertMatch(t, SuffixMatch, false, dir, "fooBarbaz ", "baz ", 6, 10,175			scoreMatch*4+bonusConsecutive*2+int(bonusBoundaryWhite))176	}177}178179func TestEmptyPattern(t *testing.T) {180	for _, dir := range []bool{true, false} {181		assertMatch(t, FuzzyMatchV1, true, dir, "foobar", "", 0, 0, 0)182		assertMatch(t, FuzzyMatchV2, true, dir, "foobar", "", 0, 0, 0)183		assertMatch(t, ExactMatchNaive, true, dir, "foobar", "", 0, 0, 0)184		assertMatch(t, PrefixMatch, true, dir, "foobar", "", 0, 0, 0)185		assertMatch(t, SuffixMatch, true, dir, "foobar", "", 6, 6, 0)186	}187}188189func TestNormalize(t *testing.T) {190	caseSensitive := false191	normalize := true192	forward := true193	test := func(input, pattern string, sidx, eidx, score int, funs ...Algo) {194		for _, fun := range funs {195			assertMatch2(t, fun, caseSensitive, normalize, forward,196				input, pattern, sidx, eidx, score)197		}198	}199	test("Só Danço Samba", "So", 0, 2, 62, FuzzyMatchV1, FuzzyMatchV2, PrefixMatch, ExactMatchNaive)200	test("Só Danço Samba", "sodc", 0, 7, 97, FuzzyMatchV1, FuzzyMatchV2)201	test("Danço", "danco", 0, 5, 140, FuzzyMatchV1, FuzzyMatchV2, PrefixMatch, SuffixMatch, ExactMatchNaive, EqualMatch)202}203204func TestLongString(t *testing.T) {205	bytes := make([]byte, math.MaxUint16*2)206	for i := range bytes {207		bytes[i] = 'x'208	}209	bytes[math.MaxUint16] = 'z'210	assertMatch(t, FuzzyMatchV2, true, true, string(bytes), "zx", math.MaxUint16, math.MaxUint16+2, scoreMatch*2+bonusConsecutive)211}212213func TestLongStringWithNormalize(t *testing.T) {214	bytes := make([]byte, 30000)215	for i := range bytes {216		bytes[i] = 'x'217	}218	unicodeString := string(bytes) + " Minímal example"219	assertMatch2(t, FuzzyMatchV1, false, true, false, unicodeString, "minim", 30001, 30006, 140)220}221222func TestResultPositionsWithReusedSlab(t *testing.T) {223	// Backtrace positions in equal-score ties must not depend on data224	// a previous match left in the slab225	pattern := []rune("co/")226	target := util.ToChars([]byte("core_color/view/server.txt"))227	_, freshPos := FuzzyMatchV2(false, false, true, &target, pattern, true, util.MakeSlab(100*1024, 2048))228229	slab := util.MakeSlab(100*1024, 2048)230	dirty := util.ToChars([]byte("completion/keybinding/client/handler/writer_index.txt"))231	FuzzyMatchV2(false, false, true, &dirty, pattern, true, slab)232	_, reusedPos := FuzzyMatchV2(false, false, true, &target, pattern, true, slab)233234	if len(*freshPos) != len(*reusedPos) {235		t.Fatalf("position count mismatch: %v vs %v", *freshPos, *reusedPos)236	}237	for i := range *freshPos {238		if (*freshPos)[i] != (*reusedPos)[i] {239			t.Errorf("positions differ with reused slab: %v vs %v", *freshPos, *reusedPos)240			break241		}242	}243}244245// TestFuzzyMatchV2TwoEquivalence verifies that the two-character fast path246// produces the same Result and positions as the general algorithm across247// case sensitivity, direction, and withPos, using a reused slab to surface248// any stale-data reads in the backtrace.249func TestFuzzyMatchV2TwoEquivalence(t *testing.T) {250	words := []string{"src", "main", "core", "config", "parser", "render", "server",251		"client", "index", "handler", "util", "list", "cache", "reader"}252	exts := []string{".go", ".rb", ".py", ".md", ".c", ".txt"}253	// Deterministic corpus (LCG), plus adversarial short/repeated items254	corpus := []util.Chars{}255	seed := uint32(12345)256	next := func(n int) int { seed = seed*1664525 + 1013904223; return int(seed>>8) % n }257	for i := 0; i < 4000; i++ {258		depth := 2 + next(4)259		s := ""260		for d := 0; d < depth; d++ {261			if d > 0 {262				s += "/"263			}264			s += words[next(len(words))]265			if next(5) == 0 {266				s += "_" + words[next(len(words))]267			}268		}269		s += exts[next(len(exts))]270		corpus = append(corpus, util.ToChars([]byte(s)))271	}272	for _, s := range []string{"", "a", "ab", "aa", "aXb", "a/b", "//", "..", "abcabc",273		"AaBb", "x.y.z", "a_b_c", "CoreCore", "  co"} {274		corpus = append(corpus, util.ToChars([]byte(s)))275	}276277	pats := []string{"co", "ab", "aa", "//", "..", "sr", "a/", "_c", "oo", "Ab",278		"z.", "b.", "1a", "ll", "re", "er", "Co"}279	slab := util.MakeSlab(100*1024, 2048)280	for _, cs := range []bool{false, true} {281		for _, fwd := range []bool{true, false} {282			for _, wp := range []bool{false, true} {283				for _, p := range pats {284					pattern := []rune(p)285					for j := range corpus {286						disableTwo = true287						rg, pg := FuzzyMatchV2(cs, false, fwd, &corpus[j], pattern, wp, slab)288						disableTwo = false289						rt, pt := FuzzyMatchV2(cs, false, fwd, &corpus[j], pattern, wp, slab)290						if rg != rt {291							t.Fatalf("Result cs=%v fwd=%v wp=%v pat=%q item=%q: general %v vs two %v",292								cs, fwd, wp, p, corpus[j].ToString(), rg, rt)293						}294						if (pg == nil) != (pt == nil) || (pg != nil && !equalInts(*pg, *pt)) {295							t.Fatalf("Pos cs=%v fwd=%v wp=%v pat=%q item=%q: general %v vs two %v",296								cs, fwd, wp, p, corpus[j].ToString(), pg, pt)297						}298					}299				}300			}301		}302	}303}304305func equalInts(a, b []int) bool {306	if len(a) != len(b) {307		return false308	}309	for i := range a {310		if a[i] != b[i] {311			return false312		}313	}314	return true315}