package app import "testing" func mustMatch(t *testing.T, query string, o searchOpts, line string, want bool) { t.Helper() m, err := buildMatcher(query, o) if err != nil { t.Fatalf("编译失败 %q: %v", query, err) } if got := m(line); got != want { t.Fatalf("%q 匹配 %q: 期望 %v 实际 %v", query, line, want, got) } } func TestMatchPlainIgnoreCase(t *testing.T) { o := searchOpts{} mustMatch(t, "func", o, "func main() {}", true) mustMatch(t, "FUNC", o, "func main() {}", true) mustMatch(t, "xyz", o, "func main() {}", false) } func TestMatchCaseSensitive(t *testing.T) { o := searchOpts{matchCase: true} mustMatch(t, "func", o, "func main() {}", true) mustMatch(t, "FUNC", o, "func main() {}", false) } func TestMatchWholeWord(t *testing.T) { o := searchOpts{wholeWord: true} mustMatch(t, "main", o, "func main() {", true) mustMatch(t, "main", o, "func mainLoop() {", false) } func TestMatchRegex(t *testing.T) { o := searchOpts{useRegex: true} mustMatch(t, `func\s+\w+\(`, o, "func Add(a, b int) {", true) mustMatch(t, `^import`, o, `import "fmt"`, true) mustMatch(t, `^\d+$`, o, "42", true) mustMatch(t, `^\d+$`, o, "42 ", false) } // TestMatchRegexLiteralWhenOff 不开正则时,特殊字符要按字面意思匹配。 func TestMatchRegexLiteralWhenOff(t *testing.T) { o := searchOpts{} mustMatch(t, "a+b", o, "x = a+b", true) mustMatch(t, "a+b", o, "x = aaab", false) mustMatch(t, "a.c", o, "a.c", true) mustMatch(t, "a.c", o, "abc", false) } // TestMatchBadRegex 正则写错时返回错误,搜索面板应显示没有结果而不是崩。 func TestMatchBadRegex(t *testing.T) { if _, err := buildMatcher("a(", searchOpts{useRegex: true}); err == nil { t.Fatal("非法正则应返回错误") } } // TestMatchChineseWholeWord 中文没有词边界,整词会退化成包含,仍应命中。 func TestMatchChineseWholeWord(t *testing.T) { o := searchOpts{wholeWord: true} mustMatch(t, "过磅", o, "// 过磅记录", true) }