package app // 测试闭环的「透镜」辅助:失败定位解析、-run 过滤串、测试函数扫描、 // 输出文件名到磁盘路径的还原。这一层全是纯逻辑(App 方法只碰缓存), // 单测不拉进程就能覆盖。 import ( "os" "path/filepath" "regexp" "strconv" "strings" ) // failLocRe 匹配测试输出里的「文件.go:行号:」。 // ` main_test.go:12: boom`、`/x/y/sub_test.go:7:` 和带盘符的 // `D:\x\y\sub_test.go:7:` 都吃——盘符的冒号在可选的 `[A-Za-z]:` 里消化掉, // 不然 `[^:\s]` 会在 D 后面被冒号截断。 var failLocRe = regexp.MustCompile(`^\s*((?:[A-Za-z]:)?[^:\s]+\.go):(\d+):`) // testFuncRe 匹配顶格的测试函数声明。只认 Test/Benchmark/Fuzz 开头的大写名, // `func writeTestFile(t *testing.T)` 这类 helper 不会误中。 var testFuncRe = regexp.MustCompile(`(?m)^func (Test|Benchmark|Fuzz)(\w+)\(`) // failureLoc 从一段测试输出里找第一个失败位置。 // go test 把 t.Errorf 的位置打在输出行首(缩进后的 file:line:), // `--- FAIL:` 行本身不带位置,正则自然跳过。 func failureLoc(lines []string) (string, int) { for _, l := range lines { m := failLocRe.FindStringSubmatch(l) if m == nil { continue } n, err := strconv.Atoi(m[2]) if err != nil || n <= 0 { continue } return m[1], n } return "", 0 } // runFilterFor 把测试全名转成 -run 的锚定正则。 // 子测试按 / 分段各锚一次:`TestFoo/case 1` → `^TestFoo$/^case 1$`。 // QuoteMeta 很关键——子测试名常带空格、方括号这类正则元字符。 func runFilterFor(name string) string { parts := strings.Split(name, "/") for i, p := range parts { parts[i] = "^" + regexp.QuoteMeta(p) + "$" } return strings.Join(parts, "/") } // testFuncInfo 是源码里扫到的一个可运行测试。 type testFuncInfo struct { Name string Line int // 0 基 } // scanTestFuncs 找出文本里的 Test/Benchmark/Fuzz 函数和它们的行号。 // 不走 gopls:确定性正则、零延迟,而且对未保存的缓冲区同样生效—— // 新写的测试函数没保存也能直接跑。 func scanTestFuncs(text string) []testFuncInfo { var out []testFuncInfo for _, loc := range testFuncRe.FindAllStringSubmatchIndex(text, -1) { out = append(out, testFuncInfo{ Name: text[loc[2]:loc[3]] + text[loc[4]:loc[5]], Line: strings.Count(text[:loc[0]], "\n"), }) } return out } // testFuncAt 返回光标行落在哪个测试函数里;不在任何函数体内时返回 false。 // 判定方式:找光标上方最近的一个测试函数,若它与光标**之间**出现了顶格的 // `}`,说明函数体已经结束——收尾 `}` 那一行本身仍算在函数里(跟主流 IDE // 的「运行光标处测试」一致),函数之间的空行不算。 func testFuncAt(text string, line int) (string, bool) { var best *testFuncInfo funcs := scanTestFuncs(text) for i := range funcs { if funcs[i].Line <= line { best = &funcs[i] } else { break } } if best == nil { return "", false } for l := best.Line + 1; l < line; l++ { if strings.HasPrefix(lineAt(text, l), "}") { return "", false } } return best.Name, true } // lineAt 取第 n 行(0 基)的内容,越界返回空串。 func lineAt(text string, n int) string { if n < 0 { return "" } for i := 0; i < n; i++ { if j := strings.IndexByte(text, '\n'); j >= 0 { text = text[j+1:] } else { return "" } } if j := strings.IndexByte(text, '\n'); j >= 0 { text = text[:j] } return strings.TrimRight(text, "\r") } // modulePrefix 读工作区 go.mod 的 module 名(按 root 缓存),读不到返回空。 func (a *App) modulePrefix() string { if a.root == "" { return "" } if a.modRoot == a.root && a.modName != "" { return a.modName } data, err := os.ReadFile(filepath.Join(a.root, "go.mod")) if err != nil { return "" } for _, l := range strings.Split(string(data), "\n") { l = strings.TrimSpace(l) if strings.HasPrefix(l, "module ") { a.modRoot = a.root a.modName = strings.TrimSpace(strings.TrimPrefix(l, "module ")) return a.modName } } return "" } // resolveTestFile 把失败输出里的文件名还原成磁盘路径。 // go test 的输出通常只给包内相对名(main_test.go:12),要拼上包目录; // 包目录按「module 前缀 + import 路径」从工作区根还原。拼出来的路径不存在时, // 退一步在工作区文件索引里找同名文件(对付特殊布局),再不行就把猜的路径 // 原样返回——openAt 打不开会自己报错,不在这里吞。 func (a *App) resolveTestFile(pkg, file string) string { if filepath.IsAbs(file) { return file } rel := pkg if mod := a.modulePrefix(); mod != "" { switch { case pkg == mod: rel = "" case strings.HasPrefix(pkg, mod+"/"): rel = strings.TrimPrefix(pkg, mod+"/") } } p := filepath.Join(a.root, filepath.FromSlash(rel), filepath.FromSlash(file)) if _, err := os.Stat(p); err == nil { return p } if paths, ok := a.indexSnapshot(); ok { base := filepath.Base(file) for _, cand := range paths { if filepath.Base(cand) == base { return cand } } } return p }