-
Notifications
You must be signed in to change notification settings - Fork 178
/
epoch_query.go
80 lines (67 loc) · 1.79 KB
/
epoch_query.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
package mocks
import (
"sync"
"testing"
"github.com/stretchr/testify/require"
"github.com/onflow/flow-go/state/protocol"
"github.com/onflow/flow-go/state/protocol/invalid"
)
// EpochQuery implements protocol.EpochQuery for testing purposes.
// Safe for concurrent use by multiple goroutines.
type EpochQuery struct {
t *testing.T
mu sync.RWMutex
counter uint64 // represents the current epoch
byCounter map[uint64]protocol.Epoch // all epochs
}
func NewEpochQuery(t *testing.T, counter uint64, epochs ...protocol.Epoch) *EpochQuery {
mock := &EpochQuery{
t: t,
counter: counter,
byCounter: make(map[uint64]protocol.Epoch),
}
for _, epoch := range epochs {
mock.Add(epoch)
}
return mock
}
func (mock *EpochQuery) Current() protocol.Epoch {
mock.mu.RLock()
defer mock.mu.RUnlock()
return mock.byCounter[mock.counter]
}
func (mock *EpochQuery) Next() protocol.Epoch {
mock.mu.RLock()
defer mock.mu.RUnlock()
epoch, exists := mock.byCounter[mock.counter+1]
if !exists {
return invalid.NewEpoch(protocol.ErrNextEpochNotSetup)
}
return epoch
}
func (mock *EpochQuery) Previous() protocol.Epoch {
mock.mu.RLock()
defer mock.mu.RUnlock()
epoch, exists := mock.byCounter[mock.counter-1]
if !exists {
return invalid.NewEpoch(protocol.ErrNoPreviousEpoch)
}
return epoch
}
func (mock *EpochQuery) ByCounter(counter uint64) protocol.Epoch {
mock.mu.RLock()
defer mock.mu.RUnlock()
return mock.byCounter[counter]
}
func (mock *EpochQuery) Transition() {
mock.mu.Lock()
defer mock.mu.Unlock()
mock.counter++
}
func (mock *EpochQuery) Add(epoch protocol.Epoch) {
mock.mu.Lock()
defer mock.mu.Unlock()
counter, err := epoch.Counter()
require.NoError(mock.t, err, "cannot add epoch with invalid counter")
mock.byCounter[counter] = epoch
}