blob: d4fb7ee027abdd656fea52da878e8753223067df [file] [log] [blame]
Philipp Schraderb15f4bd2023-03-25 14:21:38 -07001package background_task
2
3import (
4 "testing"
5 "time"
6)
7
8func TestBackgroundTask(t *testing.T) {
9 task := New(100 * time.Millisecond)
10 defer task.Stop()
11
12 counter := 0
13 task.Start(func() {
14 counter += 1
15 })
16
17 // Block until we've seeen 10 timer ticks.
18 for counter < 10 {
19 time.Sleep(100 * time.Millisecond)
20 }
21}
Philipp Schrader417ab8a2023-03-25 15:16:01 -070022
23func TestSelfCancellation(t *testing.T) {
24 task := New(100 * time.Millisecond)
25
26 done := false
27 counter := 0
28 task.Start(func() {
29 counter += 1
30
31 if done {
32 t.Fatal("callback should not be called after cancellation")
33 }
34
35 if counter == 10 {
36 task.StopFromWithinTask()
37 done = true
38 }
39 })
40
41 // Block until the background task has cancelled itself.
42 for !done {
43 time.Sleep(100 * time.Millisecond)
44 }
45
46 // Then sleep for a little longer to make sure that the task won't
47 // invoke the t.Fatal().
48 time.Sleep(time.Second)
49 task.Stop()
50}