package app import ( "os" "path/filepath" "testing" ) func TestFuzzyScore(t *testing.T) { cases := []struct { path, query string want bool }{ {"main.go", "main", true}, {"main.go", "mg", true}, {"internal/app/view.go", "view", true}, {"internal/app/view.go", "iaview", true}, {"main.go", "xyz", false}, {"", "", true}, } for _, c := range cases { if _, ok := fuzzyScore(c.path, c.query); ok != c.want { t.Fatalf("fuzzyScore(%q,%q)=%v 期望 %v", c.path, c.query, ok, c.want) } } } // TestFuzzyScorePrefersBasename 确认按文件名命中的排在目录命中的前面。 func TestFuzzyScorePrefersBasename(t *testing.T) { a, ok1 := fuzzyScore("internal/app/view.go", "view") b, ok2 := fuzzyScore("view/internal/other.go", "view") if !ok1 || !ok2 { t.Fatal("两条都该命中") } if a <= b { t.Fatalf("文件名命中应得分更高: %d vs %d", a, b) } } func TestQuickResultsRanking(t *testing.T) { a := &App{root: t.TempDir()} a.index.mu.Lock() a.index.root = a.root a.index.files = []string{"internal/app/view.go", "view/readme.md", "main.go"} a.index.ready = true a.index.mu.Unlock() got := a.quickResults("view", 10) if len(got) != 2 { t.Fatalf("应命中 2 个,实际 %d", len(got)) } if got[0].Label != "view.go" { t.Fatalf("文件名命中应排第一,实际 %q", got[0].Label) } } func TestSearchInWorkspace(t *testing.T) { root := t.TempDir() if err := os.MkdirAll(filepath.Join(root, "sub"), 0o755); err != nil { t.Fatal(err) } files := map[string]string{ "a.go": "package a\n\nfunc Needle() {}\n", "sub/b.go": "package b\n// needle 在这里\n", "c.txt": "nothing\n", } for name, body := range files { if err := os.WriteFile(filepath.Join(root, name), []byte(body), 0o644); err != nil { t.Fatal(err) } } a := &App{root: root} got, stats := a.searchInWorkspace("needle", 10, searchOpts{}) if len(got) != 2 { t.Fatalf("应命中 2 行,实际 %d: %+v", len(got), got) } if stats.hint() != "" { t.Fatalf("没有跳过文件时不该有提示:%q", stats.hint()) } seen := map[string]int{} for _, it := range got { seen[it.Label] = it.Line } if seen["a.go"] != 3 { t.Fatalf("a.go 命中行应为 3,实际 %d", seen["a.go"]) } if seen[filepath.ToSlash(filepath.Join("sub", "b.go"))] != 2 { t.Fatalf("sub/b.go 命中行应为 2,实际 %v", seen) } } func TestSearchSkipsSkippedDirs(t *testing.T) { root := t.TempDir() if err := os.MkdirAll(filepath.Join(root, "node_modules"), 0o755); err != nil { t.Fatal(err) } if err := os.WriteFile(filepath.Join(root, "node_modules", "x.js"), []byte("needle\n"), 0o644); err != nil { t.Fatal(err) } a := &App{root: root} got, _ := a.searchInWorkspace("needle", 10, searchOpts{}) if len(got) != 0 { t.Fatalf("应当跳过 node_modules,实际命中 %d", len(got)) } }