Search Apps Documentation Source Content File Folder Download Copy Actions Download

timelock_test.gno

2.59 Kb ยท 89 lines
 1package timelock
 2
 3import (
 4	"chain/runtime"
 5	"testing"
 6	"time"
 7
 8	"gno.land/p/nt/avl"
 9	"gno.land/p/nt/seqid"
10	"gno.land/p/nt/uassert"
11	"gno.land/p/thox/accesscontrol"
12)
13
14func TestTimelock(t *testing.T) {
15	// Initialization
16	timestamps := avl.NewTree()
17	minDelay := uint64(2) // 2 seconds to simplify testing
18	accessControl, _ := accesscontrol.NewRole("admin", runtime.OriginCaller())
19	timelockUtil, err := NewTimeLock(timestamps, accessControl, minDelay)
20
21	// Generate a new ID from time.Now().UnixNano() with seconds added to guarantee uniqueness
22	newID := func(offset int64) seqid.ID {
23		return seqid.ID(time.Now().UnixNano() + offset)
24	}
25
26	uassert.NoError(t, err, "Failed to create TimeLock instance")
27
28	// Test Schedule
29	t.Run("Schedule", func(t *testing.T) {
30		id := newID(0)
31		delay := uint64(3) // 3 seconds
32
33		err := timelockUtil.Schedule(id, delay)
34
35		uassert.NoError(t, err, "Schedule failed")
36
37		status, err := timelockUtil.GetOperationStatus(id)
38
39		uassert.NoError(t, err, "failed to get operation status")
40		uassert.NotEmpty(t, status.sheduleTime, "operation status not set or invalid")
41	})
42
43	// Test Cancel
44	t.Run("Cancel", func(t *testing.T) {
45		id := newID(1)
46
47		// Plan a new operation to ensure it is unique
48		err := timelockUtil.Schedule(id, uint64(3))
49		uassert.NoError(t, err, "Failed to schedule operation for cancellation")
50
51		err = timelockUtil.Cancel(id)
52		uassert.NoError(t, err, "Cancel failed")
53
54		status, err := timelockUtil.GetOperationStatus(id)
55		uassert.NoError(t, err, "failed to get operation status")
56		uassert.Empty(t, status.sheduleTime, "operation not cancelled")
57	})
58
59	// Test Execute
60	t.Run("Execute", func(t *testing.T) {
61		id := newID(2)
62		delay := uint64(3) // 3 seconds
63		futureTime := time.Now().Unix() + int64(delay)
64
65		// Schedule the operation with a future timestamp
66		err := timelockUtil.Schedule(id, delay)
67		uassert.NoError(t, err, "Failed to schedule operation for execution")
68
69		// Simulates the passage of time by setting the timestamp to a future time
70		timestamps.Set(id.Binary(), OperationStatus{sheduleTime: futureTime, isDone: false})
71
72		err = timelockUtil.Execute(id)
73		uassert.NoError(t, err, "Execute failed")
74
75		state, err := timelockUtil.GetOperationState(id)
76		uassert.NoError(t, err, "failed to get operation state")
77		uassert.Equal(t, Done.StateToString(), state.StateToString(), "operation not executed")
78	})
79
80	// Test UpdateDelay
81	t.Run("UpdateDelay", func(t *testing.T) {
82		newDelay := uint64(4) // 4 seconds
83
84		err := timelockUtil.UpdateDelay(newDelay)
85		uassert.NoError(t, err, "UpdateDelay failed")
86
87		uassert.Equal(t, newDelay, timelockUtil.minDelay, "minDelay not updated")
88	})
89}