Skip to content

Commit 39b0b1a

Browse files
authored
all: make unit tests work with Go 1.13 (#20053)
Most of these changes are related to the Go 1.13 changes to test binary flag handling. * cmd/geth: make attach tests more reliable This makes the test wait for the endpoint to come up by polling it instead of waiting for two seconds. * tests: fix test binary flags for Go 1.13 Calling flag.Parse during package initialization is prohibited as of Go 1.13 and causes test failures. Call it in TestMain instead. * crypto/ecies: remove useless -dump flag in tests * p2p/simulations: fix test binary flags for Go 1.13 Calling flag.Parse during package initialization is prohibited as of Go 1.13 and causes test failures. Call it in TestMain instead. * build: remove workaround for ./... vendor matching This workaround was necessary for Go 1.8. The Go 1.9 release changed the expansion rules to exclude vendored packages. * Makefile: use relative path for GOBIN This makes the "Run ./build/bin/..." line look nicer. * les: fix test binary flags for Go 1.13 Calling flag.Parse during package initialization is prohibited as of Go 1.13 and causes test failures. Call it in TestMain instead.
1 parent 91b7349 commit 39b0b1a

File tree

10 files changed

+79
-83
lines changed

10 files changed

+79
-83
lines changed

Makefile

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88
.PHONY: geth-darwin geth-darwin-386 geth-darwin-amd64
99
.PHONY: geth-windows geth-windows-386 geth-windows-amd64
1010

11-
GOBIN = $(shell pwd)/build/bin
11+
GOBIN = ./build/bin
1212
GO ?= latest
1313

1414
geth:

build/ci.go

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -214,7 +214,6 @@ func doInstall(cmdline []string) {
214214
if flag.NArg() > 0 {
215215
packages = flag.Args()
216216
}
217-
packages = build.ExpandPackagesNoVendor(packages)
218217

219218
if *arch == "" || *arch == runtime.GOARCH {
220219
goinstall := goTool("install", buildFlags(env)...)
@@ -311,7 +310,6 @@ func doTest(cmdline []string) {
311310
if len(flag.CommandLine.Args()) > 0 {
312311
packages = flag.CommandLine.Args()
313312
}
314-
packages = build.ExpandPackagesNoVendor(packages)
315313

316314
// Run the actual tests.
317315
// Test a single package at a time. CI builders are slow

cmd/geth/consolecmd_test.go

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -87,7 +87,7 @@ func TestIPCAttachWelcome(t *testing.T) {
8787
"--port", "0", "--maxpeers", "0", "--nodiscover", "--nat", "none",
8888
"--etherbase", coinbase, "--shh", "--ipcpath", ipc)
8989

90-
time.Sleep(2 * time.Second) // Simple way to wait for the RPC endpoint to open
90+
waitForEndpoint(t, ipc, 3*time.Second)
9191
testAttachWelcome(t, geth, "ipc:"+ipc, ipcAPIs)
9292

9393
geth.Interrupt()
@@ -101,8 +101,9 @@ func TestHTTPAttachWelcome(t *testing.T) {
101101
"--port", "0", "--maxpeers", "0", "--nodiscover", "--nat", "none",
102102
"--etherbase", coinbase, "--rpc", "--rpcport", port)
103103

104-
time.Sleep(2 * time.Second) // Simple way to wait for the RPC endpoint to open
105-
testAttachWelcome(t, geth, "http://localhost:"+port, httpAPIs)
104+
endpoint := "http://127.0.0.1:" + port
105+
waitForEndpoint(t, endpoint, 3*time.Second)
106+
testAttachWelcome(t, geth, endpoint, httpAPIs)
106107

107108
geth.Interrupt()
108109
geth.ExpectExit()
@@ -116,8 +117,9 @@ func TestWSAttachWelcome(t *testing.T) {
116117
"--port", "0", "--maxpeers", "0", "--nodiscover", "--nat", "none",
117118
"--etherbase", coinbase, "--ws", "--wsport", port)
118119

119-
time.Sleep(2 * time.Second) // Simple way to wait for the RPC endpoint to open
120-
testAttachWelcome(t, geth, "ws://localhost:"+port, httpAPIs)
120+
endpoint := "ws://127.0.0.1:" + port
121+
waitForEndpoint(t, endpoint, 3*time.Second)
122+
testAttachWelcome(t, geth, endpoint, httpAPIs)
121123

122124
geth.Interrupt()
123125
geth.ExpectExit()

cmd/geth/run_test.go

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,13 +17,16 @@
1717
package main
1818

1919
import (
20+
"context"
2021
"fmt"
2122
"io/ioutil"
2223
"os"
2324
"testing"
25+
"time"
2426

2527
"github.com/docker/docker/pkg/reexec"
2628
"github.com/ethereum/go-ethereum/internal/cmdtest"
29+
"github.com/ethereum/go-ethereum/rpc"
2730
)
2831

2932
func tmpdir(t *testing.T) string {
@@ -96,3 +99,28 @@ func runGeth(t *testing.T, args ...string) *testgeth {
9699

97100
return tt
98101
}
102+
103+
// waitForEndpoint attempts to connect to an RPC endpoint until it succeeds.
104+
func waitForEndpoint(t *testing.T, endpoint string, timeout time.Duration) {
105+
probe := func() bool {
106+
ctx, cancel := context.WithTimeout(context.Background(), timeout)
107+
defer cancel()
108+
c, err := rpc.DialContext(ctx, endpoint)
109+
if c != nil {
110+
_, err = c.SupportedModules()
111+
c.Close()
112+
}
113+
return err == nil
114+
}
115+
116+
start := time.Now()
117+
for {
118+
if probe() {
119+
return
120+
}
121+
if time.Since(start) > timeout {
122+
t.Fatal("endpoint", endpoint, "did not open within", timeout)
123+
}
124+
time.Sleep(200 * time.Millisecond)
125+
}
126+
}

crypto/ecies/ecies_test.go

Lines changed: 0 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -35,22 +35,13 @@ import (
3535
"crypto/rand"
3636
"crypto/sha256"
3737
"encoding/hex"
38-
"flag"
3938
"fmt"
4039
"math/big"
4140
"testing"
4241

4342
"github.com/ethereum/go-ethereum/crypto"
4443
)
4544

46-
var dumpEnc bool
47-
48-
func init() {
49-
flDump := flag.Bool("dump", false, "write encrypted test message to file")
50-
flag.Parse()
51-
dumpEnc = *flDump
52-
}
53-
5445
// Ensure the KDF generates appropriately sized keys.
5546
func TestKDF(t *testing.T) {
5647
msg := []byte("Hello, world")

internal/build/util.go

Lines changed: 0 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -153,32 +153,6 @@ func GoTool(tool string, args ...string) *exec.Cmd {
153153
return exec.Command(filepath.Join(runtime.GOROOT(), "bin", "go"), args...)
154154
}
155155

156-
// ExpandPackagesNoVendor expands a cmd/go import path pattern, skipping
157-
// vendored packages.
158-
func ExpandPackagesNoVendor(patterns []string) []string {
159-
expand := false
160-
for _, pkg := range patterns {
161-
if strings.Contains(pkg, "...") {
162-
expand = true
163-
}
164-
}
165-
if expand {
166-
cmd := GoTool("list", patterns...)
167-
out, err := cmd.CombinedOutput()
168-
if err != nil {
169-
log.Fatalf("package listing failed: %v\n%s", err, string(out))
170-
}
171-
var packages []string
172-
for _, line := range strings.Split(string(out), "\n") {
173-
if !strings.Contains(line, "/vendor/") {
174-
packages = append(packages, strings.TrimSpace(line))
175-
}
176-
}
177-
return packages
178-
}
179-
return patterns
180-
}
181-
182156
// UploadSFTP uploads files to a remote host using the sftp command line tool.
183157
// The destination host may be specified either as [user@]host[: or as a URI in
184158
// the form sftp://[user@]host[:port].

les/api_test.go

Lines changed: 20 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -43,11 +43,25 @@ import (
4343
"github.com/mattn/go-colorable"
4444
)
4545

46-
/*
47-
This test is not meant to be a part of the automatic testing process because it
48-
runs for a long time and also requires a large database in order to do a meaningful
49-
request performance test. When testServerDataDir is empty, the test is skipped.
50-
*/
46+
// Additional command line flags for the test binary.
47+
var (
48+
loglevel = flag.Int("loglevel", 0, "verbosity of logs")
49+
simAdapter = flag.String("adapter", "exec", "type of simulation: sim|socket|exec|docker")
50+
)
51+
52+
func TestMain(m *testing.M) {
53+
flag.Parse()
54+
log.PrintOrigins(true)
55+
log.Root().SetHandler(log.LvlFilterHandler(log.Lvl(*loglevel), log.StreamHandler(colorable.NewColorableStderr(), log.TerminalFormat(true))))
56+
// register the Delivery service which will run as a devp2p
57+
// protocol when using the exec adapter
58+
adapters.RegisterServices(services)
59+
os.Exit(m.Run())
60+
}
61+
62+
// This test is not meant to be a part of the automatic testing process because it
63+
// runs for a long time and also requires a large database in order to do a meaningful
64+
// request performance test. When testServerDataDir is empty, the test is skipped.
5165

5266
const (
5367
testServerDataDir = "" // should always be empty on the master branch
@@ -377,29 +391,13 @@ func getCapacityInfo(ctx context.Context, t *testing.T, server *rpc.Client) (min
377391
return
378392
}
379393

380-
func init() {
381-
flag.Parse()
382-
// register the Delivery service which will run as a devp2p
383-
// protocol when using the exec adapter
384-
adapters.RegisterServices(services)
385-
386-
log.PrintOrigins(true)
387-
log.Root().SetHandler(log.LvlFilterHandler(log.Lvl(*loglevel), log.StreamHandler(colorable.NewColorableStderr(), log.TerminalFormat(true))))
388-
}
389-
390-
var (
391-
adapter = flag.String("adapter", "exec", "type of simulation: sim|socket|exec|docker")
392-
loglevel = flag.Int("loglevel", 0, "verbosity of logs")
393-
nodes = flag.Int("nodes", 0, "number of nodes")
394-
)
395-
396394
var services = adapters.Services{
397395
"lesclient": newLesClientService,
398396
"lesserver": newLesServerService,
399397
}
400398

401399
func NewNetwork() (*simulations.Network, func(), error) {
402-
adapter, adapterTeardown, err := NewAdapter(*adapter, services)
400+
adapter, adapterTeardown, err := NewAdapter(*simAdapter, services)
403401
if err != nil {
404402
return nil, adapterTeardown, err
405403
}

p2p/simulations/http_test.go

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ import (
2222
"fmt"
2323
"math/rand"
2424
"net/http/httptest"
25+
"os"
2526
"reflect"
2627
"sync"
2728
"sync/atomic"
@@ -38,15 +39,13 @@ import (
3839
"github.com/mattn/go-colorable"
3940
)
4041

41-
var (
42-
loglevel = flag.Int("loglevel", 2, "verbosity of logs")
43-
)
42+
func TestMain(m *testing.M) {
43+
loglevel := flag.Int("loglevel", 2, "verbosity of logs")
4444

45-
func init() {
4645
flag.Parse()
47-
4846
log.PrintOrigins(true)
4947
log.Root().SetHandler(log.LvlFilterHandler(log.Lvl(*loglevel), log.StreamHandler(colorable.NewColorableStderr(), log.TerminalFormat(true))))
48+
os.Exit(m.Run())
5049
}
5150

5251
// testService implements the node.Service interface and provides protocols

tests/init_test.go

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ package tests
1818

1919
import (
2020
"encoding/json"
21+
"flag"
2122
"fmt"
2223
"io"
2324
"io/ioutil"
@@ -33,6 +34,17 @@ import (
3334
"github.com/ethereum/go-ethereum/params"
3435
)
3536

37+
// Command line flags to configure the interpreters.
38+
var (
39+
testEVM = flag.String("vm.evm", "", "EVM configuration")
40+
testEWASM = flag.String("vm.ewasm", "", "EWASM configuration")
41+
)
42+
43+
func TestMain(m *testing.M) {
44+
flag.Parse()
45+
os.Exit(m.Run())
46+
}
47+
3648
var (
3749
baseDir = filepath.Join(".", "testdata")
3850
blockTestDir = filepath.Join(baseDir, "BlockchainTests")

tests/state_test.go

Lines changed: 7 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -19,12 +19,10 @@ package tests
1919
import (
2020
"bufio"
2121
"bytes"
22-
"flag"
2322
"fmt"
2423
"reflect"
2524
"testing"
2625

27-
"github.com/ethereum/go-ethereum/cmd/utils"
2826
"github.com/ethereum/go-ethereum/core/vm"
2927
)
3028

@@ -71,20 +69,15 @@ func TestState(t *testing.T) {
7169
// Transactions with gasLimit above this value will not get a VM trace on failure.
7270
const traceErrorLimit = 400000
7371

74-
// The VM config for state tests that accepts --vm.* command line arguments.
75-
var testVMConfig = func() vm.Config {
76-
vmconfig := vm.Config{}
77-
flag.StringVar(&vmconfig.EVMInterpreter, utils.EVMInterpreterFlag.Name, utils.EVMInterpreterFlag.Value, utils.EVMInterpreterFlag.Usage)
78-
flag.StringVar(&vmconfig.EWASMInterpreter, utils.EWASMInterpreterFlag.Name, utils.EWASMInterpreterFlag.Value, utils.EWASMInterpreterFlag.Usage)
79-
flag.Parse()
80-
return vmconfig
81-
}()
82-
8372
func withTrace(t *testing.T, gasLimit uint64, test func(vm.Config) error) {
84-
err := test(testVMConfig)
73+
// Use config from command line arguments.
74+
config := vm.Config{EVMInterpreter: *testEVM, EWASMInterpreter: *testEWASM}
75+
err := test(config)
8576
if err == nil {
8677
return
8778
}
79+
80+
// Test failed, re-run with tracing enabled.
8881
t.Error(err)
8982
if gasLimit > traceErrorLimit {
9083
t.Log("gas limit too high for EVM trace")
@@ -93,7 +86,8 @@ func withTrace(t *testing.T, gasLimit uint64, test func(vm.Config) error) {
9386
buf := new(bytes.Buffer)
9487
w := bufio.NewWriter(buf)
9588
tracer := vm.NewJSONLogger(&vm.LogConfig{DisableMemory: true}, w)
96-
err2 := test(vm.Config{Debug: true, Tracer: tracer})
89+
config.Debug, config.Tracer = true, tracer
90+
err2 := test(config)
9791
if !reflect.DeepEqual(err, err2) {
9892
t.Errorf("different error for second run: %v", err2)
9993
}

0 commit comments

Comments
 (0)