github.com/lukso-network/go-ethereum@v1.8.22/p2p/protocols/reporter_test.go (about) 1 // Copyright 2018 The go-ethereum Authors 2 // This file is part of the go-ethereum library. 3 // 4 // The go-ethereum library is free software: you can redistribute it and/or modify 5 // it under the terms of the GNU Lesser General Public License as published by 6 // the Free Software Foundation, either version 3 of the License, or 7 // (at your option) any later version. 8 // 9 // The go-ethereum library is distributed in the hope that it will be useful, 10 // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 // GNU Lesser General Public License for more details. 13 // 14 // You should have received a copy of the GNU Lesser General Public License 15 // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>. 16 17 package protocols 18 19 import ( 20 "io/ioutil" 21 "os" 22 "path/filepath" 23 "testing" 24 "time" 25 26 "github.com/ethereum/go-ethereum/log" 27 ) 28 29 //TestReporter tests that the metrics being collected for p2p accounting 30 //are being persisted and available after restart of a node. 31 //It simulates restarting by just recreating the DB as if the node had restarted. 32 func TestReporter(t *testing.T) { 33 //create a test directory 34 dir, err := ioutil.TempDir("", "reporter-test") 35 if err != nil { 36 t.Fatal(err) 37 } 38 defer os.RemoveAll(dir) 39 40 //setup the metrics 41 log.Debug("Setting up metrics first time") 42 reportInterval := 5 * time.Millisecond 43 metrics := SetupAccountingMetrics(reportInterval, filepath.Join(dir, "test.db")) 44 log.Debug("Done.") 45 46 //do some metrics 47 mBalanceCredit.Inc(12) 48 mBytesCredit.Inc(34) 49 mMsgDebit.Inc(9) 50 51 //give the reporter time to write the metrics to DB 52 time.Sleep(20 * time.Millisecond) 53 54 //set the metrics to nil - this effectively simulates the node having shut down... 55 mBalanceCredit = nil 56 mBytesCredit = nil 57 mMsgDebit = nil 58 //close the DB also, or we can't create a new one 59 metrics.Close() 60 61 //setup the metrics again 62 log.Debug("Setting up metrics second time") 63 metrics = SetupAccountingMetrics(reportInterval, filepath.Join(dir, "test.db")) 64 defer metrics.Close() 65 log.Debug("Done.") 66 67 //now check the metrics, they should have the same value as before "shutdown" 68 if mBalanceCredit.Count() != 12 { 69 t.Fatalf("Expected counter to be %d, but is %d", 12, mBalanceCredit.Count()) 70 } 71 if mBytesCredit.Count() != 34 { 72 t.Fatalf("Expected counter to be %d, but is %d", 23, mBytesCredit.Count()) 73 } 74 if mMsgDebit.Count() != 9 { 75 t.Fatalf("Expected counter to be %d, but is %d", 9, mMsgDebit.Count()) 76 } 77 }