code.vegaprotocol.io/vega@v0.79.0/core/liquidity/target/spot/snapshot_test.go (about) 1 // Copyright (C) 2023 Gobalsky Labs Limited 2 // 3 // This program is free software: you can redistribute it and/or modify 4 // it under the terms of the GNU Affero General Public License as 5 // published by the Free Software Foundation, either version 3 of the 6 // License, or (at your option) any later version. 7 // 8 // This program is distributed in the hope that it will be useful, 9 // but WITHOUT ANY WARRANTY; without even the implied warranty of 10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 // GNU Affero General Public License for more details. 12 // 13 // You should have received a copy of the GNU Affero General Public License 14 // along with this program. If not, see <http://www.gnu.org/licenses/>. 15 16 package spot_test 17 18 import ( 19 "bytes" 20 "context" 21 "fmt" 22 "testing" 23 "time" 24 25 "code.vegaprotocol.io/vega/core/liquidity/target/spot" 26 "code.vegaprotocol.io/vega/core/types" 27 "code.vegaprotocol.io/vega/libs/num" 28 "code.vegaprotocol.io/vega/libs/proto" 29 snapshot "code.vegaprotocol.io/vega/protos/vega/snapshot/v1" 30 31 "github.com/stretchr/testify/assert" 32 ) 33 34 func newSnapshotEngine(marketID string) *spot.SnapshotEngine { 35 params := types.TargetStakeParameters{ 36 TimeWindow: 5, 37 ScalingFactor: num.NewDecimalFromFloat(2), 38 } 39 40 return spot.NewSnapshotEngine(params, marketID, num.DecimalFromFloat(1)) 41 } 42 43 func TestSaveAndLoadSnapshot(t *testing.T) { 44 a := assert.New(t) 45 marketID := "market-1" 46 key := fmt.Sprintf("target:%s", marketID) 47 se := newSnapshotEngine(marketID) 48 49 s, _, err := se.GetState("") 50 a.Empty(s) 51 a.EqualError(err, types.ErrSnapshotKeyDoesNotExist.Error()) 52 53 d := time.Date(2015, time.December, 24, 19, 0, 0, 0, time.UTC) 54 se.RecordTotalStake(40, d) 55 se.RecordTotalStake(40, d.Add(time.Hour*3)) 56 57 s, _, err = se.GetState(key) 58 a.NotEmpty(s) 59 a.NoError(err) 60 61 se2 := newSnapshotEngine(marketID) 62 63 pl := snapshot.Payload{} 64 assert.NoError(t, proto.Unmarshal(s, &pl)) 65 66 _, err = se2.LoadState(context.TODO(), types.PayloadFromProto(&pl)) 67 a.NoError(err) 68 69 s2, _, err := se2.GetState(key) 70 a.NoError(err) 71 a.True(bytes.Equal(s, s2)) 72 } 73 74 func TestStopSnapshotTaking(t *testing.T) { 75 marketID := "market-1" 76 key := fmt.Sprintf("target:%s", marketID) 77 se := newSnapshotEngine(marketID) 78 79 // signal to kill the engine's snapshots 80 se.StopSnapshots() 81 82 s, _, err := se.GetState(key) 83 assert.NoError(t, err) 84 assert.Nil(t, s) 85 assert.True(t, se.Stopped()) 86 }