Skip to content

Commit

Permalink
test: update test for Schedule
Browse files Browse the repository at this point in the history
  • Loading branch information
duke-git committed Aug 9, 2024
1 parent 0f9764f commit 5c580ed
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 15 deletions.
6 changes: 4 additions & 2 deletions function/function.go
Original file line number Diff line number Diff line change
Expand Up @@ -164,16 +164,18 @@ func Throttle(fn func(), interval time.Duration) func() {

// Schedule invoke function every duration time, util close the returned bool channel.
// Play: https://go.dev/play/p/hbON-Xeyn5N
func Schedule(d time.Duration, fn any, args ...any) chan bool {
func Schedule(duration time.Duration, fn any, args ...any) chan bool {
// Catch programming error while constructing the closure
mustBeFunction(fn)

quit := make(chan bool)

go func() {
for {
unsafeInvokeFunc(fn, args...)

select {
case <-time.After(d):
case <-time.After(duration):
case <-quit:
return
}
Expand Down
38 changes: 25 additions & 13 deletions function/function_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -268,23 +268,35 @@ func TestThrottle(t *testing.T) {
}

func TestSchedule(t *testing.T) {
// assert := internal.NewAssert(t, "TestSchedule")
assert := internal.NewAssert(t, "TestSchedule")

var res []string
appendStr := func(s string) {
res = append(res, s)
}
t.Run("Single call", func(t *testing.T) {
res := []string{}
appendStr := func(s string) {
res = append(res, s)
}
stop := Schedule(200*time.Millisecond, appendStr, "*")
close(stop)

time.Sleep(400 * time.Millisecond)

assert.Equal([]string{"*"}, res)
})

t.Run("Multiple calls", func(t *testing.T) {
res := []string{}
appendStr := func(s string) {
res = append(res, s)
}
stop := Schedule(200*time.Millisecond, appendStr, "*")

stop := Schedule(1*time.Second, appendStr, "*")
time.Sleep(5 * time.Second)
close(stop)
time.Sleep(800 * time.Millisecond)

t.Log(res)
close(stop)

assert.Equal([]string{"*", "*", "*", "*"}, res)
})

// todo: in github action, for now, this test is not working sometimes
// res maybe [* * * * *] or [* * * * * *]
// expected := []string{"*", "*", "*", "*", "*"}
// assert.Equal(expected, res)
}

func TestPipeline(t *testing.T) {
Expand Down

0 comments on commit 5c580ed

Please sign in to comment.