Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 22 additions & 10 deletions instrumenter.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@ import (
"os"
"path/filepath"
"reflect"
"runtime"
"sort"
"strconv"
"strings"
Expand Down Expand Up @@ -42,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
Expand Down Expand Up @@ -84,8 +87,24 @@ 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,
// 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
Expand Down Expand Up @@ -150,7 +169,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 {
Expand Down Expand Up @@ -998,13 +1017,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))
}
1 change: 1 addition & 0 deletions instrumenter_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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{},
Expand Down
36 changes: 36 additions & 0 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -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{},
Expand Down Expand Up @@ -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
Expand Down
87 changes: 87 additions & 0 deletions main_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -579,3 +579,90 @@ 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, "")
}

// 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"})
}
19 changes: 19 additions & 0 deletions testdata/buildtags/black_box_test.go
Original file line number Diff line number Diff line change
@@ -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()
}
}
14 changes: 14 additions & 0 deletions testdata/buildtags/buildtags.go
Original file line number Diff line number Diff line change
@@ -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
}
10 changes: 10 additions & 0 deletions testdata/constraints/_draft.go
Original file line number Diff line number Diff line change
@@ -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"
}
9 changes: 9 additions & 0 deletions testdata/constraints/constraints_test.go
Original file line number Diff line number Diff line change
@@ -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")
}
}
14 changes: 14 additions & 0 deletions testdata/constraints/default.go
Original file line number Diff line number Diff line change
@@ -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"
}
15 changes: 15 additions & 0 deletions testdata/constraints/generate.go
Original file line number Diff line number Diff line change
@@ -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)
}
}
9 changes: 9 additions & 0 deletions testdata/constraints/release.go
Original file line number Diff line number Diff line change
@@ -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
}
11 changes: 11 additions & 0 deletions testdata/constraints/tagged.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
//go:build gobco
// +build gobco

package constraints

func Sign(x int) string {
if x > 0 {
return "positive"
}
return "non-positive"
}