Files
MyGolandRelease/internal/app/codeaction_test.go
T
zerorigin 6b07d16738 代码动作改用选区、补文件级请求、滤掉 gopls 的浏览类命令
第 10 项。原报告说「代码动作只取光标行 range,所以生成测试/实现接口取
不到」——实测(gopls v0.23)推翻了一半,真问题在别处:

1. 选区被忽略。原来一律传整行,用户选中 foo() 按 Alt+Enter,gopls 收到
   整行,只能给 refactor.extract.function;refactor.extract.variable 和
   refactor.inline.call **只在范围正好圈住表达式时才返回**。
2. 噪音淹没有效动作。一次请求 6–9 项,其中 5 项是 gopls.doc(开
   pkg.go.dev)、assembly、free_symbols、client_open_url、gc_details。
   「Extract variable」被挤到第七位。

而「生成测试」(source.addTest)本来就有;「零宽位置会丢快速修复」也是
错的——gopls 会把位置摊到所属节点,行首零宽照样拿得到 quickfix。

改法:
- 有选区用选区,没有才用整行;
- 发两次请求:光标/选区(带同行诊断)+ 整文件且 only=refactor.rewrite
  (refactor.rewrite.addTags 这类只有范围覆盖到才出现);
- 按**命令名**过滤那 5 个浏览命令(不是标题,标题会随版本变),只黑
  已知噪音、其余放行,gopls 加新能力不会被误杀;
- 同标题取第一次出现的那份(与用户眼前范围一致),再按
  IsPreferred → quickfix → refactor → source 稳定排序;
- 全是浏览命令时提示「这里有 N 项,但都只是打开文档/汇编之类的浏览
  命令,已隐藏」,不再假装什么都没发生。

验证分三层:
- 13 条 app 层单测:范围(含 UTF-16 中文列)、诊断相交、噪音判定、
  合并去重首见优先、排序稳定性;
- 3 条真 gopls 回归:选区给 extract.variable/inline.call、整行不给、
  整文件 only=refactor.rewrite 给 addTags、缺 import 的 quickfix 依赖
  诊断且对零宽位置也宽容;
- 1 条 app 层全管线集成:选中表达式 → 必须出现 extract.variable 且不得
  混入浏览命令。
真实窗口截图 docs/code-action-panel.png 只剩两项,5 个浏览命令没露头。

顺带把 Client.CodeActions 拆出 CodeActionsOnly(支持 context.only),
queryCodeActions 从 goroutine 里拆出来以支持集成测试;actionKindLabel
给 source.addTest/organizeImports/fixAll 单列文案,并给 IsPreferred 加
「推荐 ·」前缀。
2026-11-05 16:38:30 +08:00

377 lines
13 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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)
}
}