package app import ( "os" "path/filepath" "reflect" "testing" ) func TestFailureLocPicksTestFile(t *testing.T) { lines := []string{ "=== RUN TestFoo", " main_test.go:12: boom", "--- FAIL: TestFoo (0.00s)", "FAIL", } file, line := failureLoc(lines) if file != "main_test.go" || line != 12 { t.Fatalf("应解析出 main_test.go:12,实际 %s:%d", file, line) } } func TestFailureLocAbsolutePath(t *testing.T) { file, line := failureLoc([]string{` D:\x\y\sub_test.go:7: nope`}) if file != `D:\x\y\sub_test.go` || line != 7 { t.Fatalf("绝对路径应原样保留,实际 %s:%d", file, line) } } func TestFailureLocNone(t *testing.T) { if f, l := failureLoc([]string{"--- FAIL: TestX (0.1s)", "panic: boom"}); f != "" || l != 0 { t.Fatalf("没有 file:line 时应为空,实际 %s:%d", f, l) } } func TestRunFilterFor(t *testing.T) { cases := map[string]string{ "TestFoo": "^TestFoo$", "TestFoo/case 1": "^TestFoo$/^case 1$", "TestFoo/a[b]/sub": "^TestFoo$/^a\\[b\\]$/^sub$", } for name, want := range cases { if got := runFilterFor(name); got != want { t.Errorf("runFilterFor(%q) = %q,期望 %q", name, got, want) } } } func TestScanTestFuncs(t *testing.T) { src := `package app func helper(t *testing.T) {} func TestFoo(t *testing.T) { } func BenchmarkX(b *testing.B) { } func TestBar(t *testing.T) { } ` got := scanTestFuncs(src) want := []testFuncInfo{ {Name: "TestFoo", Line: 4}, {Name: "BenchmarkX", Line: 7}, {Name: "TestBar", Line: 10}, } if !reflect.DeepEqual(got, want) { t.Fatalf("扫描结果不符,got %+v want %+v", got, want) } } func TestTestFuncAt(t *testing.T) { src := "package app\n\nfunc TestFoo(t *testing.T) {\n\tx()\n}\n\nfunc TestBar(t *testing.T) {\n}\n" cases := []struct { line int name string found bool }{ {0, "", false}, // package 行 {1, "", false}, // 第一个函数之前 {2, "TestFoo", true}, // 声明行本身 {3, "TestFoo", true}, // 函数体内 {4, "TestFoo", true}, // 收尾 } 上仍算在函数里 {5, "", false}, // 函数之间的空行 {6, "TestBar", true}, } for _, c := range cases { name, ok := testFuncAt(src, c.line) if ok != c.found || name != c.name { t.Errorf("testFuncAt(line=%d) = (%q,%v),期望 (%q,%v)", c.line, name, ok, c.name, c.found) } } } func TestResolveTestFile(t *testing.T) { root := t.TempDir() if err := os.WriteFile(filepath.Join(root, "go.mod"), []byte("module demo\n\ngo 1.21\n"), 0o644); err != nil { t.Fatal(err) } dir := filepath.Join(root, "internal", "app") if err := os.MkdirAll(dir, 0o755); err != nil { t.Fatal(err) } if err := os.WriteFile(filepath.Join(dir, "foo_test.go"), []byte("package app\n"), 0o644); err != nil { t.Fatal(err) } a := &App{root: root} got := a.resolveTestFile("demo/internal/app", "foo_test.go") if want := filepath.Join(dir, "foo_test.go"); got != want { t.Fatalf("应按 module 前缀还原,got %q want %q", got, want) } // 绝对路径直接透传。 if got := a.resolveTestFile("demo", root); got != root { t.Fatalf("绝对路径应透传,got %q", got) } // 包路径不在 module 里且文件不存在:不 panic,返回一个猜测路径。 _ = a.resolveTestFile("other/pkg", "zzz_test.go") }