| 1 |
// Licensed under the MIT license, see LICENSE file for details. |
| 2 |
|
| 3 |
package quicktest_test |
| 4 |
|
| 5 |
import ( |
| 6 |
"sync" |
| 7 |
"sync/atomic" |
| 8 |
"testing" |
| 9 |
|
| 10 |
qt "github.com/frankban/quicktest" |
| 11 |
) |
| 12 |
|
| 13 |
func TestConcurrentMethods(t *testing.T) { |
| 14 |
// This test is designed to be run with the race |
| 15 |
// detector enabled. It checks that C methods |
| 16 |
// are safe to call concurrently. |
| 17 |
|
| 18 |
// N holds the number of iterations to run any given |
| 19 |
// operation concurrently with the others. |
| 20 |
const N = 100 |
| 21 |
|
| 22 |
var x, y int32 |
| 23 |
c := qt.New(dummyT{t}) |
| 24 |
c.Run("subtest", func(c *qt.C) { |
| 25 |
var wg sync.WaitGroup |
| 26 |
// start calls f in two goroutines, each |
| 27 |
// running it N times. |
| 28 |
// All the goroutines get started before we actually |
| 29 |
// start them running, so that the race detector |
| 30 |
// has a better chance of catching issues. |
| 31 |
gogogo := make(chan struct{}) |
| 32 |
start := func(f func()) { |
| 33 |
repeat := func() { |
| 34 |
defer wg.Done() |
| 35 |
<-gogogo |
| 36 |
for i := 0; i < N; i++ { |
| 37 |
f() |
| 38 |
} |
| 39 |
} |
| 40 |
wg.Add(2) |
| 41 |
go repeat() |
| 42 |
go repeat() |
| 43 |
} |
| 44 |
start(func() { |
| 45 |
c.Defer(func() { |
| 46 |
atomic.AddInt32(&x, 1) |
| 47 |
}) |
| 48 |
c.Defer(func() { |
| 49 |
atomic.AddInt32(&y, 1) |
| 50 |
}) |
| 51 |
}) |
| 52 |
start(func() { |
| 53 |
c.Done() |
| 54 |
}) |
| 55 |
start(func() { |
| 56 |
c.SetFormat(func(v interface{}) string { |
| 57 |
return "x" |
| 58 |
}) |
| 59 |
}) |
| 60 |
start(func() { |
| 61 |
// Do an assert to exercise the formatter. |
| 62 |
c.Check(true, qt.Equals, false) |
| 63 |
}) |
| 64 |
start(func() { |
| 65 |
c.Run("", func(c *qt.C) {}) |
| 66 |
}) |
| 67 |
close(gogogo) |
| 68 |
wg.Wait() |
| 69 |
}) |
| 70 |
// Check that all the defer functions ran OK. |
| 71 |
if x != N*2 || y != N*2 { |
| 72 |
t.Fatalf("unexpected x, y counts; got %d, %d; want %d, %d", x, y, N*2, N*2) |
| 73 |
} |
| 74 |
} |
| 75 |
|
| 76 |
// dummyT wraps a *testing.T value suitable |
| 77 |
// for TestConcurrentMethods so that calling Error |
| 78 |
// won't fail the test and that it implements |
| 79 |
// Run correctly. |
| 80 |
type dummyT struct { |
| 81 |
*testing.T |
| 82 |
} |
| 83 |
|
| 84 |
func (dummyT) Error(...interface{}) {} |
| 85 |
|
| 86 |
func (t dummyT) Run(name string, f func(t dummyT)) bool { |
| 87 |
return t.T.Run(name, func(t *testing.T) { |
| 88 |
f(dummyT{t}) |
| 89 |
}) |
| 90 |
} |