github.com/ava-labs/avalanchego@v1.11.11/vms/components/gas/state_test.go (about) 1 // Copyright (C) 2019-2024, Ava Labs, Inc. All rights reserved. 2 // See the file LICENSE for licensing terms. 3 4 package gas 5 6 import ( 7 "math" 8 "testing" 9 10 "github.com/stretchr/testify/require" 11 ) 12 13 func Test_State_AdvanceTime(t *testing.T) { 14 tests := []struct { 15 name string 16 initial State 17 maxCapacity Gas 18 maxPerSecond Gas 19 targetPerSecond Gas 20 duration uint64 21 expected State 22 }{ 23 { 24 name: "cap capacity", 25 initial: State{ 26 Capacity: 10, 27 Excess: 0, 28 }, 29 maxCapacity: 20, 30 maxPerSecond: 10, 31 targetPerSecond: 0, 32 duration: 2, 33 expected: State{ 34 Capacity: 20, 35 Excess: 0, 36 }, 37 }, 38 { 39 name: "increase capacity", 40 initial: State{ 41 Capacity: 10, 42 Excess: 0, 43 }, 44 maxCapacity: 30, 45 maxPerSecond: 10, 46 targetPerSecond: 0, 47 duration: 1, 48 expected: State{ 49 Capacity: 20, 50 Excess: 0, 51 }, 52 }, 53 { 54 name: "avoid excess underflow", 55 initial: State{ 56 Capacity: 10, 57 Excess: 10, 58 }, 59 maxCapacity: 20, 60 maxPerSecond: 10, 61 targetPerSecond: 10, 62 duration: 2, 63 expected: State{ 64 Capacity: 20, 65 Excess: 0, 66 }, 67 }, 68 { 69 name: "reduce excess", 70 initial: State{ 71 Capacity: 10, 72 Excess: 10, 73 }, 74 maxCapacity: 20, 75 maxPerSecond: 10, 76 targetPerSecond: 5, 77 duration: 1, 78 expected: State{ 79 Capacity: 20, 80 Excess: 5, 81 }, 82 }, 83 } 84 for _, test := range tests { 85 t.Run(test.name, func(t *testing.T) { 86 actual := test.initial.AdvanceTime(test.maxCapacity, test.maxPerSecond, test.targetPerSecond, test.duration) 87 require.Equal(t, test.expected, actual) 88 }) 89 } 90 } 91 92 func Test_State_ConsumeGas(t *testing.T) { 93 tests := []struct { 94 name string 95 initial State 96 gas Gas 97 expected State 98 expectedErr error 99 }{ 100 { 101 name: "consume some gas", 102 initial: State{ 103 Capacity: 10, 104 Excess: 10, 105 }, 106 gas: 5, 107 expected: State{ 108 Capacity: 5, 109 Excess: 15, 110 }, 111 expectedErr: nil, 112 }, 113 { 114 name: "consume all gas", 115 initial: State{ 116 Capacity: 10, 117 Excess: 10, 118 }, 119 gas: 10, 120 expected: State{ 121 Capacity: 0, 122 Excess: 20, 123 }, 124 expectedErr: nil, 125 }, 126 { 127 name: "consume too much gas", 128 initial: State{ 129 Capacity: 10, 130 Excess: 10, 131 }, 132 gas: 11, 133 expected: State{}, 134 expectedErr: ErrInsufficientCapacity, 135 }, 136 { 137 name: "maximum excess", 138 initial: State{ 139 Capacity: 10, 140 Excess: math.MaxUint64, 141 }, 142 gas: 1, 143 expected: State{ 144 Capacity: 9, 145 Excess: math.MaxUint64, 146 }, 147 expectedErr: nil, 148 }, 149 } 150 for _, test := range tests { 151 t.Run(test.name, func(t *testing.T) { 152 require := require.New(t) 153 154 actual, err := test.initial.ConsumeGas(test.gas) 155 require.ErrorIs(err, test.expectedErr) 156 require.Equal(test.expected, actual) 157 }) 158 } 159 }