blob: 0d0f928d0ecfb692288ac0cf941450c4de7fc3d0 [file] [log] [blame]
Jan Schär75ea9f42024-07-29 17:01:41 +02001package up
2
3// Taken and modified from CoreDNS, under Apache 2.0.
4
5import (
6 "sync"
7 "sync/atomic"
8 "testing"
9 "time"
10)
11
12func TestUp(t *testing.T) {
13 pr := New()
14 wg := sync.WaitGroup{}
15 hits := int32(0)
16
17 upfunc := func() error {
18 atomic.AddInt32(&hits, 1)
19 // Sleep tiny amount so that our other pr.Do() calls hit the lock.
20 time.Sleep(3 * time.Millisecond)
21 wg.Done()
22 return nil
23 }
24
25 pr.Start(5 * time.Millisecond)
26 defer pr.Stop()
27
28 // These functions AddInt32 to the same hits variable, but we only want to
29 // wait when upfunc finishes, as that only calls Done() on the waitgroup.
30 upfuncNoWg := func() error { atomic.AddInt32(&hits, 1); return nil }
31 wg.Add(1)
32 pr.Do(upfunc)
33 pr.Do(upfuncNoWg)
34 pr.Do(upfuncNoWg)
35
36 wg.Wait()
37
38 h := atomic.LoadInt32(&hits)
39 if h != 1 {
40 t.Errorf("Expected hits to be %d, got %d", 1, h)
41 }
42}