Skip to content

Commit 58f7ae8

Browse files
committed
test: add piroutine unit tests
1 parent 797ebff commit 58f7ae8

File tree

1 file changed

+77
-0
lines changed

1 file changed

+77
-0
lines changed

piroutine/piroutine_test.go

Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,8 +6,10 @@ package piroutine_test
66
import (
77
"testing"
88

9+
"github.com/elgopher/pi/piloop"
910
"github.com/elgopher/pi/piroutine"
1011
"github.com/stretchr/testify/assert"
12+
"github.com/stretchr/testify/require"
1113
)
1214

1315
func TestPiroutine(t *testing.T) {
@@ -45,3 +47,78 @@ func TestRoutine_Resume(t *testing.T) {
4547
assert.False(t, routine.Resume()) // nothing changed
4648
})
4749
}
50+
51+
func TestCall(t *testing.T) {
52+
t.Run("should call callback", func(t *testing.T) {
53+
var executed = false
54+
step := piroutine.Call(func() {
55+
executed = true
56+
})
57+
// when
58+
result := step()
59+
// then
60+
assert.True(t, executed)
61+
assert.True(t, result)
62+
})
63+
}
64+
65+
func TestSlowDown(t *testing.T) {
66+
t.Run("should wait n updates before running callback", func(t *testing.T) {
67+
executionCount := 0
68+
step := piroutine.SlowDown(2, func() bool {
69+
executionCount++
70+
return true
71+
})
72+
assert.False(t, step())
73+
assert.Equal(t, 0, executionCount)
74+
assert.False(t, step())
75+
assert.Equal(t, 0, executionCount)
76+
assert.True(t, step())
77+
assert.Equal(t, 1, executionCount)
78+
})
79+
80+
t.Run("should immediately run callback", func(t *testing.T) {
81+
executionCount := 0
82+
step := piroutine.SlowDown(0, func() bool {
83+
executionCount++
84+
return true
85+
})
86+
assert.True(t, step())
87+
assert.Equal(t, 1, executionCount)
88+
})
89+
90+
t.Run("should wait another n updates after callback returned false", func(t *testing.T) {
91+
executionCount := 0
92+
step := piroutine.SlowDown(3, func() bool {
93+
executionCount++
94+
return executionCount%2 == 0
95+
})
96+
for range 3 {
97+
assert.False(t, step()) // wait
98+
}
99+
assert.False(t, step()) // callback returns false
100+
for range 3 {
101+
assert.False(t, step()) // wait
102+
}
103+
assert.True(t, step()) // callback returns true this time
104+
assert.Equal(t, 2, executionCount)
105+
})
106+
}
107+
108+
func TestRoutine_ScheduleOn(t *testing.T) {
109+
t.Run("should run callback on event", func(t *testing.T) {
110+
executionCount := 0
111+
step := func() bool {
112+
executionCount++
113+
return true
114+
}
115+
routine := piroutine.New(step)
116+
// when
117+
handler := routine.ScheduleOn(piloop.EventDraw)
118+
// then
119+
require.True(t, piloop.Target().IsSubscribed(handler))
120+
piloop.Target().Publish(piloop.EventDraw) // runs callback and unsubscribes handlers
121+
assert.Equal(t, 1, executionCount)
122+
assert.False(t, piloop.Target().IsSubscribed(handler))
123+
})
124+
}

0 commit comments

Comments
 (0)