From 8c0828bac0dbe4eec53ad1094bf25d8c82c1d7c0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20M=2E=20Requena=20Plens?= Date: Mon, 28 Sep 2026 17:28:18 +0200 Subject: [PATCH 1/2] Skip files that the go command does not build Since gobco resolves types, it type-checks all parsed files of a directory together. For a package that declares a function once per platform, this failed with "redeclared in this block". A file with '//go:build ignore' and 'package main', as used by 'go generate', resulted in an invalid gobco_bridge_test.go. Select the files in the build context of the go command before parsing them. This also skips file names starting with '_' or '.', and it honors constraints on release tags such as 'go1.21', which shouldBuild did not know about. See https://github.com/rillig/gobco/issues/40. --- instrumenter.go | 22 ++++++++++++---------- main_test.go | 21 +++++++++++++++++++++ testdata/constraints/_draft.go | 10 ++++++++++ testdata/constraints/constraints_test.go | 9 +++++++++ testdata/constraints/default.go | 14 ++++++++++++++ testdata/constraints/generate.go | 15 +++++++++++++++ testdata/constraints/release.go | 9 +++++++++ testdata/constraints/tagged.go | 11 +++++++++++ 8 files changed, 101 insertions(+), 10 deletions(-) create mode 100644 testdata/constraints/_draft.go create mode 100644 testdata/constraints/constraints_test.go create mode 100644 testdata/constraints/default.go create mode 100644 testdata/constraints/generate.go create mode 100644 testdata/constraints/release.go create mode 100644 testdata/constraints/tagged.go diff --git a/instrumenter.go b/instrumenter.go index 8fe71c9..38f0e88 100644 --- a/instrumenter.go +++ b/instrumenter.go @@ -13,7 +13,6 @@ import ( "os" "path/filepath" "reflect" - "runtime" "sort" "strconv" "strings" @@ -84,8 +83,18 @@ type instrumenter struct { func (i *instrumenter) instrument(srcDir, singleFile, dstDir string) bool { i.fset = token.NewFileSet() + // Only the files that the go command builds belong to the package. + // The other files may redeclare the same names, + // such as a function that is implemented once per platform, + // or they may even belong to another package, + // such as a 'package main' that is only run by 'go generate'. isRelevant := func(info os.FileInfo) bool { - return singleFile == "" || info.Name() == singleFile + if singleFile != "" && info.Name() != singleFile { + return false + } + match, err := build.Default.MatchFile(srcDir, info.Name()) + ok(err) + return match } // Comments are needed for build tags @@ -150,7 +159,7 @@ func (i *instrumenter) resolveTypes(pkgsMap map[string]*ast.Package) { func (i *instrumenter) instrumentFile(filename string, astFile *ast.File, dstDir string) { isTest := strings.HasSuffix(filename, "_test.go") - if (i.coverTest || !isTest) && shouldBuild(filename) { + if i.coverTest || !isTest { i.instrumentFileNode(astFile) } if isTest { @@ -998,13 +1007,6 @@ again: return ok && ident.Name == "nil" } -func shouldBuild(filename string) bool { - ctx := build.Context{GOOS: runtime.GOOS, GOARCH: runtime.GOARCH} - m, err := ctx.MatchFile(filepath.Split(filename)) - ok(err) - return m -} - func writeFile(filename string, content string) { ok(os.WriteFile(filename, []byte(content), 0o666)) } diff --git a/main_test.go b/main_test.go index e1a1caf..dc371db 100644 --- a/main_test.go +++ b/main_test.go @@ -579,3 +579,24 @@ func Test_gobcoMain__issue38(t *testing.T) { }) s.CheckEquals(stderr, "") } + +// Files that the go command doesn't build are not instrumented. +// They may redeclare names from the other files, +// or they may even belong to another package. +// The files that the go command builds are instrumented, +// even if their constraints refer to the release of the go toolchain. +func Test_gobcoMain__build_constraints(t *testing.T) { + s := NewSuite(t) + defer s.TearDownTest() + + stdout, stderr := s.RunMain(0, "gobco", "./testdata/constraints") + + s.CheckEquals(s.GobcoLines(stdout), []string{ + "Condition coverage: 1/4", + "testdata/constraints/default.go:10:5: " + + "condition \"x < 0\" was once false but never true", + "testdata/constraints/release.go:8:9: " + + "condition \"x == 0\" was never evaluated", + }) + s.CheckEquals(stderr, "") +} diff --git a/testdata/constraints/_draft.go b/testdata/constraints/_draft.go new file mode 100644 index 0000000..e642e6a --- /dev/null +++ b/testdata/constraints/_draft.go @@ -0,0 +1,10 @@ +package constraints + +// The go command ignores files whose names start with '_' or '.'. + +func Sign(x int) string { + if x == 0 { + return "zero" + } + return "draft" +} diff --git a/testdata/constraints/constraints_test.go b/testdata/constraints/constraints_test.go new file mode 100644 index 0000000..8c664f8 --- /dev/null +++ b/testdata/constraints/constraints_test.go @@ -0,0 +1,9 @@ +package constraints + +import "testing" + +func TestSign(t *testing.T) { + if Sign(1) == "" { + t.Error("Sign must not return an empty string") + } +} diff --git a/testdata/constraints/default.go b/testdata/constraints/default.go new file mode 100644 index 0000000..55d1437 --- /dev/null +++ b/testdata/constraints/default.go @@ -0,0 +1,14 @@ +//go:build !gobco +// +build !gobco + +package constraints + +// Sign is declared in two files, like a function that is implemented once +// per platform. A plain 'go test' builds this file, while +// 'go test -tags gobco' builds tagged.go instead. +func Sign(x int) string { + if x < 0 { + return "negative" + } + return "non-negative" +} diff --git a/testdata/constraints/generate.go b/testdata/constraints/generate.go new file mode 100644 index 0000000..f199352 --- /dev/null +++ b/testdata/constraints/generate.go @@ -0,0 +1,15 @@ +//go:build ignore +// +build ignore + +// This file does not belong to the package, it is only run by +// 'go generate' or 'go run generate.go'. + +package main + +import "os" + +func main() { + if len(os.Args) > 1 { + os.Exit(1) + } +} diff --git a/testdata/constraints/release.go b/testdata/constraints/release.go new file mode 100644 index 0000000..19057ac --- /dev/null +++ b/testdata/constraints/release.go @@ -0,0 +1,9 @@ +//go:build go1.16 +// +build go1.16 + +package constraints + +// Files can also be constrained on the release of the go toolchain. +func IsZero(x int) bool { + return x == 0 +} diff --git a/testdata/constraints/tagged.go b/testdata/constraints/tagged.go new file mode 100644 index 0000000..dc58d82 --- /dev/null +++ b/testdata/constraints/tagged.go @@ -0,0 +1,11 @@ +//go:build gobco +// +build gobco + +package constraints + +func Sign(x int) string { + if x > 0 { + return "positive" + } + return "non-positive" +} From 13bacb739ef2787029eb6ffbc32ffbec7c8b139c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20M=2E=20Requena=20Plens?= Date: Mon, 28 Sep 2026 17:35:29 +0200 Subject: [PATCH 2/2] Honor the build tags that are passed to go test Files that are only built with a build tag, as in 'go test -tags integration', were never instrumented, not even when gobco was run with '-test -tags=integration'. The report then silently missed their conditions. In a black box test of such a package, the import of the package under test could not be resolved either. Take the build tags from GOFLAGS and from the -test options, in the same way as the go command does, and use them both for selecting the files of the package and for resolving the imported packages. Fixes https://github.com/rillig/gobco/issues/40 --- instrumenter.go | 10 +++++ instrumenter_test.go | 1 + main.go | 36 +++++++++++++++ main_test.go | 66 ++++++++++++++++++++++++++++ testdata/buildtags/black_box_test.go | 19 ++++++++ testdata/buildtags/buildtags.go | 14 ++++++ 6 files changed, 146 insertions(+) create mode 100644 testdata/buildtags/black_box_test.go create mode 100644 testdata/buildtags/buildtags.go diff --git a/instrumenter.go b/instrumenter.go index 38f0e88..82b17bf 100644 --- a/instrumenter.go +++ b/instrumenter.go @@ -41,6 +41,10 @@ type instrumenter struct { listAll bool // also list conditions that are covered debugTypes bool + // The build tags of 'go test', which decide + // which files belong to the package. + buildTags []string + fset *token.FileSet pkg map[*ast.Package]*types.Package typ map[ast.Expr]types.Type @@ -83,6 +87,12 @@ type instrumenter struct { func (i *instrumenter) instrument(srcDir, singleFile, dstDir string) bool { i.fset = token.NewFileSet() + // The source importer that resolves the imported packages + // always uses build.Default, so the build tags must be set there. + // Selecting the files in the package uses the same build context. + defer func(tags []string) { build.Default.BuildTags = tags }(build.Default.BuildTags) + build.Default.BuildTags = i.buildTags + // Only the files that the go command builds belong to the package. // The other files may redeclare the same names, // such as a function that is implemented once per platform, diff --git a/instrumenter_test.go b/instrumenter_test.go index 5a6cb7a..76fbf3f 100644 --- a/instrumenter_test.go +++ b/instrumenter_test.go @@ -86,6 +86,7 @@ func Test_instrumenter(t *testing.T) { false, false, false, + nil, fset, map[*ast.Package]*types.Package{}, map[ast.Expr]types.Type{}, diff --git a/main.go b/main.go index afd9bff..a80117f 100644 --- a/main.go +++ b/main.go @@ -256,6 +256,7 @@ func (g *gobco) instrument() bool { g.immediately, g.listAll, false, + buildTags(os.Getenv("GOFLAGS"), g.goTestArgs), nil, map[*ast.Package]*types.Package{}, map[ast.Expr]types.Type{}, @@ -455,6 +456,41 @@ func (goTest) args(verbose bool, extraArgs []string) []string { return args } +// buildTags returns the build tags with which 'go test' builds the package. +// The go command reads its options first from the environment variable +// GOFLAGS and then from the command line, and the last -tags option wins. +func buildTags(goflags string, goTestArgs []string) []string { + var tags []string + scan := func(args []string) { + for i := 0; i < len(args); i++ { + if !strings.HasPrefix(args[i], "-") { + continue + } + name := strings.TrimPrefix(args[i][1:], "-") + switch { + case name == "args": + return // The remaining arguments are for the test binary. + case name == "tags" && i+1 < len(args): + i++ + tags = splitTags(args[i]) + case strings.HasPrefix(name, "tags="): + tags = splitTags(name[len("tags="):]) + } + } + } + scan(strings.Fields(goflags)) + scan(goTestArgs) + return tags +} + +// splitTags splits a list of build tags that are separated by commas, +// or by spaces, which was the format up to go1.12. +func splitTags(list string) []string { + return strings.FieldsFunc(list, func(r rune) bool { + return r == ',' || r == ' ' + }) +} + func (goTest) env(tmpdir, gopaths, statsFilename string) []string { var env []string diff --git a/main_test.go b/main_test.go index dc371db..b96ebe4 100644 --- a/main_test.go +++ b/main_test.go @@ -600,3 +600,69 @@ func Test_gobcoMain__build_constraints(t *testing.T) { }) s.CheckEquals(stderr, "") } + +// The files are selected with the build tags that are passed to 'go test'. +func Test_gobcoMain__build_tags(t *testing.T) { + s := NewSuite(t) + defer s.TearDownTest() + + stdout, stderr := s.RunMain(0, "gobco", + "-test", "-tags=gobco", "./testdata/constraints") + + s.CheckEquals(s.GobcoLines(stdout), []string{ + "Condition coverage: 1/4", + "testdata/constraints/release.go:8:9: " + + "condition \"x == 0\" was never evaluated", + "testdata/constraints/tagged.go:7:5: " + + "condition \"x > 0\" was once true but never false", + }) + s.CheckEquals(stderr, "") +} + +// The imported packages are resolved with the same build tags, +// including the package under test when it is imported by a black box test. +func Test_gobcoMain__build_tags_import(t *testing.T) { + s := NewSuite(t) + defer s.TearDownTest() + + stdout, stderr := s.RunMain(0, "gobco", + "-test", "-tags", "-test", "gobco", "./testdata/buildtags") + + s.CheckEquals(s.GobcoLines(stdout), []string{ + "Condition coverage: 1/2", + "testdata/buildtags/buildtags.go:10:5: " + + "condition \"x < 0\" was once true but never false", + }) + s.CheckEquals(stderr, "") +} + +func Test_buildTags(t *testing.T) { + s := NewSuite(t) + defer s.TearDownTest() + + test := func(goflags string, goTestArgs []string, expected []string) { + s.CheckEquals(buildTags(goflags, goTestArgs), expected) + } + + test("", nil, nil) + test("", []string{"-vet=off"}, nil) + test("", []string{"-tags=a,b"}, []string{"a", "b"}) + test("", []string{"--tags=a"}, []string{"a"}) + test("", []string{"-tags", "a,b"}, []string{"a", "b"}) + test("", []string{"-tags"}, nil) + test("", []string{"-run", "tags"}, nil) + + // Up to go1.12, the tags were separated by spaces. + test("", []string{"-tags=a b"}, []string{"a", "b"}) + + // The last option wins, even if it is empty. + test("", []string{"-tags=a", "-tags=b"}, []string{"b"}) + test("", []string{"-tags=a", "-tags="}, []string{}) + + // The arguments after '-args' are passed to the test binary. + test("", []string{"-tags=a", "-args", "-tags=b"}, []string{"a"}) + + // The options from the command line override those from GOFLAGS. + test("-mod=mod -tags=a", nil, []string{"a"}) + test("-tags=a", []string{"-tags=b"}, []string{"b"}) +} diff --git a/testdata/buildtags/black_box_test.go b/testdata/buildtags/black_box_test.go new file mode 100644 index 0000000..d2d6139 --- /dev/null +++ b/testdata/buildtags/black_box_test.go @@ -0,0 +1,19 @@ +//go:build gobco +// +build gobco + +package buildtags_test + +import ( + "github.com/rillig/gobco/testdata/buildtags" + "testing" +) + +// When the black box test is type-checked, the imported package under test +// must be resolved with the same build tags, as otherwise it would not have +// any files. + +func TestAbs(t *testing.T) { + if buildtags.Abs(-3) != 3 { + t.Fail() + } +} diff --git a/testdata/buildtags/buildtags.go b/testdata/buildtags/buildtags.go new file mode 100644 index 0000000..115c610 --- /dev/null +++ b/testdata/buildtags/buildtags.go @@ -0,0 +1,14 @@ +//go:build gobco +// +build gobco + +// Like many integration tests, this package is only built with a build tag, +// in this case with 'go test -tags gobco'. + +package buildtags + +func Abs(x int) int { + if x < 0 { + return -x + } + return x +}