Carlos Amedee | b0ce0eb | 2020-09-16 14:32:16 -0400 | [diff] [blame] | 1 | // Copyright 2020 The Go Authors. All rights reserved. |
| 2 | // Use of this source code is governed by a BSD-style |
| 3 | // license that can be found in the LICENSE file. |
| 4 | |
| 5 | package internal |
| 6 | |
| 7 | import ( |
| 8 | "context" |
| 9 | "testing" |
| 10 | "time" |
| 11 | ) |
| 12 | |
| 13 | func TestPeriodicallyDo(t *testing.T) { |
| 14 | ctx, cancel := context.WithCancel(context.Background()) |
| 15 | defer cancel() |
| 16 | |
| 17 | didWork := make(chan time.Time, 2) |
| 18 | done := make(chan interface{}) |
| 19 | go func() { |
| 20 | PeriodicallyDo(ctx, time.Millisecond, func(ctx context.Context, t time.Time) { |
| 21 | select { |
| 22 | case didWork <- t: |
| 23 | case <-ctx.Done(): |
| 24 | } |
| 25 | }) |
| 26 | close(done) |
| 27 | }() |
| 28 | select { |
| 29 | case <-time.After(5 * time.Second): |
| 30 | t.Error("PeriodicallyDo() never called f, wanted at least one call") |
| 31 | case <-didWork: |
| 32 | // PeriodicallyDo called f successfully. |
| 33 | } |
| 34 | select { |
| 35 | case <-done: |
| 36 | t.Errorf("PeriodicallyDo() finished early, wanted it to still be looping") |
| 37 | case <-didWork: |
| 38 | cancel() |
| 39 | } |
| 40 | <-done |
| 41 | } |