neo-go/pkg/peer/stall/stall_test.go

85 lines
1.6 KiB
Go
Raw Normal View History

2019-02-25 22:44:14 +00:00
package stall
import (
"sync"
2019-02-25 22:44:14 +00:00
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/CityOfZion/neo-go/pkg/wire/command"
)
func TestAddRemoveMessage(t *testing.T) {
responseTime := 2 * time.Second
tickerInterval := 1 * time.Second
d := NewDetector(responseTime, tickerInterval)
d.AddMessage(command.GetAddr)
mp := d.GetMessages()
assert.Equal(t, 1, len(mp))
assert.IsType(t, time.Time{}, mp[command.GetAddr])
d.RemoveMessage(command.GetAddr)
mp = d.GetMessages()
assert.Equal(t, 0, len(mp))
assert.Empty(t, mp[command.GetAddr])
}
type mockPeer struct {
lock *sync.RWMutex
2019-02-25 22:44:14 +00:00
online bool
detector *Detector
}
func (mp *mockPeer) loop() {
loop:
for {
select {
case <-mp.detector.Quitch:
break loop
}
}
// cleanup
mp.lock.Lock()
2019-02-25 22:44:14 +00:00
mp.online = false
mp.lock.Unlock()
2019-02-25 22:44:14 +00:00
}
func TestDeadlineWorks(t *testing.T) {
responseTime := 2 * time.Second
tickerInterval := 1 * time.Second
d := NewDetector(responseTime, tickerInterval)
mp := mockPeer{online: true, detector: d, lock: new(sync.RWMutex)}
2019-02-25 22:44:14 +00:00
go mp.loop()
d.AddMessage(command.GetAddr)
time.Sleep(responseTime + 1*time.Second)
k := make(map[command.Type]time.Time)
d.lock.RLock()
2019-02-25 22:44:14 +00:00
assert.Equal(t, k, d.responses)
d.lock.RUnlock()
mp.lock.RLock()
2019-02-25 22:44:14 +00:00
assert.Equal(t, false, mp.online)
mp.lock.RUnlock()
2019-02-25 22:44:14 +00:00
}
func TestDeadlineShouldNotBeEmpty(t *testing.T) {
responseTime := 10 * time.Second
tickerInterval := 1 * time.Second
d := NewDetector(responseTime, tickerInterval)
d.AddMessage(command.GetAddr)
time.Sleep(1 * time.Second)
k := make(map[command.Type]time.Time)
d.lock.RLock()
2019-02-25 22:44:14 +00:00
assert.NotEqual(t, k, d.responses)
d.lock.RUnlock()
2019-02-25 22:44:14 +00:00
}