forked from 0xProject/0x-mesh
-
Notifications
You must be signed in to change notification settings - Fork 1
/
fake_log_client.go
66 lines (56 loc) · 2.04 KB
/
fake_log_client.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
package blockwatch
import (
"errors"
"fmt"
"math/big"
"sync/atomic"
"time"
"github.com/0xProject/0x-mesh/ethereum/miniheader"
"github.com/ethereum/go-ethereum"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core/types"
)
type filterLogsResponse struct {
Logs []types.Log
Err error
}
// fakeLogClient is a fake Client for testing code calling the `FilterLogs` method.
// It allows the instatiator to specify `FilterLogs` responses for several block ranges.
type fakeLogClient struct {
count int64
rangeToResponse map[string]filterLogsResponse
}
// newFakeLogClient instantiates a fakeLogClient for testing log fetching
func newFakeLogClient(rangeToResponse map[string]filterLogsResponse) (*fakeLogClient, error) {
return &fakeLogClient{count: 0, rangeToResponse: rangeToResponse}, nil
}
// HeaderByNumber fetches a block header by its number
func (fc *fakeLogClient) HeaderByNumber(number *big.Int) (*miniheader.MiniHeader, error) {
return nil, errors.New("NOT_IMPLEMENTED")
}
// HeaderByHash fetches a block header by its block hash
func (fc *fakeLogClient) HeaderByHash(hash common.Hash) (*miniheader.MiniHeader, error) {
return nil, errors.New("NOT_IMPLEMENTED")
}
// FilterLogs returns the logs that satisfy the supplied filter query
func (fc *fakeLogClient) FilterLogs(q ethereum.FilterQuery) ([]types.Log, error) {
// Add a slight delay to simulate an actual network request. This also gives
// BlockWatcher.getLogsInBlockRange multi-requests to hit the concurrent request
// limit semaphore and simulate more realistic conditions.
time.Sleep(5 * time.Millisecond)
r := toRange(q.FromBlock, q.ToBlock)
res, ok := fc.rangeToResponse[r]
if !ok {
return nil, fmt.Errorf("Didn't find response for range %s but was expecting it to exist", r)
}
atomic.AddInt64(&fc.count, 1)
return res.Logs, res.Err
}
// Count returns the number of times FilterLogs was called
func (fc *fakeLogClient) Count() int {
return int(fc.count)
}
func toRange(from, to *big.Int) string {
r := fmt.Sprintf("%s-%s", from, to)
return r
}