Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

periodic: add timeout to all function calls in the tests #3309

Merged
merged 1 commit into from
Nov 4, 2019
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 31 additions & 8 deletions go/lib/periodic/periodic_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ package periodic

import (
"context"
"fmt"
"os"
"testing"
"time"
Expand Down Expand Up @@ -44,18 +45,21 @@ func TestPeriodicExecution(t *testing.T) {
want := 5
p := time.Duration(want) * time.Millisecond
r := Start(fn, p, time.Hour)
defer r.Stop()
defer func() {
err := runWithTimeout(r.Stop, time.Second)
assert.NoError(t, err)
}()

start := time.Now()
done := make(chan struct{})
go func() {
defer close(done)
v := 0
for {
select {
case <-cnt:
v++
if v == want {
close(done)
return
}
case <-time.After(2 * p):
Expand Down Expand Up @@ -83,7 +87,8 @@ func TestKillExitsLongRunningFunc(t *testing.T) {
})
r := Start(fn, p, time.Hour)
xtest.AssertReadReturnsBefore(t, done, time.Second)
r.Kill()
err := runWithTimeout(r.Kill, time.Second)
assert.NoError(t, err)

select {
case err := <-errChan:
Expand All @@ -103,14 +108,17 @@ func TestTaskDoesntRunAfterKill(t *testing.T) {

done := make(chan struct{})
go func() {
defer close(done)
select {
case <-cnt:
case <-time.After(2 * p):
t.Fatalf("time out while waiting on first run")
}
r.Kill()
time.Sleep(p)
close(done)

err := runWithTimeout(r.Kill, 2*p)
assert.NoError(t, err)

<-time.After(p)
}()
xtest.AssertReadReturnsBefore(t, done, time.Second)
assert.Equal(t, len(cnt), 0, "No other run within a period")
Expand All @@ -129,15 +137,16 @@ func TestTriggerNow(t *testing.T) {

done := make(chan struct{})
go func() {
defer close(done)
select {
case <-cnt:
case <-time.After(2 * p):
t.Fatalf("time out while waiting on first run")
}
for i := 0; i < want; i++ {
r.TriggerRun()
err := runWithTimeout(r.TriggerRun, p)
assert.NoError(t, err)
}
close(done)
}()
xtest.AssertReadReturnsBefore(t, done, time.Second)
assert.GreaterOrEqual(t, len(cnt), want-1, "Must run %v times within short time", want-1)
Expand All @@ -147,3 +156,17 @@ func TestMain(m *testing.M) {
log.Root().SetHandler(log.DiscardHandler())
os.Exit(m.Run())
}

func runWithTimeout(f func(), t time.Duration) error {
done := make(chan struct{})
go func() {
defer close(done)
f()
}()
select {
case <-done:
return nil
case <-time.After(t):
return fmt.Errorf("timed out after %v", t)
}
}