add initial support for running tests

For now, it mainly consists of not garbling Test* funcs, and not
garbling the _testmain.go file that will run them.

Updates #6.
pull/22/head
Daniel Martí 5 years ago
parent c23f529830
commit bee30aff41

@ -108,7 +108,7 @@ func main1() int {
func mainErr(args []string) error {
// If we recognise an argument, we're not running within -toolexec.
switch cmd := args[0]; cmd {
case "build":
case "build", "test":
execPath, err := os.Executable()
if err != nil {
return err
@ -192,6 +192,9 @@ func transformCompile(args []string) ([]string, error) {
// Nothing to transform; probably just ["-V=full"].
return args, nil
}
if len(paths) == 1 && filepath.Base(paths[0]) == "_testmain.go" {
return args, nil
}
// If the value of -trimpath doesn't contain the separator ';', the 'go
// build' command is most likely not using '-trimpath'.
@ -363,6 +366,9 @@ func transformGo(node ast.Node, info *types.Info) ast.Node {
case "main", "init":
return true // don't break them
}
if strings.HasPrefix(node.Name, "Test") && isTestSignature(sign) {
return true // don't break tests
}
case nil:
switch cursor.Parent().(type) {
case *ast.AssignStmt:
@ -404,6 +410,27 @@ func isStandardLibrary(path string) bool {
return !strings.Contains(path, ".")
}
// isTestSignature returns true if the signature matches "func _(*testing.T)".
func isTestSignature(sign *types.Signature) bool {
if sign.Recv() != nil {
return false
}
params := sign.Params()
if params.Len() != 1 {
return false
}
ptr, ok := params.At(0).Type().(*types.Pointer) // *testing.T
if !ok {
return false
}
named, ok := ptr.Elem().(*types.Named) // testing.T
if !ok {
return false
}
obj := named.Obj()
return obj.Pkg().Path() == "testing" && obj.Name() == "T"
}
func transformLink(args []string) ([]string, error) {
flags, paths := splitFlagsFromFiles(args, ".a")
if len(paths) == 0 {

@ -0,0 +1,40 @@
! garble badcmd
stderr 'unknown command'
! garble /does/not/exist
stderr 'unknown tool'
! garble /does/not/exist/compile
stderr 'no such file'
exec go test -v
stdout 'PASS.*TestFoo'
garble test -v
stdout 'PASS.*TestFoo'
garble test -c -vet=off
bingrep bar.test$exe 'TestFoo'
! bingrep bar.test$exe 'ImportedVar'
-- go.mod --
module foo.com/bar
-- bar.go --
package bar
func Foo() string { return "Foo" }
var ImportedVar = "imported var value"
-- bar_test.go --
package bar
import (
"testing"
)
func TestFoo(t *testing.T) {
t.Log(ImportedVar)
if Foo() != "Foo" {
t.FailNow()
}
}
Loading…
Cancel
Save