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