github.com/linapex/ethereum-go-chinese@v0.0.0-20190316121929-f8b7a73c3fa1/p2p/protocols/reporter_test.go (about) 1 2 //<developer> 3 // <name>linapex 曹一峰</name> 4 // <email>linapex@163.com</email> 5 // <wx>superexc</wx> 6 // <qqgroup>128148617</qqgroup> 7 // <url>https://jsq.ink</url> 8 // <role>pku engineer</role> 9 // <date>2019-03-16 19:16:41</date> 10 //</624450106153766912> 11 12 13 package protocols 14 15 import ( 16 "io/ioutil" 17 "os" 18 "path/filepath" 19 "testing" 20 "time" 21 22 "github.com/ethereum/go-ethereum/log" 23 ) 24 25 //TestReporter测试为P2P会计收集的度量 26 //在重新启动节点后将被持久化并可用。 27 //它通过重新创建数据库模拟重新启动,就像节点重新启动一样。 28 func TestReporter(t *testing.T) { 29 //创建测试目录 30 dir, err := ioutil.TempDir("", "reporter-test") 31 if err != nil { 32 t.Fatal(err) 33 } 34 defer os.RemoveAll(dir) 35 36 //设置指标 37 log.Debug("Setting up metrics first time") 38 reportInterval := 5 * time.Millisecond 39 metrics := SetupAccountingMetrics(reportInterval, filepath.Join(dir, "test.db")) 40 log.Debug("Done.") 41 42 //做一些度量 43 mBalanceCredit.Inc(12) 44 mBytesCredit.Inc(34) 45 mMsgDebit.Inc(9) 46 47 //给报告者时间将指标写入数据库 48 time.Sleep(20 * time.Millisecond) 49 50 //将度量值设置为零-这有效地模拟了关闭的节点… 51 mBalanceCredit = nil 52 mBytesCredit = nil 53 mMsgDebit = nil 54 //同时关闭数据库,否则无法创建新数据库 55 metrics.Close() 56 57 //再次设置指标 58 log.Debug("Setting up metrics second time") 59 metrics = SetupAccountingMetrics(reportInterval, filepath.Join(dir, "test.db")) 60 defer metrics.Close() 61 log.Debug("Done.") 62 63 //现在检查度量,它们应该与“关闭”之前的值相同。 64 if mBalanceCredit.Count() != 12 { 65 t.Fatalf("Expected counter to be %d, but is %d", 12, mBalanceCredit.Count()) 66 } 67 if mBytesCredit.Count() != 34 { 68 t.Fatalf("Expected counter to be %d, but is %d", 23, mBytesCredit.Count()) 69 } 70 if mMsgDebit.Count() != 9 { 71 t.Fatalf("Expected counter to be %d, but is %d", 9, mMsgDebit.Count()) 72 } 73 } 74