all: replace fmt.Print* calls with t.Log* in tests (#19670)

This commit is contained in:
大彬 2019-07-17 19:20:24 +08:00 committed by Felix Lange
parent 8f80cafa10
commit 4ac04ae0fe
10 changed files with 85 additions and 87 deletions

View File

@ -18,7 +18,6 @@ package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"reflect"
"strings"
@ -61,7 +60,7 @@ func TestAlethSturebyConverter(t *testing.T) {
got := strings.Split(c.Sdump(spec), "\n")
for i := 0; i < len(exp) && i < len(got); i++ {
if exp[i] != got[i] {
fmt.Printf("got: %v\nexp: %v\n", exp[i], got[i])
t.Logf("got: %v\nexp: %v\n", exp[i], got[i])
}
}
}
@ -102,7 +101,7 @@ func TestParitySturebyConverter(t *testing.T) {
got := strings.Split(c.Sdump(spec), "\n")
for i := 0; i < len(exp) && i < len(got); i++ {
if exp[i] != got[i] {
fmt.Printf("got: %v\nexp: %v\n", exp[i], got[i])
t.Logf("got: %v\nexp: %v\n", exp[i], got[i])
}
}
}

View File

@ -46,7 +46,7 @@ func print(t *testing.T, f *freezerTable, item uint64) {
if err != nil {
t.Fatal(err)
}
fmt.Printf("db[%d] = %x\n", item, a)
t.Logf("db[%d] = %x\n", item, a)
}
// TestFreezerBasics test initializing a freezertable from scratch, writing to the table,

View File

@ -58,11 +58,11 @@ func TestKDF(t *testing.T) {
k, err := concatKDF(h, msg, nil, 64)
if err != nil {
fmt.Println(err.Error())
t.Log(err.Error())
t.FailNow()
}
if len(k) != 64 {
fmt.Printf("KDF: generated key is the wrong size (%d instead of 64\n", len(k))
t.Logf("KDF: generated key is the wrong size (%d instead of 64\n", len(k))
t.FailNow()
}
}
@ -97,31 +97,31 @@ func cmpPublic(pub1, pub2 PublicKey) bool {
func TestSharedKey(t *testing.T) {
prv1, err := GenerateKey(rand.Reader, DefaultCurve, nil)
if err != nil {
fmt.Println(err.Error())
t.Log(err.Error())
t.FailNow()
}
skLen := MaxSharedKeyLength(&prv1.PublicKey) / 2
prv2, err := GenerateKey(rand.Reader, DefaultCurve, nil)
if err != nil {
fmt.Println(err.Error())
t.Log(err.Error())
t.FailNow()
}
sk1, err := prv1.GenerateShared(&prv2.PublicKey, skLen, skLen)
if err != nil {
fmt.Println(err.Error())
t.Log(err.Error())
t.FailNow()
}
sk2, err := prv2.GenerateShared(&prv1.PublicKey, skLen, skLen)
if err != nil {
fmt.Println(err.Error())
t.Log(err.Error())
t.FailNow()
}
if !bytes.Equal(sk1, sk2) {
fmt.Println(ErrBadSharedKeys.Error())
t.Log(ErrBadSharedKeys.Error())
t.FailNow()
}
}
@ -151,7 +151,7 @@ func TestSharedKeyPadding(t *testing.T) {
// test shared secret generation
sk1, err := prv0.GenerateShared(&prv1.PublicKey, 16, 16)
if err != nil {
fmt.Println(err.Error())
t.Log(err.Error())
}
sk2, err := prv1.GenerateShared(&prv0.PublicKey, 16, 16)
@ -169,25 +169,25 @@ func TestSharedKeyPadding(t *testing.T) {
func TestTooBigSharedKey(t *testing.T) {
prv1, err := GenerateKey(rand.Reader, DefaultCurve, nil)
if err != nil {
fmt.Println(err.Error())
t.Log(err.Error())
t.FailNow()
}
prv2, err := GenerateKey(rand.Reader, DefaultCurve, nil)
if err != nil {
fmt.Println(err.Error())
t.Log(err.Error())
t.FailNow()
}
_, err = prv1.GenerateShared(&prv2.PublicKey, 32, 32)
if err != ErrSharedKeyTooBig {
fmt.Println("ecdh: shared key should be too large for curve")
t.Log("ecdh: shared key should be too large for curve")
t.FailNow()
}
_, err = prv2.GenerateShared(&prv1.PublicKey, 32, 32)
if err != ErrSharedKeyTooBig {
fmt.Println("ecdh: shared key should be too large for curve")
t.Log("ecdh: shared key should be too large for curve")
t.FailNow()
}
}
@ -196,7 +196,7 @@ func TestTooBigSharedKey(t *testing.T) {
func BenchmarkGenerateKeyP256(b *testing.B) {
for i := 0; i < b.N; i++ {
if _, err := GenerateKey(rand.Reader, elliptic.P256(), nil); err != nil {
fmt.Println(err.Error())
b.Log(err.Error())
b.FailNow()
}
}
@ -206,14 +206,14 @@ func BenchmarkGenerateKeyP256(b *testing.B) {
func BenchmarkGenSharedKeyP256(b *testing.B) {
prv, err := GenerateKey(rand.Reader, elliptic.P256(), nil)
if err != nil {
fmt.Println(err.Error())
b.Log(err.Error())
b.FailNow()
}
b.ResetTimer()
for i := 0; i < b.N; i++ {
_, err := prv.GenerateShared(&prv.PublicKey, 16, 16)
if err != nil {
fmt.Println(err.Error())
b.Log(err.Error())
b.FailNow()
}
}
@ -223,14 +223,14 @@ func BenchmarkGenSharedKeyP256(b *testing.B) {
func BenchmarkGenSharedKeyS256(b *testing.B) {
prv, err := GenerateKey(rand.Reader, crypto.S256(), nil)
if err != nil {
fmt.Println(err.Error())
b.Log(err.Error())
b.FailNow()
}
b.ResetTimer()
for i := 0; i < b.N; i++ {
_, err := prv.GenerateShared(&prv.PublicKey, 16, 16)
if err != nil {
fmt.Println(err.Error())
b.Log(err.Error())
b.FailNow()
}
}
@ -240,37 +240,37 @@ func BenchmarkGenSharedKeyS256(b *testing.B) {
func TestEncryptDecrypt(t *testing.T) {
prv1, err := GenerateKey(rand.Reader, DefaultCurve, nil)
if err != nil {
fmt.Println(err.Error())
t.Log(err.Error())
t.FailNow()
}
prv2, err := GenerateKey(rand.Reader, DefaultCurve, nil)
if err != nil {
fmt.Println(err.Error())
t.Log(err.Error())
t.FailNow()
}
message := []byte("Hello, world.")
ct, err := Encrypt(rand.Reader, &prv2.PublicKey, message, nil, nil)
if err != nil {
fmt.Println(err.Error())
t.Log(err.Error())
t.FailNow()
}
pt, err := prv2.Decrypt(ct, nil, nil)
if err != nil {
fmt.Println(err.Error())
t.Log(err.Error())
t.FailNow()
}
if !bytes.Equal(pt, message) {
fmt.Println("ecies: plaintext doesn't match message")
t.Log("ecies: plaintext doesn't match message")
t.FailNow()
}
_, err = prv1.Decrypt(ct, nil, nil)
if err == nil {
fmt.Println("ecies: encryption should not have succeeded")
t.Log("ecies: encryption should not have succeeded")
t.FailNow()
}
}
@ -341,48 +341,48 @@ func TestParamSelection(t *testing.T) {
func testParamSelection(t *testing.T, c testCase) {
params := ParamsFromCurve(c.Curve)
if params == nil && c.Expected != nil {
fmt.Printf("%s (%s)\n", ErrInvalidParams.Error(), c.Name)
t.Logf("%s (%s)\n", ErrInvalidParams.Error(), c.Name)
t.FailNow()
} else if params != nil && !cmpParams(params, c.Expected) {
fmt.Printf("ecies: parameters should be invalid (%s)\n",
t.Logf("ecies: parameters should be invalid (%s)\n",
c.Name)
t.FailNow()
}
prv1, err := GenerateKey(rand.Reader, DefaultCurve, nil)
if err != nil {
fmt.Printf("%s (%s)\n", err.Error(), c.Name)
t.Logf("%s (%s)\n", err.Error(), c.Name)
t.FailNow()
}
prv2, err := GenerateKey(rand.Reader, DefaultCurve, nil)
if err != nil {
fmt.Printf("%s (%s)\n", err.Error(), c.Name)
t.Logf("%s (%s)\n", err.Error(), c.Name)
t.FailNow()
}
message := []byte("Hello, world.")
ct, err := Encrypt(rand.Reader, &prv2.PublicKey, message, nil, nil)
if err != nil {
fmt.Printf("%s (%s)\n", err.Error(), c.Name)
t.Logf("%s (%s)\n", err.Error(), c.Name)
t.FailNow()
}
pt, err := prv2.Decrypt(ct, nil, nil)
if err != nil {
fmt.Printf("%s (%s)\n", err.Error(), c.Name)
t.Logf("%s (%s)\n", err.Error(), c.Name)
t.FailNow()
}
if !bytes.Equal(pt, message) {
fmt.Printf("ecies: plaintext doesn't match message (%s)\n",
t.Logf("ecies: plaintext doesn't match message (%s)\n",
c.Name)
t.FailNow()
}
_, err = prv1.Decrypt(ct, nil, nil)
if err == nil {
fmt.Printf("ecies: encryption should not have succeeded (%s)\n",
t.Logf("ecies: encryption should not have succeeded (%s)\n",
c.Name)
t.FailNow()
}
@ -396,14 +396,14 @@ func TestBasicKeyValidation(t *testing.T) {
prv, err := GenerateKey(rand.Reader, DefaultCurve, nil)
if err != nil {
fmt.Println(err.Error())
t.Log(err.Error())
t.FailNow()
}
message := []byte("Hello, world.")
ct, err := Encrypt(rand.Reader, &prv.PublicKey, message, nil, nil)
if err != nil {
fmt.Println(err.Error())
t.Log(err.Error())
t.FailNow()
}
@ -411,7 +411,7 @@ func TestBasicKeyValidation(t *testing.T) {
ct[0] = b
_, err := prv.Decrypt(ct, nil, nil)
if err != ErrInvalidPublicKey {
fmt.Println("ecies: validated an invalid key")
t.Log("ecies: validated an invalid key")
t.FailNow()
}
}
@ -450,18 +450,18 @@ func TestSharedKeyStatic(t *testing.T) {
sk1, err := prv1.GenerateShared(&prv2.PublicKey, skLen, skLen)
if err != nil {
fmt.Println(err.Error())
t.Log(err.Error())
t.FailNow()
}
sk2, err := prv2.GenerateShared(&prv1.PublicKey, skLen, skLen)
if err != nil {
fmt.Println(err.Error())
t.Log(err.Error())
t.FailNow()
}
if !bytes.Equal(sk1, sk2) {
fmt.Println(ErrBadSharedKeys.Error())
t.Log(ErrBadSharedKeys.Error())
t.FailNow()
}

View File

@ -1614,8 +1614,8 @@ func TestRemoteHeaderRequestSpan(t *testing.T) {
if failed {
res := strings.Replace(fmt.Sprint(data), " ", ",", -1)
exp := strings.Replace(fmt.Sprint(tt.expected), " ", ",", -1)
fmt.Printf("got: %v\n", res)
fmt.Printf("exp: %v\n", exp)
t.Logf("got: %v\n", res)
t.Logf("exp: %v\n", exp)
t.Errorf("test %d: wrong values", i)
}
}

View File

@ -64,7 +64,7 @@ const benchFilterCnt = 2000
func benchmarkBloomBits(b *testing.B, sectionSize uint64) {
benchDataDir := node.DefaultDataDir() + "/geth/chaindata"
fmt.Println("Running bloombits benchmark section size:", sectionSize)
b.Log("Running bloombits benchmark section size:", sectionSize)
db, err := rawdb.NewLevelDBDatabase(benchDataDir, 128, 1024, "")
if err != nil {
@ -76,7 +76,7 @@ func benchmarkBloomBits(b *testing.B, sectionSize uint64) {
}
clearBloomBits(db)
fmt.Println("Generating bloombits data...")
b.Log("Generating bloombits data...")
headNum := rawdb.ReadHeaderNumber(db, head)
if headNum == nil || *headNum < sectionSize+512 {
b.Fatalf("not enough blocks for running a benchmark")
@ -111,16 +111,16 @@ func benchmarkBloomBits(b *testing.B, sectionSize uint64) {
rawdb.WriteBloomBits(db, uint(i), sectionIdx, sectionHead, comp)
}
//if sectionIdx%50 == 0 {
// fmt.Println(" section", sectionIdx, "/", cnt)
// b.Log(" section", sectionIdx, "/", cnt)
//}
}
d := time.Since(start)
fmt.Println("Finished generating bloombits data")
fmt.Println(" ", d, "total ", d/time.Duration(cnt*sectionSize), "per block")
fmt.Println(" data size:", dataSize, " compressed size:", compSize, " compression ratio:", float64(compSize)/float64(dataSize))
b.Log("Finished generating bloombits data")
b.Log(" ", d, "total ", d/time.Duration(cnt*sectionSize), "per block")
b.Log(" data size:", dataSize, " compressed size:", compSize, " compression ratio:", float64(compSize)/float64(dataSize))
fmt.Println("Running filter benchmarks...")
b.Log("Running filter benchmarks...")
start = time.Now()
mux := new(event.TypeMux)
var backend *testBackend
@ -140,8 +140,8 @@ func benchmarkBloomBits(b *testing.B, sectionSize uint64) {
}
}
d = time.Since(start)
fmt.Println("Finished running filter benchmarks")
fmt.Println(" ", d, "total ", d/time.Duration(benchFilterCnt), "per address", d*time.Duration(1000000)/time.Duration(benchFilterCnt*cnt*sectionSize), "per million blocks")
b.Log("Finished running filter benchmarks")
b.Log(" ", d, "total ", d/time.Duration(benchFilterCnt), "per address", d*time.Duration(1000000)/time.Duration(benchFilterCnt*cnt*sectionSize), "per million blocks")
db.Close()
}
@ -158,7 +158,7 @@ func clearBloomBits(db ethdb.Database) {
func BenchmarkNoBloomBits(b *testing.B) {
benchDataDir := node.DefaultDataDir() + "/geth/chaindata"
fmt.Println("Running benchmark without bloombits")
b.Log("Running benchmark without bloombits")
db, err := rawdb.NewLevelDBDatabase(benchDataDir, 128, 1024, "")
if err != nil {
b.Fatalf("error opening database at %v: %v", benchDataDir, err)
@ -171,14 +171,14 @@ func BenchmarkNoBloomBits(b *testing.B) {
clearBloomBits(db)
fmt.Println("Running filter benchmarks...")
b.Log("Running filter benchmarks...")
start := time.Now()
mux := new(event.TypeMux)
backend := &testBackend{mux, db, 0, new(event.Feed), new(event.Feed), new(event.Feed), new(event.Feed)}
filter := NewRangeFilter(backend, 0, int64(*headNum), []common.Address{{}}, nil)
filter.Logs(context.Background())
d := time.Since(start)
fmt.Println("Finished running filter benchmarks")
fmt.Println(" ", d, "total ", d*time.Duration(1000000)/time.Duration(*headNum+1), "per million blocks")
b.Log("Finished running filter benchmarks")
b.Log(" ", d, "total ", d*time.Duration(1000000)/time.Duration(*headNum+1), "per million blocks")
db.Close()
}

View File

@ -20,7 +20,6 @@ import (
"context"
"errors"
"flag"
"fmt"
"io/ioutil"
"math/rand"
"os"
@ -41,7 +40,7 @@ import (
"github.com/ethereum/go-ethereum/p2p/simulations"
"github.com/ethereum/go-ethereum/p2p/simulations/adapters"
"github.com/ethereum/go-ethereum/rpc"
colorable "github.com/mattn/go-colorable"
"github.com/mattn/go-colorable"
)
/*
@ -100,7 +99,7 @@ func testCapacityAPI(t *testing.T, clientCount int) {
totalCap := getTotalCap(ctx, t, serverRpcClient)
minCap := getMinCap(ctx, t, serverRpcClient)
testCap := totalCap * 3 / 4
fmt.Printf("Server testCap: %d minCap: %d head number: %d head hash: %064x\n", testCap, minCap, headNum, headHash)
t.Logf("Server testCap: %d minCap: %d head number: %d head hash: %064x\n", testCap, minCap, headNum, headHash)
reqMinCap := uint64(float64(testCap) * minRelCap / (minRelCap + float64(len(clients)-1)))
if minCap > reqMinCap {
t.Fatalf("Minimum client capacity (%d) bigger than required minimum for this test (%d)", minCap, reqMinCap)
@ -116,7 +115,7 @@ func testCapacityAPI(t *testing.T, clientCount int) {
t.Fatalf("Failed to obtain rpc client: %v", err)
}
fmt.Println("connecting client", i)
t.Log("connecting client", i)
if i != freeIdx {
setCapacity(ctx, t, serverRpcClient, client.ID(), testCap/uint64(len(clients)))
}
@ -130,7 +129,7 @@ func testCapacityAPI(t *testing.T, clientCount int) {
}
num, hash := getHead(ctx, t, clientRpcClients[i])
if num == headNum && hash == headHash {
fmt.Println("client", i, "synced")
t.Log("client", i, "synced")
break
}
time.Sleep(time.Millisecond * 200)
@ -225,12 +224,12 @@ func testCapacityAPI(t *testing.T, clientCount int) {
}
time.Sleep(flowcontrol.DecParamDelay)
fmt.Println("Starting measurement")
fmt.Printf("Relative weights:")
t.Log("Starting measurement")
t.Logf("Relative weights:")
for i := range clients {
fmt.Printf(" %f", weights[i])
t.Logf(" %f", weights[i])
}
fmt.Println()
t.Log()
start := processedSince(nil)
for {
select {
@ -241,7 +240,7 @@ func testCapacityAPI(t *testing.T, clientCount int) {
totalCap = getTotalCap(ctx, t, serverRpcClient)
if totalCap < testCap {
fmt.Println("Total capacity underrun")
t.Log("Total capacity underrun")
close(stop)
wg.Wait()
return false
@ -249,9 +248,9 @@ func testCapacityAPI(t *testing.T, clientCount int) {
processed := processedSince(start)
var avg uint64
fmt.Printf("Processed")
t.Logf("Processed")
for i, p := range processed {
fmt.Printf(" %d", p)
t.Logf(" %d", p)
processed[i] = uint64(float64(p) / weights[i])
avg += processed[i]
}
@ -261,7 +260,7 @@ func testCapacityAPI(t *testing.T, clientCount int) {
var maxDev float64
for _, p := range processed {
dev := float64(int64(p-avg)) / float64(avg)
fmt.Printf(" %7.4f", dev)
t.Logf(" %7.4f", dev)
if dev < 0 {
dev = -dev
}
@ -269,13 +268,13 @@ func testCapacityAPI(t *testing.T, clientCount int) {
maxDev = dev
}
}
fmt.Printf(" max deviation: %f totalCap: %d\n", maxDev, totalCap)
t.Logf(" max deviation: %f totalCap: %d\n", maxDev, totalCap)
if maxDev <= testTolerance {
fmt.Println("success")
t.Log("success")
break
}
} else {
fmt.Println()
t.Log()
}
time.Sleep(time.Millisecond * 200)
}
@ -285,11 +284,11 @@ func testCapacityAPI(t *testing.T, clientCount int) {
wg.Wait()
for i, count := range reqCount {
fmt.Println("client", i, "processed", count)
t.Log("client", i, "processed", count)
}
return true
}) {
fmt.Println("restarting test")
t.Log("restarting test")
}
}
@ -323,7 +322,7 @@ func testRequest(ctx context.Context, t *testing.T, client *rpc.Client) bool {
// if err := client.CallContext(ctx, &res, "eth_getProof", addr, nil, "latest"); err != nil {
err := client.CallContext(c, &res, "eth_getBalance", addr, "latest")
if err != nil {
fmt.Println("request error:", err)
t.Log("request error:", err)
}
return err == nil
}

View File

@ -50,7 +50,7 @@ func TestSimRandomResolve(t *testing.T) {
if err := net.SetFallbackNodes([]*Node{bootnode.Self()}); err != nil {
panic(err)
}
fmt.Printf("launched @ %v: %x\n", time.Now(), net.Self().ID[:16])
t.Logf("launched @ %v: %x\n", time.Now(), net.Self().ID[:16])
}
}()

View File

@ -321,11 +321,11 @@ func TestFormatter(t *testing.T) {
}
formatted, _ := d.Format()
for _, item := range formatted {
fmt.Printf("'%v'\n", item.Pprint(0))
t.Logf("'%v'\n", item.Pprint(0))
}
j, _ := json.Marshal(formatted)
fmt.Printf("'%v'\n", string(j))
t.Logf("'%v'\n", string(j))
}
func sign(typedData core.TypedData) ([]byte, []byte, error) {
@ -364,7 +364,7 @@ func TestJsonFiles(t *testing.T) {
continue
}
_, _, err = sign(typedData)
fmt.Printf("Error %v\n", err)
t.Logf("Error %v\n", err)
if err != nil && !expectedFailure {
t.Errorf("Test %d failed, file %v: %v", i, fInfo.Name(), err)
}
@ -397,11 +397,11 @@ func TestFuzzerFiles(t *testing.T) {
}
_, err = typedData.EncodeData("EIP712Domain", typedData.Domain.Map(), 1)
if verbose && err != nil {
fmt.Printf("%d, EncodeData[1] err: %v\n", i, err)
t.Logf("%d, EncodeData[1] err: %v\n", i, err)
}
_, err = typedData.EncodeData(typedData.PrimaryType, typedData.Message, 1)
if verbose && err != nil {
fmt.Printf("%d, EncodeData[2] err: %v\n", i, err)
t.Logf("%d, EncodeData[2] err: %v\n", i, err)
}
typedData.Format()
}

View File

@ -178,7 +178,7 @@ func TestSignTxRequest(t *testing.T) {
t.Error(err)
return
}
fmt.Printf("to %v", to.Address().String())
t.Logf("to %v", to.Address().String())
resp, err := r.ApproveTx(&core.SignTxRequest{
Transaction: core.SendTxArgs{
From: *from,
@ -294,7 +294,7 @@ func TestMissingFunc(t *testing.T) {
if approved {
t.Errorf("Expected missing method to cause non-approval")
}
fmt.Printf("Err %v", err)
t.Logf("Err %v", err)
}
func TestStorage(t *testing.T) {
@ -346,7 +346,7 @@ func TestStorage(t *testing.T) {
if retval != exp {
t.Errorf("Unexpected data, expected '%v', got '%v'", exp, retval)
}
fmt.Printf("Err %v", err)
t.Logf("Err %v", err)
}
@ -602,7 +602,7 @@ function ApproveSignData(r){
hash, rawdata := accounts.TextAndHash([]byte(message))
addr, _ := mixAddr("0x694267f14675d7e1b9494fd8d72fefe1755710fa")
fmt.Printf("address %v %v\n", addr.String(), addr.Original())
t.Logf("address %v %v\n", addr.String(), addr.Original())
nvt := []*core.NameValueType{
{

View File

@ -38,13 +38,13 @@ func TestEncryption(t *testing.T) {
if err != nil {
t.Fatal(err)
}
fmt.Printf("Ciphertext %x, nonce %x\n", c, iv)
t.Logf("Ciphertext %x, nonce %x\n", c, iv)
p, err := decrypt(key, iv, c, nil)
if err != nil {
t.Fatal(err)
}
fmt.Printf("Plaintext %v\n", string(p))
t.Logf("Plaintext %v\n", string(p))
if !bytes.Equal(plaintext, p) {
t.Errorf("Failed: expected plaintext recovery, got %v expected %v", string(plaintext), string(p))
}