-
Notifications
You must be signed in to change notification settings - Fork 661
/
test_vm.go
101 lines (85 loc) · 2.58 KB
/
test_vm.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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
// Copyright (C) 2019-2023, Ava Labs, Inc. All rights reserved.
// See the file LICENSE for licensing terms.
package block
import (
"context"
"errors"
"github.com/stretchr/testify/require"
"github.com/ava-labs/avalanchego/ids"
"github.com/ava-labs/avalanchego/snow/consensus/snowman"
"github.com/ava-labs/avalanchego/snow/engine/common"
)
var (
errBuildBlock = errors.New("unexpectedly called BuildBlock")
errParseBlock = errors.New("unexpectedly called ParseBlock")
errGetBlock = errors.New("unexpectedly called GetBlock")
errLastAccepted = errors.New("unexpectedly called LastAccepted")
_ ChainVM = (*TestVM)(nil)
)
// TestVM is a ChainVM that is useful for testing.
type TestVM struct {
common.TestVM
CantBuildBlock,
CantParseBlock,
CantGetBlock,
CantSetPreference,
CantLastAccepted bool
BuildBlockF func(context.Context) (snowman.Block, error)
ParseBlockF func(context.Context, []byte) (snowman.Block, error)
GetBlockF func(context.Context, ids.ID) (snowman.Block, error)
SetPreferenceF func(context.Context, ids.ID) error
LastAcceptedF func(context.Context) (ids.ID, error)
}
func (vm *TestVM) Default(cant bool) {
vm.TestVM.Default(cant)
vm.CantBuildBlock = cant
vm.CantParseBlock = cant
vm.CantGetBlock = cant
vm.CantSetPreference = cant
vm.CantLastAccepted = cant
}
func (vm *TestVM) BuildBlock(ctx context.Context) (snowman.Block, error) {
if vm.BuildBlockF != nil {
return vm.BuildBlockF(ctx)
}
if vm.CantBuildBlock && vm.T != nil {
require.FailNow(vm.T, errBuildBlock.Error())
}
return nil, errBuildBlock
}
func (vm *TestVM) ParseBlock(ctx context.Context, b []byte) (snowman.Block, error) {
if vm.ParseBlockF != nil {
return vm.ParseBlockF(ctx, b)
}
if vm.CantParseBlock && vm.T != nil {
require.FailNow(vm.T, errParseBlock.Error())
}
return nil, errParseBlock
}
func (vm *TestVM) GetBlock(ctx context.Context, id ids.ID) (snowman.Block, error) {
if vm.GetBlockF != nil {
return vm.GetBlockF(ctx, id)
}
if vm.CantGetBlock && vm.T != nil {
require.FailNow(vm.T, errGetBlock.Error())
}
return nil, errGetBlock
}
func (vm *TestVM) SetPreference(ctx context.Context, id ids.ID) error {
if vm.SetPreferenceF != nil {
return vm.SetPreferenceF(ctx, id)
}
if vm.CantSetPreference && vm.T != nil {
require.FailNow(vm.T, "Unexpectedly called SetPreference")
}
return nil
}
func (vm *TestVM) LastAccepted(ctx context.Context) (ids.ID, error) {
if vm.LastAcceptedF != nil {
return vm.LastAcceptedF(ctx)
}
if vm.CantLastAccepted && vm.T != nil {
require.FailNow(vm.T, errLastAccepted.Error())
}
return ids.ID{}, errLastAccepted
}