Files
MyGolandRelease/internal/lsp/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

219 lines
6.9 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 lsp
import (
"context"
"path/filepath"
"strings"
"testing"
"time"
)
// codeActionKinds 请求一次代码动作,返回所有 kind。
func codeActionKinds(t *testing.T, c *Client, uri string, r Range, diags []Diagnostic, only []string) []string {
t.Helper()
ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
defer cancel()
acts, err := c.CodeActionsOnly(ctx, uri, r, diags, only)
if err != nil {
t.Fatalf("请求代码动作失败: %v", err)
}
kinds := make([]string, 0, len(acts))
for _, a := range acts {
kinds = append(kinds, a.Kind)
}
return kinds
}
// waitKind 轮询到出现指定 kind 为止(gopls 加载包需要时间)。
func waitKind(t *testing.T, c *Client, uri string, r Range, diags []Diagnostic, only []string, want string) []string {
t.Helper()
var kinds []string
for i := 0; i < 40; i++ {
kinds = codeActionKinds(t, c, uri, r, diags, only)
for _, k := range kinds {
if k == want {
return kinds
}
}
time.Sleep(500 * time.Millisecond)
}
t.Fatalf("等了 20 秒也没等到 %q,最后的 kind:%v", want, kinds)
return nil
}
// hasKind 判断 kind 列表里有没有某一项。
func hasKind(kinds []string, want string) bool {
for _, k := range kinds {
if k == want {
return true
}
}
return false
}
const codeActionSrc = `package demo
import "strings"
type Rect struct {
W, H float64
}
func (r Rect) Area() float64 { return r.W * r.H }
func caller() string {
return strings.ToUpper("b")
}
`
// TestGoplsCodeActionSelection 选区决定 gopls 给不给 extract/inline。
//
// 这条测试钉的是一个**实测事实**(gopls v0.23):
// - 范围正好圈住表达式 → 有 refactor.extract.variable、refactor.inline.call
// - 范围是整行 → 只有 refactor.extract.function,没有前两者
//
// 应用层就是靠它把「选中 foo() 再按 Alt+Enter」做成「提取这个表达式」的;
// 一旦有人把选区退回成整行,这里会红。
func TestGoplsCodeActionSelection(t *testing.T) {
c, dir, _ := startTestClient(t)
path := filepath.Join(dir, "demo.go")
writeFile(t, path, codeActionSrc)
uri := PathToURI(path)
if err := c.DidOpen(uri, "go", 1, codeActionSrc); err != nil {
t.Fatal(err)
}
off := strings.Index(codeActionSrc, `strings.ToUpper("b")`)
if off < 0 {
t.Fatal("测试源码里找不到目标表达式")
}
sel := Range{
Start: OffsetToPosition(codeActionSrc, off),
End: OffsetToPosition(codeActionSrc, off+len(`strings.ToUpper("b")`)),
}
kinds := waitKind(t, c, uri, sel, nil, nil, "refactor.extract.variable")
for _, want := range []string{"refactor.extract.variable", "refactor.inline.call"} {
if !hasKind(kinds, want) {
t.Fatalf("选区请求里没有 %q:%v", want, kinds)
}
}
// 同一行、但范围是整个行 → 只剩 extract.function。
line := sel.Start.Line
lineText := strings.Split(codeActionSrc, "\n")[line]
lineRange := Range{
Start: Position{Line: line, Character: 0},
End: Position{Line: line, Character: UTF16Len(lineText)},
}
kinds = waitKind(t, c, uri, lineRange, nil, nil, "refactor.extract.function")
if hasKind(kinds, "refactor.extract.variable") {
t.Fatalf("整行范围居然也给了 extract.variable,前提变了:%v", kinds)
}
}
// TestGoplsCodeActionWholeFile 整文件范围 + only=refactor.rewrite 才能拿到
// 「Add struct tags」这类文件级重构。
func TestGoplsCodeActionWholeFile(t *testing.T) {
c, dir, _ := startTestClient(t)
path := filepath.Join(dir, "demo.go")
writeFile(t, path, codeActionSrc)
uri := PathToURI(path)
if err := c.DidOpen(uri, "go", 1, codeActionSrc); err != nil {
t.Fatal(err)
}
lines := strings.Split(codeActionSrc, "\n")
whole := Range{
Start: Position{Line: 0},
End: Position{Line: len(lines) - 1, Character: UTF16Len(lines[len(lines)-1])},
}
kinds := waitKind(t, c, uri, whole, nil, []string{"refactor.rewrite"}, "refactor.rewrite.addTags")
// only 得真的起过滤作用:不该混进 quickfix 或 source。
for _, k := range kinds {
if strings.HasPrefix(k, "quickfix") || strings.HasPrefix(k, "source") {
t.Fatalf("only=refactor.rewrite 却返回了 %q", k)
}
}
}
// TestGoplsCodeActionMissingImportQuickfix 快速修复的取法。
//
// 用「缺 import」当例子:gopls v0.23 对 `undefined: fmt` 会给
// 「Add import: "fmt"」这条 quickfix。钉住两点(实测,不是推测):
// - 不带诊断 → 拿不到。quickfix 靠上下文里的诊断匹配,这条是硬前提;
// - 请求范围给整行还是行首的零宽位置 → 都拿得到。gopls 会把位置摊到
// 所属节点上,所以「范围必须盖住诊断」不是必要条件。
//
// 第二条是修正:原先应用层的注释声称「零宽位置会丢快速修复」,实测不成立。
func TestGoplsCodeActionMissingImportQuickfix(t *testing.T) {
c, dir, diags := startTestClient(t)
src := "package demo\n\nfunc f() { fmt.Println(1) }\n"
path := filepath.Join(dir, "demo.go")
writeFile(t, path, src)
uri := PathToURI(path)
if err := c.DidOpen(uri, "go", 1, src); err != nil {
t.Fatal(err)
}
var dg []Diagnostic
select {
case dg = <-diags:
case <-time.After(90 * time.Second):
t.Fatal("等诊断超时")
}
if len(dg) == 0 {
t.Skip("gopls 这次没推诊断,跳过")
}
pos := OffsetToPosition(src, strings.Index(src, "func f()"))
full := Range{
Start: Position{Line: pos.Line, Character: 0},
End: Position{Line: pos.Line, Character: UTF16Len("func f() { fmt.Println(1) }")},
}
// 整行 + 诊断:应当拿到 quickfix,且是那条加 import 的。
var titles []string
for i := 0; i < 40; i++ {
kinds := codeActionKinds(t, c, uri, full, dg, []string{"quickfix"})
titles = titles[:0]
if len(kinds) > 0 {
ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
acts, err := c.CodeActionsOnly(ctx, uri, full, dg, []string{"quickfix"})
cancel()
if err != nil {
t.Fatalf("请求代码动作失败: %v", err)
}
for _, a := range acts {
titles = append(titles, a.Title)
}
break
}
time.Sleep(500 * time.Millisecond)
}
if len(titles) == 0 {
t.Fatalf("整行范围 + 诊断没拿到快速修复")
}
found := false
for _, s := range titles {
if strings.Contains(s, "import") && strings.Contains(s, "fmt") {
found = true
}
}
if !found {
t.Fatalf("快速修复里没有加 import 的那条:%v", titles)
}
// 对照组一:不带诊断。
if got := codeActionKinds(t, c, uri, full, nil, []string{"quickfix"}); len(got) != 0 {
t.Fatalf("不带诊断也拿到了 %v,前提变了", got)
}
// 对照:带诊断,但请求范围收成行首的零宽位置——照样拿得到。
// 说明「整行」是给按节点展开的动作留范围,不是 quickfix 的必要条件。
zero := Range{Start: full.Start, End: full.Start}
if got := codeActionKinds(t, c, uri, zero, dg, []string{"quickfix"}); len(got) == 0 {
t.Fatal("零宽位置反而丢了快速修复,那注释里的说法要再改一次")
}
}