Best Syzkaller code snippet using state.MakeTestState
sync_test.go
Source:sync_test.go
1// Copyright 2015 The go-ethereum Authors2// This file is part of the go-ethereum library.3//4// The go-ethereum library is free software: you can redistribute it and/or modify5// it under the terms of the GNU Lesser General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (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 of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the12// GNU Lesser General Public License for more details.13//14// You should have received a copy of the GNU Lesser General Public License15// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.16package state17import (18 "bytes"19 "math/big"20 "testing"21 "github.com/ethereum/go-ethereum/common"22 "github.com/ethereum/go-ethereum/crypto"23 "github.com/ethereum/go-ethereum/ethdb"24 "github.com/ethereum/go-ethereum/trie"25)26// testAccount is the data associated with an account used by the state tests.27type testAccount struct {28 address common.Address29 balance *big.Int30 nonce uint6431 code []byte32}33// makeTestState create a sample test state to test node-wise reconstruction.34func makeTestState() (Database, common.Hash, []*testAccount) {35 // Create an empty state36 db := NewDatabase(ethdb.NewMemDatabase())37 state, _ := New(common.Hash{}, db)38 // Fill it with some arbitrary data39 accounts := []*testAccount{}40 for i := byte(0); i < 96; i++ {41 obj := state.GetOrNewStateObject(common.BytesToAddress([]byte{i}))42 acc := &testAccount{address: common.BytesToAddress([]byte{i})}43 obj.AddBalance(big.NewInt(int64(11 * i)))44 acc.balance = big.NewInt(int64(11 * i))45 obj.SetNonce(uint64(42 * i))46 acc.nonce = uint64(42 * i)47 if i%3 == 0 {48 obj.SetCode(crypto.Keccak256Hash([]byte{i, i, i, i, i}), []byte{i, i, i, i, i})49 acc.code = []byte{i, i, i, i, i}50 }51 state.updateStateObject(obj)52 accounts = append(accounts, acc)53 }54 root, _ := state.Commit(false)55 // Return the generated state56 return db, root, accounts57}58// checkStateAccounts cross references a reconstructed state with an expected59// account array.60func checkStateAccounts(t *testing.T, db ethdb.Database, root common.Hash, accounts []*testAccount) {61 // Check root availability and state contents62 state, err := New(root, NewDatabase(db))63 if err != nil {64 t.Fatalf("failed to create state trie at %x: %v", root, err)65 }66 if err := checkStateConsistency(db, root); err != nil {67 t.Fatalf("inconsistent state trie at %x: %v", root, err)68 }69 for i, acc := range accounts {70 if balance := state.GetBalance(acc.address); balance.Cmp(acc.balance) != 0 {71 t.Errorf("account %d: balance mismatch: have %v, want %v", i, balance, acc.balance)72 }73 if nonce := state.GetNonce(acc.address); nonce != acc.nonce {74 t.Errorf("account %d: nonce mismatch: have %v, want %v", i, nonce, acc.nonce)75 }76 if code := state.GetCode(acc.address); !bytes.Equal(code, acc.code) {77 t.Errorf("account %d: code mismatch: have %x, want %x", i, code, acc.code)78 }79 }80}81// checkTrieConsistency checks that all nodes in a (sub-)trie are indeed present.82func checkTrieConsistency(db ethdb.Database, root common.Hash) error {83 if v, _ := db.Get(root[:]); v == nil {84 return nil // Consider a non existent state consistent.85 }86 trie, err := trie.New(root, trie.NewDatabase(db))87 if err != nil {88 return err89 }90 it := trie.NodeIterator(nil)91 for it.Next(true) {92 }93 return it.Error()94}95// checkStateConsistency checks that all data of a state root is present.96func checkStateConsistency(db ethdb.Database, root common.Hash) error {97 // Create and iterate a state trie rooted in a sub-node98 if _, err := db.Get(root.Bytes()); err != nil {99 return nil // Consider a non existent state consistent.100 }101 state, err := New(root, NewDatabase(db))102 if err != nil {103 return err104 }105 it := NewNodeIterator(state)106 for it.Next() {107 }108 return it.Error109}110// Tests that an empty state is not scheduled for syncing.111func TestEmptyStateSync(t *testing.T) {112 empty := common.HexToHash("56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421")113 if req := NewStateSync(empty, ethdb.NewMemDatabase()).Missing(1); len(req) != 0 {114 t.Errorf("content requested for empty state: %v", req)115 }116}117// Tests that given a root hash, a state can sync iteratively on a single thread,118// requesting retrieval tasks and returning all of them in one go.119func TestIterativeStateSyncIndividual(t *testing.T) { testIterativeStateSync(t, 1) }120func TestIterativeStateSyncBatched(t *testing.T) { testIterativeStateSync(t, 100) }121func testIterativeStateSync(t *testing.T, batch int) {122 // Create a random state to copy123 srcDb, srcRoot, srcAccounts := makeTestState()124 // Create a destination state and sync with the scheduler125 dstDb := ethdb.NewMemDatabase()126 sched := NewStateSync(srcRoot, dstDb)127 queue := append([]common.Hash{}, sched.Missing(batch)...)128 for len(queue) > 0 {129 results := make([]trie.SyncResult, len(queue))130 for i, hash := range queue {131 data, err := srcDb.TrieDB().Node(hash)132 if err != nil {133 t.Fatalf("failed to retrieve node data for %x", hash)134 }135 results[i] = trie.SyncResult{Hash: hash, Data: data}136 }137 if _, index, err := sched.Process(results); err != nil {138 t.Fatalf("failed to process result #%d: %v", index, err)139 }140 if index, err := sched.Commit(dstDb); err != nil {141 t.Fatalf("failed to commit data #%d: %v", index, err)142 }143 queue = append(queue[:0], sched.Missing(batch)...)144 }145 // Cross check that the two states are in sync146 checkStateAccounts(t, dstDb, srcRoot, srcAccounts)147}148// Tests that the trie scheduler can correctly reconstruct the state even if only149// partial results are returned, and the others sent only later.150func TestIterativeDelayedStateSync(t *testing.T) {151 // Create a random state to copy152 srcDb, srcRoot, srcAccounts := makeTestState()153 // Create a destination state and sync with the scheduler154 dstDb := ethdb.NewMemDatabase()155 sched := NewStateSync(srcRoot, dstDb)156 queue := append([]common.Hash{}, sched.Missing(0)...)157 for len(queue) > 0 {158 // Sync only half of the scheduled nodes159 results := make([]trie.SyncResult, len(queue)/2+1)160 for i, hash := range queue[:len(results)] {161 data, err := srcDb.TrieDB().Node(hash)162 if err != nil {163 t.Fatalf("failed to retrieve node data for %x", hash)164 }165 results[i] = trie.SyncResult{Hash: hash, Data: data}166 }167 if _, index, err := sched.Process(results); err != nil {168 t.Fatalf("failed to process result #%d: %v", index, err)169 }170 if index, err := sched.Commit(dstDb); err != nil {171 t.Fatalf("failed to commit data #%d: %v", index, err)172 }173 queue = append(queue[len(results):], sched.Missing(0)...)174 }175 // Cross check that the two states are in sync176 checkStateAccounts(t, dstDb, srcRoot, srcAccounts)177}178// Tests that given a root hash, a trie can sync iteratively on a single thread,179// requesting retrieval tasks and returning all of them in one go, however in a180// random order.181func TestIterativeRandomStateSyncIndividual(t *testing.T) { testIterativeRandomStateSync(t, 1) }182func TestIterativeRandomStateSyncBatched(t *testing.T) { testIterativeRandomStateSync(t, 100) }183func testIterativeRandomStateSync(t *testing.T, batch int) {184 // Create a random state to copy185 srcDb, srcRoot, srcAccounts := makeTestState()186 // Create a destination state and sync with the scheduler187 dstDb := ethdb.NewMemDatabase()188 sched := NewStateSync(srcRoot, dstDb)189 queue := make(map[common.Hash]struct{})190 for _, hash := range sched.Missing(batch) {191 queue[hash] = struct{}{}192 }193 for len(queue) > 0 {194 // Fetch all the queued nodes in a random order195 results := make([]trie.SyncResult, 0, len(queue))196 for hash := range queue {197 data, err := srcDb.TrieDB().Node(hash)198 if err != nil {199 t.Fatalf("failed to retrieve node data for %x", hash)200 }201 results = append(results, trie.SyncResult{Hash: hash, Data: data})202 }203 // Feed the retrieved results back and queue new tasks204 if _, index, err := sched.Process(results); err != nil {205 t.Fatalf("failed to process result #%d: %v", index, err)206 }207 if index, err := sched.Commit(dstDb); err != nil {208 t.Fatalf("failed to commit data #%d: %v", index, err)209 }210 queue = make(map[common.Hash]struct{})211 for _, hash := range sched.Missing(batch) {212 queue[hash] = struct{}{}213 }214 }215 // Cross check that the two states are in sync216 checkStateAccounts(t, dstDb, srcRoot, srcAccounts)217}218// Tests that the trie scheduler can correctly reconstruct the state even if only219// partial results are returned (Even those randomly), others sent only later.220func TestIterativeRandomDelayedStateSync(t *testing.T) {221 // Create a random state to copy222 srcDb, srcRoot, srcAccounts := makeTestState()223 // Create a destination state and sync with the scheduler224 dstDb := ethdb.NewMemDatabase()225 sched := NewStateSync(srcRoot, dstDb)226 queue := make(map[common.Hash]struct{})227 for _, hash := range sched.Missing(0) {228 queue[hash] = struct{}{}229 }230 for len(queue) > 0 {231 // Sync only half of the scheduled nodes, even those in random order232 results := make([]trie.SyncResult, 0, len(queue)/2+1)233 for hash := range queue {234 delete(queue, hash)235 data, err := srcDb.TrieDB().Node(hash)236 if err != nil {237 t.Fatalf("failed to retrieve node data for %x", hash)238 }239 results = append(results, trie.SyncResult{Hash: hash, Data: data})240 if len(results) >= cap(results) {241 break242 }243 }244 // Feed the retrieved results back and queue new tasks245 if _, index, err := sched.Process(results); err != nil {246 t.Fatalf("failed to process result #%d: %v", index, err)247 }248 if index, err := sched.Commit(dstDb); err != nil {249 t.Fatalf("failed to commit data #%d: %v", index, err)250 }251 for _, hash := range sched.Missing(0) {252 queue[hash] = struct{}{}253 }254 }255 // Cross check that the two states are in sync256 checkStateAccounts(t, dstDb, srcRoot, srcAccounts)257}258// Tests that at any point in time during a sync, only complete sub-tries are in259// the database.260func TestIncompleteStateSync(t *testing.T) {261 // Create a random state to copy262 srcDb, srcRoot, srcAccounts := makeTestState()263 checkTrieConsistency(srcDb.TrieDB().DiskDB().(ethdb.Database), srcRoot)264 // Create a destination state and sync with the scheduler265 dstDb := ethdb.NewMemDatabase()266 sched := NewStateSync(srcRoot, dstDb)267 added := []common.Hash{}268 queue := append([]common.Hash{}, sched.Missing(1)...)269 for len(queue) > 0 {270 // Fetch a batch of state nodes271 results := make([]trie.SyncResult, len(queue))272 for i, hash := range queue {273 data, err := srcDb.TrieDB().Node(hash)274 if err != nil {275 t.Fatalf("failed to retrieve node data for %x", hash)276 }277 results[i] = trie.SyncResult{Hash: hash, Data: data}278 }279 // Process each of the state nodes280 if _, index, err := sched.Process(results); err != nil {281 t.Fatalf("failed to process result #%d: %v", index, err)282 }283 if index, err := sched.Commit(dstDb); err != nil {284 t.Fatalf("failed to commit data #%d: %v", index, err)285 }286 for _, result := range results {287 added = append(added, result.Hash)288 }289 // Check that all known sub-tries added so far are complete or missing entirely.290 checkSubtries:291 for _, hash := range added {292 for _, acc := range srcAccounts {293 if hash == crypto.Keccak256Hash(acc.code) {294 continue checkSubtries // skip trie check of code nodes.295 }296 }297 // Can't use checkStateConsistency here because subtrie keys may have odd298 // length and crash in LeafKey.299 if err := checkTrieConsistency(dstDb, hash); err != nil {300 t.Fatalf("state inconsistent: %v", err)301 }302 }303 // Fetch the next batch to retrieve304 queue = append(queue[:0], sched.Missing(1)...)305 }306 // Sanity check that removing any node from the database is detected307 for _, node := range added[1:] {308 key := node.Bytes()309 value, _ := dstDb.Get(key)310 dstDb.Delete(key)311 if err := checkStateConsistency(dstDb, added[0]); err == nil {312 t.Fatalf("trie inconsistency not caught, missing: %x", key)313 }314 dstDb.Put(key, value)315 }316}...
coordinator_test.go
Source:coordinator_test.go
1package coordinator2import (3 "errors"4 "net/http"5 "testing"6 "github.com/stretchr/testify/mock"7 _testing "github.com/decentraland/webrtc-broker/internal/testing"8 "github.com/decentraland/webrtc-broker/internal/ws"9 protocol "github.com/decentraland/webrtc-broker/pkg/protocol"10 "github.com/golang/protobuf/proto"11 "github.com/stretchr/testify/require"12)13type MockWebsocket = _testing.MockWebsocket14type mockUpgrader struct {15 mock.Mock16}17func (m *mockUpgrader) Upgrade(w http.ResponseWriter, r *http.Request) (ws.IWebsocket, error) {18 args := m.Called(w, r)19 return args.Get(0).(ws.IWebsocket), args.Error(1)20}21type mockCoordinatorAuthenticator struct{ mock.Mock }22func (m *mockCoordinatorAuthenticator) AuthenticateFromURL(role protocol.Role, r *http.Request) (bool, error) {23 args := m.Called(role, r)24 return args.Bool(0), args.Error(1)25}26func makeDefaultServerSelector() *DefaultServerSelector {27 return &DefaultServerSelector{ServerAliases: make(map[uint64]bool)}28}29func makeTestState() *State {30 config := Config{ServerSelector: makeDefaultServerSelector()}31 return MakeState(&config)32}33func TestUpgradeRequest(t *testing.T) {34 testSuccessfulUpgrade := func(t *testing.T, req *http.Request, expectedRole protocol.Role) {35 auth := &mockCoordinatorAuthenticator{}36 auth.On("AuthenticateFromURL", expectedRole, mock.Anything).Return(true, nil).Once()37 config := Config{38 ServerSelector: makeDefaultServerSelector(),39 Auth: auth,40 }41 ws := &MockWebsocket{}42 upgrader := &mockUpgrader{}43 state := MakeState(&config)44 state.upgrader = upgrader45 upgrader.On("Upgrade", nil, req).Return(ws, nil)46 _, err := UpgradeRequest(state, expectedRole, nil, req)47 require.NoError(t, err)48 upgrader.AssertExpectations(t)49 }50 t.Run("upgrade discover request", func(t *testing.T) {51 req, err := http.NewRequest("GET", "/discover?method=fake", nil)52 require.NoError(t, err)53 testSuccessfulUpgrade(t, req, protocol.Role_COMMUNICATION_SERVER)54 })55 t.Run("upgrade connect request", func(t *testing.T) {56 req, err := http.NewRequest("GET", "/connect?method=fake", nil)57 require.NoError(t, err)58 testSuccessfulUpgrade(t, req, protocol.Role_CLIENT)59 })60 t.Run("upgrade request (unauthorized)", func(t *testing.T) {61 auth := &mockCoordinatorAuthenticator{}62 auth.On("AuthenticateFromURL", protocol.Role_COMMUNICATION_SERVER, mock.Anything).Return(false, nil).Once()63 config := Config{64 ServerSelector: makeDefaultServerSelector(),65 Auth: auth,66 }67 upgrader := &mockUpgrader{}68 state := MakeState(&config)69 state.upgrader = upgrader70 req, err := http.NewRequest("GET", "/discover?method=fake", nil)71 require.NoError(t, err)72 _, err = UpgradeRequest(state, protocol.Role_COMMUNICATION_SERVER, nil, req)73 require.Equal(t, err, ErrUnauthorized)74 upgrader.AssertExpectations(t)75 })76}77func TestReadPump(t *testing.T) {78 t.Run("webrtc message", func(t *testing.T) {79 state := makeTestState()80 defer closeState(state)81 conn := &MockWebsocket{}82 p := makePeer(state, conn, protocol.Role_COMMUNICATION_SERVER)83 p.Alias = 184 msg := &protocol.WebRtcMessage{85 Type: protocol.MessageType_WEBRTC_ANSWER,86 ToAlias: 2,87 }88 encodedMsg, err := proto.Marshal(msg)89 require.NoError(t, err)90 conn.91 On("Close").Return(nil).Once().92 On("ReadMessage").Return(encodedMsg, nil).Once().93 On("ReadMessage").Return([]byte{}, errors.New("stop")).Once().94 On("SetReadLimit", mock.Anything).Return(nil).Once().95 On("SetReadDeadline", mock.Anything).Return(nil).Once().96 On("SetPongHandler", mock.Anything).Once()97 go readPump(state, p)98 unregistered := <-state.unregister99 require.Equal(t, p, unregistered)100 require.Len(t, state.signalingQueue, 1)101 in := <-state.signalingQueue102 require.Equal(t, msg.Type, in.msgType)103 require.Equal(t, p, in.from, p)104 require.Equal(t, uint64(2), in.toAlias)105 require.NoError(t, proto.Unmarshal(in.bytes, msg))106 require.Equal(t, uint64(1), msg.FromAlias)107 conn.AssertExpectations(t)108 })109 t.Run("connect message (with alias)", func(t *testing.T) {110 state := makeTestState()111 defer closeState(state)112 conn := &MockWebsocket{}113 p := makePeer(state, conn, protocol.Role_COMMUNICATION_SERVER)114 p.Alias = 1115 msg := &protocol.ConnectMessage{116 Type: protocol.MessageType_CONNECT,117 ToAlias: 2,118 }119 encodedMsg, err := proto.Marshal(msg)120 require.NoError(t, err)121 conn.122 On("Close").Return(nil).Once().123 On("ReadMessage").Return(encodedMsg, nil).Once().124 On("ReadMessage").Return([]byte{}, errors.New("stop")).Once().125 On("SetReadLimit", mock.Anything).Return(nil).Once().126 On("SetReadDeadline", mock.Anything).Return(nil).Once().127 On("SetPongHandler", mock.Anything).Once()128 go readPump(state, p)129 unregistered := <-state.unregister130 require.Equal(t, p, unregistered)131 require.Len(t, state.signalingQueue, 1)132 in := <-state.signalingQueue133 require.Equal(t, msg.Type, in.msgType)134 require.Equal(t, p, in.from)135 require.Equal(t, uint64(2), in.toAlias)136 })137}138func TestWritePump(t *testing.T) {139 msg, err := proto.Marshal(&protocol.ConnectMessage{})140 require.NoError(t, err)141 t.Run("success", func(t *testing.T) {142 state := makeTestState()143 defer closeState(state)144 conn := &MockWebsocket{}145 conn.146 On("WriteMessage", msg).Return(nil).Once().147 On("WriteMessage", msg).Return(errors.New("stop")).Once()148 p := makePeer(state, conn, protocol.Role_CLIENT)149 p.Alias = 1150 p.sendCh <- msg151 p.sendCh <- msg152 p.writePump(state)153 conn.AssertExpectations(t)154 })155 t.Run("first write error", func(t *testing.T) {156 state := makeTestState()157 defer closeState(state)158 conn := &MockWebsocket{}159 conn.160 On("WriteMessage", msg).Return(errors.New("error")).Once()161 p := makePeer(state, conn, protocol.Role_CLIENT)162 p.Alias = 1163 p.sendCh <- msg164 p.sendCh <- msg165 p.writePump(state)166 conn.AssertExpectations(t)167 })168}169func TestConnectCommServer(t *testing.T) {170 forRole := func(t *testing.T, role protocol.Role) {171 state := makeTestState()172 defer closeState(state)173 conn := &MockWebsocket{}174 conn.175 On("Close").Return(nil).Once().176 On("ReadMessage").Return([]byte{}, nil).Maybe().177 On("WriteCloseMessage").Return(nil).Maybe().178 On("SetReadLimit", mock.Anything).Return(nil).Maybe().179 On("SetReadDeadline", mock.Anything).Return(nil).Maybe().180 On("SetPongHandler", mock.Anything).Maybe()181 ConnectCommServer(state, conn, role)182 p := <-state.registerCommServer183 p.close()184 require.Equal(t, p.role, role)185 conn.AssertExpectations(t)186 }187 t.Run("communication server role", func(t *testing.T) {188 forRole(t, protocol.Role_COMMUNICATION_SERVER)189 })190 t.Run("communication server hub role", func(t *testing.T) {191 forRole(t, protocol.Role_COMMUNICATION_SERVER_HUB)192 })193}194func TestConnectClient(t *testing.T) {195 state := makeTestState()196 defer closeState(state)197 conn := &MockWebsocket{}198 conn.199 On("Close").Return(nil).Once().200 On("ReadMessage").Return([]byte{}, nil).Maybe().201 On("WriteCloseMessage").Return(nil).Maybe().202 On("SetReadLimit", mock.Anything).Return(nil).Maybe().203 On("SetReadDeadline", mock.Anything).Return(nil).Maybe().204 On("SetPongHandler", mock.Anything).Maybe()205 ConnectClient(state, conn)206 p := <-state.registerClient207 p.close()208 require.Equal(t, p.role, protocol.Role_CLIENT)209 conn.AssertExpectations(t)210}211func TestRegisterCommServer(t *testing.T) {212 state := makeTestState()213 defer closeState(state)214 conn := &MockWebsocket{}215 conn.On("Close").Return(nil).Once()216 s := makePeer(state, conn, protocol.Role_COMMUNICATION_SERVER)217 conn2 := &MockWebsocket{}218 conn2.On("Close").Return(nil).Once()219 s2 := makePeer(state, conn2, protocol.Role_COMMUNICATION_SERVER)220 state.registerCommServer <- s221 state.registerCommServer <- s2222 go Start(state)223 welcomeMessage := &protocol.WelcomeMessage{}224 bytes := <-s.sendCh225 require.NoError(t, proto.Unmarshal(bytes, welcomeMessage))226 require.Equal(t, welcomeMessage.Type, protocol.MessageType_WELCOME)227 require.NotEmpty(t, welcomeMessage.Alias)228 bytes = <-s2.sendCh229 require.NoError(t, proto.Unmarshal(bytes, welcomeMessage))230 require.Equal(t, welcomeMessage.Type, protocol.MessageType_WELCOME)231 require.NotEmpty(t, welcomeMessage.Alias)232 state.stop <- true233 s.close()234 s2.close()235 conn.AssertExpectations(t)236 conn2.AssertExpectations(t)237}238func TestRegisterClient(t *testing.T) {239 state := makeTestState()240 defer closeState(state)241 conn := &MockWebsocket{}242 conn.On("Close").Return(nil).Once()243 c := makePeer(state, conn, protocol.Role_CLIENT)244 conn2 := &MockWebsocket{}245 conn2.On("Close").Return(nil).Once()246 c2 := makePeer(state, conn2, protocol.Role_CLIENT)247 state.registerClient <- c248 state.registerClient <- c2249 go Start(state)250 welcomeMessage := &protocol.WelcomeMessage{}251 bytes := <-c.sendCh252 require.NoError(t, proto.Unmarshal(bytes, welcomeMessage))253 require.Equal(t, welcomeMessage.Type, protocol.MessageType_WELCOME)254 require.NotEmpty(t, welcomeMessage.Alias)255 bytes = <-c2.sendCh256 require.NoError(t, proto.Unmarshal(bytes, welcomeMessage))257 require.Equal(t, welcomeMessage.Type, protocol.MessageType_WELCOME)258 require.NotEmpty(t, welcomeMessage.Alias)259 state.stop <- true260 c.close()261 c2.close()262 conn.AssertExpectations(t)263 conn2.AssertExpectations(t)264}265func TestUnregister(t *testing.T) {266 selector := makeDefaultServerSelector()267 config := Config{ServerSelector: selector}268 state := MakeState(&config)269 state.unregister = make(chan *Peer)270 defer closeState(state)271 conn := &MockWebsocket{}272 s := makePeer(state, conn, protocol.Role_COMMUNICATION_SERVER)273 s.Alias = 1274 state.Peers[s.Alias] = s275 selector.ServerAliases[s.Alias] = true276 conn2 := &MockWebsocket{}277 s2 := makePeer(state, conn2, protocol.Role_COMMUNICATION_SERVER)278 s2.Alias = 2279 state.Peers[s2.Alias] = s2280 selector.ServerAliases[s2.Alias] = true281 go Start(state)282 state.unregister <- s283 state.unregister <- s2284 state.stop <- true285 require.Len(t, state.Peers, 0)286 require.Len(t, selector.ServerAliases, 0)287}288func TestSignaling(t *testing.T) {289 bytes, err := proto.Marshal(&protocol.WebRtcMessage{})290 require.NoError(t, err)291 t.Run("success", func(t *testing.T) {292 state := makeTestState()293 defer closeState(state)294 conn := &MockWebsocket{}295 p := makePeer(state, conn, protocol.Role_CLIENT)296 p.Alias = 1297 conn2 := &MockWebsocket{}298 p2 := makePeer(state, conn2, protocol.Role_CLIENT)299 p2.Alias = 2300 state.Peers[p.Alias] = p301 state.Peers[p2.Alias] = p2302 state.signalingQueue <- &inMessage{303 msgType: protocol.MessageType_WEBRTC_ANSWER,304 from: p,305 bytes: bytes,306 toAlias: p2.Alias,307 }308 state.signalingQueue <- &inMessage{309 msgType: protocol.MessageType_WEBRTC_ANSWER,310 from: p2,311 bytes: bytes,312 toAlias: p.Alias,313 }314 go Start(state)315 <-p.sendCh316 <-p2.sendCh317 state.stop <- true318 })319 t.Run("on peer not found", func(t *testing.T) {320 state := makeTestState()321 state.signalingQueue = make(chan *inMessage)322 defer closeState(state)323 conn := &MockWebsocket{}324 p := makePeer(state, conn, protocol.Role_CLIENT)325 p.Alias = 1326 state.Peers[p.Alias] = p327 go Start(state)328 state.signalingQueue <- &inMessage{329 msgType: protocol.MessageType_WEBRTC_ANSWER,330 from: p,331 bytes: bytes,332 toAlias: 2,333 }334 state.stop <- true335 })336 t.Run("on channel closed", func(t *testing.T) {337 state := makeTestState()338 state.signalingQueue = make(chan *inMessage)339 defer closeState(state)340 conn := &MockWebsocket{}341 p := makePeer(state, conn, protocol.Role_CLIENT)342 p.Alias = 1343 conn2 := &MockWebsocket{}344 conn2.On("Close").Return(nil).Once()345 p2 := makePeer(state, conn2, protocol.Role_CLIENT)346 p2.Alias = 2347 p2.close()348 state.Peers[p.Alias] = p349 state.Peers[p2.Alias] = p2350 go Start(state)351 state.signalingQueue <- &inMessage{352 msgType: protocol.MessageType_WEBRTC_ANSWER,353 from: p,354 bytes: bytes,355 toAlias: p2.Alias,356 }357 state.stop <- true358 })359}...
state_test.go
Source:state_test.go
1package state2import (3 "bytes"4 "encoding/binary"5 "encoding/hex"6 "reflect"7 "testing"8 "github.com/stretchr/testify/assert"9 "0chain.net/core/encryption"10 "0chain.net/core/util"11)12func makeTestState() *State {13 rHash := encryption.RawHash("txn hash")14 return &State{15 TxnHash: hex.EncodeToString(rHash),16 TxnHashBytes: rHash,17 Round: 1,18 Balance: 5,19 }20}21func TestState_GetHash(t *testing.T) {22 t.Parallel()23 st := makeTestState()24 type fields struct {25 TxnHash string26 TxnHashBytes []byte27 Round int6428 Balance Balance29 }30 tests := []struct {31 name string32 fields fields33 want string34 }{35 {36 name: "OK",37 fields: fields(*st),38 want: util.ToHex(st.GetHashBytes()),39 },40 }41 for _, tt := range tests {42 tt := tt43 t.Run(tt.name, func(t *testing.T) {44 t.Parallel()45 s := &State{46 TxnHash: tt.fields.TxnHash,47 TxnHashBytes: tt.fields.TxnHashBytes,48 Round: tt.fields.Round,49 Balance: tt.fields.Balance,50 }51 if got := s.GetHash(); got != tt.want {52 t.Errorf("GetHash() = %v, want %v", got, tt.want)53 }54 })55 }56}57func TestState_GetHashBytes(t *testing.T) {58 t.Parallel()59 st := makeTestState()60 type fields struct {61 TxnHash string62 TxnHashBytes []byte63 Round int6464 Balance Balance65 }66 tests := []struct {67 name string68 fields fields69 want []byte70 }{71 {72 name: "OK",73 fields: fields(*st),74 want: encryption.RawHash(st.Encode()),75 },76 }77 for _, tt := range tests {78 tt := tt79 t.Run(tt.name, func(t *testing.T) {80 t.Parallel()81 s := &State{82 TxnHash: tt.fields.TxnHash,83 TxnHashBytes: tt.fields.TxnHashBytes,84 Round: tt.fields.Round,85 Balance: tt.fields.Balance,86 }87 if got := s.GetHashBytes(); !reflect.DeepEqual(got, tt.want) {88 t.Errorf("GetHashBytes() = %v, want %v", got, tt.want)89 }90 })91 }92}93func TestState_Encode(t *testing.T) {94 t.Parallel()95 st := makeTestState()96 type fields struct {97 TxnHash string98 TxnHashBytes []byte99 Round int64100 Balance Balance101 }102 tests := []struct {103 name string104 fields fields105 want []byte106 }{107 {108 name: "OK",109 fields: fields(*st),110 want: func() []byte {111 buf := bytes.NewBuffer(nil)112 buf.Write(st.TxnHashBytes)113 if err := binary.Write(buf, binary.LittleEndian, st.Round); err != nil {114 t.Fatal(err)115 }116 if err := binary.Write(buf, binary.LittleEndian, st.Balance); err != nil {117 t.Fatal(err)118 }119 return buf.Bytes()120 }(),121 },122 }123 for _, tt := range tests {124 tt := tt125 t.Run(tt.name, func(t *testing.T) {126 t.Parallel()127 s := &State{128 TxnHash: tt.fields.TxnHash,129 TxnHashBytes: tt.fields.TxnHashBytes,130 Round: tt.fields.Round,131 Balance: tt.fields.Balance,132 }133 if got := s.Encode(); !reflect.DeepEqual(got, tt.want) {134 t.Errorf("Encode() = %v, want %v", got, tt.want)135 }136 })137 }138}139func TestState_Decode(t *testing.T) {140 t.Parallel()141 st := makeTestState()142 st.TxnHash = ""143 blob := st.Encode()144 type fields struct {145 TxnHash string146 TxnHashBytes []byte147 Round int64148 Balance Balance149 }150 type args struct {151 data []byte152 }153 tests := []struct {154 name string155 fields fields156 args args157 wantErr bool158 want *State159 }{160 {161 name: "OK",162 args: args{data: blob},163 wantErr: false,164 want: st,165 },166 }167 for _, tt := range tests {168 tt := tt169 t.Run(tt.name, func(t *testing.T) {170 t.Parallel()171 s := &State{172 TxnHash: tt.fields.TxnHash,173 TxnHashBytes: tt.fields.TxnHashBytes,174 Round: tt.fields.Round,175 Balance: tt.fields.Balance,176 }177 if err := s.Decode(tt.args.data); (err != nil) != tt.wantErr {178 t.Errorf("Decode() error = %v, wantErr %v", err, tt.wantErr)179 }180 assert.Equal(t, tt.want, s)181 })182 }183}184func TestState_ComputeProperties(t *testing.T) {185 t.Parallel()186 st := makeTestState()187 type fields struct {188 TxnHash string189 TxnHashBytes []byte190 Round int64191 Balance Balance192 }193 tests := []struct {194 name string195 fields fields196 want *State197 }{198 {199 name: "OK",200 fields: fields{201 TxnHashBytes: st.TxnHashBytes,202 Round: st.Round,203 Balance: st.Balance,204 },205 want: st,206 },207 }208 for _, tt := range tests {209 tt := tt210 t.Run(tt.name, func(t *testing.T) {211 t.Parallel()212 s := &State{213 TxnHash: tt.fields.TxnHash,214 TxnHashBytes: tt.fields.TxnHashBytes,215 Round: tt.fields.Round,216 Balance: tt.fields.Balance,217 }218 s.ComputeProperties()219 assert.Equal(t, tt.want, s)220 })221 }222}223func TestState_Set(t *testing.T) {224 t.Parallel()225 st := makeTestState()226 type fields struct {227 TxnHash string228 TxnHashBytes []byte229 Round int64230 Balance Balance231 }232 type args struct {233 round int64234 txnHash string235 }236 tests := []struct {237 name string238 fields fields239 args args240 want *State241 wantErr bool242 }{243 {244 name: "OK",245 fields: fields{246 Balance: 5,247 },248 args: args{round: st.Round, txnHash: st.TxnHash},249 want: st,250 },251 {252 name: "Invalid_Txn_Hash_ERR",253 args: args{txnHash: "!"},254 want: st,255 wantErr: true,256 },257 }258 for _, tt := range tests {259 tt := tt260 t.Run(tt.name, func(t *testing.T) {261 t.Parallel()262 s := &State{263 TxnHash: tt.fields.TxnHash,264 TxnHashBytes: tt.fields.TxnHashBytes,265 Round: tt.fields.Round,266 Balance: tt.fields.Balance,267 }268 s.SetRound(tt.args.round)269 err := s.SetTxnHash(tt.args.txnHash)270 if !tt.wantErr {271 assert.NoError(t, err)272 assert.Equal(t, tt.want, s)273 } else {274 assert.Error(t, err)275 }276 })277 }278}279func TestDeserializer_Deserialize(t *testing.T) {280 t.Parallel()281 st := makeTestState()282 st.TxnHash = ""283 sv := util.SecureSerializableValue{Buffer: st.Encode()}284 type args struct {285 sv util.Serializable286 }287 tests := []struct {288 name string289 args args290 want util.Serializable291 }{292 {293 name: "OK",294 args: args{sv: &sv},295 want: st,296 },297 }298 for _, tt := range tests {299 tt := tt300 t.Run(tt.name, func(t *testing.T) {301 t.Parallel()302 bd := &Deserializer{}303 got := bd.Deserialize(tt.args.sv)304 assert.Equal(t, tt.want, got)305 })306 }307}...
MakeTestState
Using AI Code Generation
1import (2func main() {3 db, _ := ethdb.NewMemDatabase()4 genesis := core.GenesisBlockForTesting(db, common.Address{}, big.NewInt(1000000000000000000))5 statedb, _ := state.New(genesis.Root(), state.NewDatabase(db))6 statedb.AddBalance(common.HexToAddress("0x1234567890123456789012345678901234567890"), big.NewInt(1000000000000000000))7 statedb.AddBalance(common.HexToAddress("0x1234567890123456789012345678901234567891"), big.NewInt(1000000000000000000))8 statedb.AddBalance(common.HexToAddress("0x1234567890123456789012345678901234567892"), big.NewInt(1000000000000000000))9 statedb.AddBalance(common.HexToAddress("0x1234567890123456789012345678901234567893"), big.NewInt(1000000000000000000))10 statedb.AddBalance(common.HexToAddress("0x1234567890123456789012345678901234567894"), big.NewInt(1000000000000000000))11 statedb.AddBalance(common.HexToAddress("0x1234567890123456789012345678901234567895"), big.NewInt(1000000000000000000))12 statedb.AddBalance(common.HexToAddress("0x1234567890123456789012345678901234567896"), big.NewInt(1000000000000000000))13 statedb.AddBalance(common.HexToAddress("0x1234567890123456789012345678901234567897"), big.NewInt(1000000000000000000))14 statedb.AddBalance(common.HexToAddress("0x1234567890123456789012345678901234567898"), big.NewInt(1000000000000000000))15 statedb.AddBalance(common.HexToAddress("0x1234567890123456789012345678901234567899"), big.NewInt(
MakeTestState
Using AI Code Generation
1import (2func main() {3 db, _ := ethdb.NewMemDatabase()4 statedb, _ := state.New(common.Hash{}, state.NewDatabase(db))5 statedb.CreateAccount(common.HexToAddress("0x1234567890123456789012345678901234567890"))6 statedb.SetCode(common.HexToAddress("0x123456789012345
MakeTestState
Using AI Code Generation
1import (2func main() {3 fmt.Println("Hello, playground")4}5import (6type State struct {7}8func (s *State) MakeTestState() {9}10func main() {11 fmt.Println("Hello, playground")12}13import (14func main() {15 fmt.Println("Hello, playground")16}17import (18func main() {19 fmt.Println("Hello, playground")20}21import (22func main() {23 fmt.Println("Hello, playground")24}25import (26func main() {27 fmt.Println("Hello, playground")28}29import (30func main() {31 fmt.Println("Hello, playground")32}33import (34func main() {35 fmt.Println("Hello, playground")36}37import (38func main() {39 fmt.Println("Hello, playground")40}41import (42func main() {43 fmt.Println("Hello, playground")44}45import (46func main() {47 fmt.Println("Hello, playground")48}49import (50func main() {51 fmt.Println("Hello, playground")52}
MakeTestState
Using AI Code Generation
1import (2func main() {3 testState := state.MakeTestState()4 fmt.Println(testState)5}6type TestState struct {7}8func MakeTestState() TestState {9 return TestState{Num: 2}10}11import "testing"12func TestMakeTestState(t *testing.T) {13 testState := MakeTestState()14 if testState.Num != 2 {15 t.Error("Expected 2, got ", testState.Num)16 }17}18./2.go:6: imported and not used: "fmt"
MakeTestState
Using AI Code Generation
1import (2func main() {3 fmt.Println("Hello, playground")4 testState := state.MakeTestState()5 fmt.Println(testState)6}7import (8func main() {9 fmt.Println("Hello, playground")10 testState := state.MakeTestState()11 fmt.Println(testState)12}13import (14type State struct {15}16func MakeTestState() State {17 return State{Name: "test"}18}19import (20type State struct {21}22func MakeTestState() State {23 return State{Name: "test"}24}25import (26type State struct {27}28func MakeTestState() State {29 return State{Name: "test"}30}31./1.go:8: cannot use state.MakeTestState() (type state.State) as type state.State in assignment32./1.go:8: cannot use state.MakeTestState() (type state.State) as type state.State in assignment
MakeTestState
Using AI Code Generation
1import (2func main() {3 fmt.Println("Hello, playground")4 testState := state.MakeTestState()5 testState.PrintState()6}7import (8type State struct {9}10func MakeTestState() *State {11 return &State{Count: 5, Time: time.Now()}12}13func (s *State) PrintState() {14 fmt.Println("Count:", s.Count, "Time:", s.Time)15}
MakeTestState
Using AI Code Generation
1import (2func main() {3 fmt.Println("Hello, playground")4 s.MakeTestState()5 fmt.Println("State is ", s)6}7State is {0 0 0 0 0 0 0 0 0}
MakeTestState
Using AI Code Generation
1import "fmt"2import "mytest"3func main() {4 state.MakeTestState()5 fmt.Println(state)6}7type State struct {8}9func (state *State) MakeTestState() {10}
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!