golang.org/x/playground@v0.0.0-20230418134305-14ebe15bcd59/internal/internal_test.go (about) 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 didWork := make(chan time.Time, 2) 16 done := make(chan interface{}) 17 go func() { 18 PeriodicallyDo(ctx, 100*time.Millisecond, func(ctx context.Context, t time.Time) { 19 select { 20 case didWork <- t: 21 default: 22 // No need to assert that we can't send, we just care that we sent. 23 } 24 }) 25 close(done) 26 }() 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 35 select { 36 case <-done: 37 t.Errorf("PeriodicallyDo() finished early, wanted it to still be looping") 38 case <-didWork: 39 cancel() 40 } 41 42 select { 43 case <-time.After(time.Second): 44 t.Fatal("PeriodicallyDo() never returned, wanted return after context cancellation") 45 case <-done: 46 // PeriodicallyDo successfully returned. 47 } 48 }