github.com/status-im/status-go@v1.1.0/services/ext/mailservers/connmonitor_test.go (about) 1 package mailservers 2 3 import ( 4 "fmt" 5 "sort" 6 "testing" 7 "time" 8 9 "github.com/stretchr/testify/require" 10 11 "github.com/ethereum/go-ethereum/p2p/enode" 12 13 "github.com/status-im/status-go/eth-node/types" 14 "github.com/status-im/status-go/t/utils" 15 ) 16 17 func TestUsedConnectionPersisted(t *testing.T) { 18 nodes := make([]*enode.Node, 2) 19 fillWithRandomNodes(t, nodes) 20 21 cache := newInMemCache(t) 22 store := NewPeerStore(cache) 23 require.NoError(t, store.Update(nodes)) 24 whisperMock := newFakeEnvelopesEvents() 25 monitor := NewLastUsedConnectionMonitor(store, cache, whisperMock) 26 monitor.Start() 27 28 // Send a confirmation that we received history from one of the peers. 29 select { 30 case whisperMock.input <- types.EnvelopeEvent{ 31 Event: types.EventMailServerRequestCompleted, Peer: types.EnodeID(nodes[0].ID())}: 32 case <-time.After(time.Second): 33 require.FailNow(t, "can't send a 'completed' event") 34 } 35 36 // Wait until records will be updated in the cache. 37 require.NoError(t, utils.Eventually(func() error { 38 records, err := cache.LoadAll() 39 if err != nil { 40 return err 41 } 42 if lth := len(records); lth != 2 { 43 return fmt.Errorf("unexpected length of all records stored in the cache. expected %d got %d", 2, lth) 44 } 45 var used bool 46 for _, r := range records { 47 if r.Node().ID() == nodes[0].ID() { 48 used = !r.LastUsed.IsZero() 49 } 50 } 51 if !used { 52 return fmt.Errorf("record %s is not marked as used", types.EnodeID(nodes[0].ID())) 53 } 54 return nil 55 }, time.Second, 100*time.Millisecond)) 56 57 // Use different peer, first will be marked as unused. 58 select { 59 case whisperMock.input <- types.EnvelopeEvent{ 60 Event: types.EventMailServerRequestCompleted, Peer: types.EnodeID(nodes[1].ID())}: 61 case <-time.After(time.Second): 62 require.FailNow(t, "can't send a 'completed' event") 63 } 64 65 require.NoError(t, utils.Eventually(func() error { 66 records, err := cache.LoadAll() 67 if err != nil { 68 return err 69 } 70 if lth := len(records); lth != 2 { 71 return fmt.Errorf("unexpected length of all records stored in the cache. expected %d got %d", 2, lth) 72 } 73 sort.Slice(records, func(i, j int) bool { 74 return records[i].LastUsed.After(records[j].LastUsed) 75 }) 76 if records[0].Node().ID() != nodes[1].ID() { 77 return fmt.Errorf("record wasn't updated after previous event") 78 } 79 return nil 80 }, time.Second, 100*time.Millisecond)) 81 }