package app import ( "context" "os" "path/filepath" "testing" "time" "github.com/egoist/mygo/ui/editor" "mygoland/internal/lsp" ) // newActionDoc 造一个带缓冲区的文档;path 决定语言。 func newActionDoc(t *testing.T, text string) *Doc { t.Helper() a := &App{root: t.TempDir()} return a.newDoc(filepath.Join(a.root, "a.go"), text) } // TestCursorRangeNoSelection 没有选区时,范围是光标所在的整行。 // // 用整行而不是零宽位置,是因为 gopls 靠「请求范围与诊断范围相交」挑快速 // 修复,而诊断通常只盖住标识符那几个列。 func TestCursorRangeNoSelection(t *testing.T) { d := newActionDoc(t, "package a\n\nfunc main() {}\n") r := cursorOrSelectionRange(d) if r.Start.Line != 0 || r.Start.Character != 0 { t.Fatalf("起点 = %+v", r.Start) } if r.End.Line != 0 || r.End.Character != len("package a") { t.Fatalf("终点 = %+v, 想要第 0 行第 %d 列", r.End, len("package a")) } } // TestCursorRangeAtLine 光标在第二行时范围跟到第二行。 func TestCursorRangeAtLine(t *testing.T) { d := newActionDoc(t, "package a\n\nvar x = 1\n") d.st.GoTo(editor.Pos{Line: 2, Col: 4}) r := cursorOrSelectionRange(d) if r.Start.Line != 2 || r.End.Line != 2 { t.Fatalf("范围落在 %d..%d 行, 想要 2..2", r.Start.Line, r.End.Line) } if r.End.Character != len("var x = 1") { t.Fatalf("终点列 = %d, 想要 %d", r.End.Character, len("var x = 1")) } } // TestCursorRangeSelection 有选区时用选区——这是 extract/inline 的前提。 func TestCursorRangeSelection(t *testing.T) { src := "package a\n\nvar s = foo(1)\n" d := newActionDoc(t, src) // 选中 "foo(1)"(第 2 行第 8..14 字节)。 start := indexOf(src, "foo(1)") d.st.SetSelections(editor.Selection{Anchor: start, Head: start + len("foo(1)")}) r := cursorOrSelectionRange(d) if r.Start.Line != 2 || r.Start.Character != 8 { t.Fatalf("起点 = %+v, 想要第 2 行第 8 列", r.Start) } if r.End.Line != 2 || r.End.Character != 14 { t.Fatalf("终点 = %+v, 想要第 2 行第 14 列", r.End) } } // TestCursorRangeSelectionCJK UTF-16 列号:中文一个字算一列,不能按字节。 func TestCursorRangeSelectionCJK(t *testing.T) { // 前置注释里放中文,让后面的字节数不等于列数。 src := "package a\n\n// 中文注释 x\n" d := newActionDoc(t, src) start := indexOf(src, "x\n") d.st.SetSelections(editor.Selection{Anchor: start, Head: start + 1}) r := cursorOrSelectionRange(d) // "// 中文注释 x" 的 UTF-16 长度:// 加空格 3,中文 4 个字 4,空格 1,x 1 → 9。 if r.Start.Character != 8 || r.End.Character != 9 { t.Fatalf("列号 = %d..%d, 想要 8..9", r.Start.Character, r.End.Character) } } // TestWholeFileRange 整文件范围从第 0 行第 0 列到文件末尾。 // // 注意末尾换行会多出一个空行:`"a\nb\n"` 的 LineCount 是 3,第 2 行是空的。 // 所以文件末尾落在「最后一行第 0 列」,这正是 LSP 眼里的 EOF。 func TestWholeFileRange(t *testing.T) { d := newActionDoc(t, "package a\n\nfunc main() {}\n") r := wholeFileRange(d) if r.Start.Line != 0 || r.Start.Character != 0 { t.Fatalf("起点 = %+v", r.Start) } if r.End.Line != 3 || r.End.Character != 0 { t.Fatalf("终点 = %+v, 想要第 3 行第 0 列(末尾换行后的空行)", r.End) } } // TestWholeFileRangeNoTrailingNewline 没有末尾换行时,末尾是最后一行末列。 func TestWholeFileRangeNoTrailingNewline(t *testing.T) { d := newActionDoc(t, "package a\n\nfunc main() {}") r := wholeFileRange(d) if r.End.Line != 2 || r.End.Character != len("func main() {}") { t.Fatalf("终点 = %+v", r.End) } } // TestDiagsIn 只带与请求范围同行的诊断。 func TestDiagsIn(t *testing.T) { diags := []lsp.Diagnostic{ {Range: lsp.Range{Start: lsp.Position{Line: 3}, End: lsp.Position{Line: 3, Character: 5}}, Message: "a"}, {Range: lsp.Range{Start: lsp.Position{Line: 5}, End: lsp.Position{Line: 7}}, Message: "b"}, {Range: lsp.Range{Start: lsp.Position{Line: 9}, End: lsp.Position{Line: 9}}, Message: "c"}, } // 单行范围:只命中第 3 行那条。 if got := diagsIn(diags, lsp.Range{Start: lsp.Position{Line: 3}, End: lsp.Position{Line: 3}}); len(got) != 1 || got[0].Message != "a" { t.Fatalf("单行范围取到 %+v", got) } // 跨行范围:第 5–7 行的诊断为 b。 if got := diagsIn(diags, lsp.Range{Start: lsp.Position{Line: 4}, End: lsp.Position{Line: 8}}); len(got) != 1 || got[0].Message != "b" { t.Fatalf("跨行范围取到 %+v", got) } // 覆盖全部:三条都要。 if got := diagsIn(diags, lsp.Range{Start: lsp.Position{Line: 0}, End: lsp.Position{Line: 20}}); len(got) != 3 { t.Fatalf("整文件范围只取到 %d 条", len(got)) } // 都不沾:空。 if got := diagsIn(diags, lsp.Range{Start: lsp.Position{Line: 1}, End: lsp.Position{Line: 2}}); len(got) != 0 { t.Fatalf("不相干的范围取到 %+v", got) } } // TestCodeActionRequests 两次请求:一次光标/选区,一次整文件只问 refactor.rewrite。 func TestCodeActionRequests(t *testing.T) { d := newActionDoc(t, "package a\n\nfunc main() {}\n") d.diags = []lsp.Diagnostic{ {Range: lsp.Range{Start: lsp.Position{Line: 0}, End: lsp.Position{Line: 0}}}, {Range: lsp.Range{Start: lsp.Position{Line: 9}, End: lsp.Position{Line: 9}}}, } reqs := codeActionRequests(d) if len(reqs) != 2 { t.Fatalf("请求 %d 次, 想要 2 次", len(reqs)) } // 第一次:第 0 行整行,只带第 0 行的诊断。 if reqs[0].rng.Start.Line != 0 || reqs[0].rng.End.Line != 0 { t.Fatalf("第一次范围 = %+v", reqs[0].rng) } if len(reqs[0].diags) != 1 { t.Fatalf("第一次带了 %d 条诊断, 想要 1 条", len(reqs[0].diags)) } if len(reqs[0].only) != 0 { t.Fatalf("第一次不该限定 only:%v", reqs[0].only) } // 第二次:整文件(末尾换行导致最后一行是空的第 3 行),只问 // refactor.rewrite,且不带诊断。 if reqs[1].rng.End.Line != 3 { t.Fatalf("第二次范围到第 %d 行, 想要文件末尾 3", reqs[1].rng.End.Line) } if len(reqs[1].only) != 1 || reqs[1].only[0] != "refactor.rewrite" { t.Fatalf("第二次 only = %v", reqs[1].only) } if len(reqs[1].diags) != 0 { t.Fatalf("整文件请求不该带诊断:%+v", reqs[1].diags) } } // TestActionNoise 浏览类命令被认出来,真会改代码的放行。 func TestActionNoise(t *testing.T) { withCmd := func(name string) lsp.CodeAction { return lsp.CodeAction{Command: &lsp.Command{Command: name}} } for _, name := range []string{"gopls.doc", "gopls.assembly", "gopls.free_symbols", "gopls.client_open_url", "gopls.gc_details"} { if !actionNoise(withCmd(name)) { t.Fatalf("%q 应判为浏览类", name) } } for _, name := range []string{"gopls.apply_fix", "gopls.add_test", "gopls.modify_tags", "gopls.split_package"} { if actionNoise(withCmd(name)) { t.Fatalf("%q 会改代码,不该过滤", name) } } // 没有 command 的(自带 edit)一律保留。 if actionNoise(lsp.CodeAction{}) { t.Fatal("没有 command 的动作不该被过滤") } } // TestMergeActions 过滤噪音 + 同标题只留第一次出现的那条。 func TestMergeActions(t *testing.T) { first := []lsp.CodeAction{ {Title: "Extract function", Kind: "refactor.extract.function", Command: &lsp.Command{Command: "gopls.apply_fix"}}, {Title: "Browse documentation", Kind: "source.doc", Command: &lsp.Command{Command: "gopls.doc"}}, } second := []lsp.CodeAction{ {Title: "Extract function", Kind: "refactor.rewrite.function", Command: &lsp.Command{Command: "gopls.apply_fix"}}, {Title: "Add struct tags", Kind: "refactor.rewrite.addTags", Command: &lsp.Command{Command: "gopls.modify_tags"}}, } got := mergeActions(first, second) if len(got) != 2 { t.Fatalf("合并后有 %d 项: %+v", len(got), titles(got)) } // 同标题保留第一次的 kind——它的范围与用户眼前一致。 if got[0].Kind != "refactor.extract.function" { t.Fatalf("同名项保留了 %q, 想要第一次的 refactor.extract.function", got[0].Kind) } if got[1].Title != "Add struct tags" { t.Fatalf("第二项是 %q", got[1].Title) } // 顺序:第一次请求的在前。 if got[0].Title != "Extract function" { t.Fatalf("顺序反了:%+v", titles(got)) } } // TestMergeActionsAllNoise 全是浏览命令时结果为空(调用方据此给出「已隐藏」提示)。 func TestMergeActionsAllNoise(t *testing.T) { acts := []lsp.CodeAction{ {Title: "Browse documentation", Command: &lsp.Command{Command: "gopls.doc"}}, {Title: "Browse assembly", Command: &lsp.Command{Command: "gopls.assembly"}}, } if got := mergeActions(acts); len(got) != 0 { t.Fatalf("还剩 %+v", titles(got)) } } // TestRankActions 排序:推荐 → 快速修复 → 重构 → 源码,同档保持原序。 func TestRankActions(t *testing.T) { acts := []lsp.CodeAction{ {Title: "source1", Kind: "source.addTest"}, {Title: "refactor1", Kind: "refactor.rewrite.addTags"}, {Title: "quick1", Kind: "quickfix"}, {Title: "refactor0", Kind: "refactor.extract.variable"}, {Title: "preferred", Kind: "quickfix", IsPreferred: true}, {Title: "other", Kind: ""}, } got := titles(rankActions(acts)) want := []string{"preferred", "quick1", "refactor1", "refactor0", "source1", "other"} if len(got) != len(want) { t.Fatalf("got %v", got) } for i := range want { if got[i] != want[i] { t.Fatalf("第 %d 位是 %q, 想要 %q(全部:%v)", i, got[i], want[i], got) } } } // TestRankActionsStable 同档内不重排:gopls 给的相对顺序是有意义的。 func TestRankActionsStable(t *testing.T) { acts := []lsp.CodeAction{ {Title: "a", Kind: "refactor.a"}, {Title: "b", Kind: "refactor.b"}, {Title: "c", Kind: "refactor.c"}, } if got := titles(rankActions(acts)); len(got) != 3 || got[0] != "a" || got[1] != "b" || got[2] != "c" { t.Fatalf("同档顺序被改动:%v", got) } } // TestActionKindLabel 分类文案,重点是 source 里那几个真会改代码的。 func TestActionKindLabel(t *testing.T) { cases := map[string]string{ "quickfix": "快速修复", "refactor.extract.variable": "提取", "refactor.inline.call": "内联", "refactor.rewrite.addTags": "重写", "refactor.other": "重构", "source.addTest": "生成测试", "source.organizeImports": "整理 import", "source.fixAll": "全部修复", "source.splitPackage": "源码", "": "", "gopls.doc.features": "", } for kind, want := range cases { if got := actionKindLabel(kind); got != want { t.Fatalf("actionKindLabel(%q) = %q, 想要 %q", kind, got, want) } } } // titles 提取标题,便于断言。 func titles(acts []lsp.CodeAction) []string { out := make([]string, len(acts)) for i, a := range acts { out[i] = a.Title } return out } // indexOf 返回子串的字节偏移,找不到返回 -1。 func indexOf(s, sub string) int { for i := 0; i+len(sub) <= len(s); i++ { if s[i:i+len(sub)] == sub { return i } } return -1 } // TestQueryCodeActionsAgainstGopls 用真 gopls 跑完 app 层整条管线: // 算范围 → 发两次请求 → 过滤噪音 → 合并去重 → 排序。 // // 单测覆盖不到的是「我们算出来的范围,gopls 认不认」。这条盯着两件事: // - 选中表达式时,结果里有 refactor.extract.variable(只有选区才有); // - 结果里没有任何 gopls 的浏览类命令(说明噪音过滤生效)。 func TestQueryCodeActionsAgainstGopls(t *testing.T) { if testing.Short() { t.Skip("集成测试需要 gopls") } dir := t.TempDir() if err := os.WriteFile(filepath.Join(dir, "go.mod"), []byte("module demo\n\ngo 1.21\n"), 0o644); err != nil { t.Fatal(err) } src := "package demo\n\nimport \"strings\"\n\nfunc caller() string {\n\treturn strings.ToUpper(\"b\")\n}\n" path := filepath.Join(dir, "demo.go") if err := os.WriteFile(path, []byte(src), 0o644); err != nil { t.Fatal(err) } c, err := lsp.Start(context.Background(), lsp.Options{Root: dir, Logf: t.Logf}) if err != nil { t.Skipf("gopls 不可用: %v", err) } t.Cleanup(func() { _ = c.Close() }) uri := lsp.PathToURI(path) if err := c.DidOpen(uri, "go", 1, src); err != nil { t.Fatal(err) } a := &App{root: dir} d := a.newDoc(path, src) off := indexOf(src, `strings.ToUpper("b")`) if off < 0 { t.Fatal("测试源码里找不到目标表达式") } d.st.SetSelections(editor.Selection{Anchor: off, Head: off + len(`strings.ToUpper("b")`)}) reqs := codeActionRequests(d) if len(reqs) != 2 { t.Fatalf("请求 %d 次", len(reqs)) } var acts []lsp.CodeAction for i := 0; i < 40; i++ { ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second) acts, _, err = queryCodeActions(ctx, c, uri, reqs) cancel() if err != nil { t.Logf("第 %d 次请求出错:%v", i, err) } if len(acts) > 0 { break } time.Sleep(500 * time.Millisecond) } if len(acts) == 0 { t.Fatal("一条动作都没拿到") } var kinds []string for _, act := range acts { kinds = append(kinds, act.Kind) if actionNoise(act) { t.Fatalf("结果里混进了浏览类命令 %q", act.Title) } } t.Logf("过滤排序后 %d 项:%v → %v", len(acts), titles(acts), kinds) found := false for _, k := range kinds { if k == "refactor.extract.variable" { found = true } } if !found { t.Fatalf("选中表达式后没有 extract.variable,实际:%v", kinds) } }