diff --git a/mock/mock.go b/mock/mock.go index 746151e1b..1187dd18a 100644 --- a/mock/mock.go +++ b/mock/mock.go @@ -326,7 +326,10 @@ func (m *Mock) String() string { // TestData holds any data that might be useful for testing. Testify ignores // this data completely allowing you to do whatever you like with it. +// Access to the returned map must be synchronized by the caller. func (m *Mock) TestData() objx.Map { + m.mutex.Lock() + defer m.mutex.Unlock() if m.testData == nil { m.testData = make(objx.Map) } diff --git a/mock/testdata_race_test.go b/mock/testdata_race_test.go new file mode 100644 index 000000000..0a2bd142c --- /dev/null +++ b/mock/testdata_race_test.go @@ -0,0 +1,44 @@ +package mock + +import ( + "sync" + "testing" + + "github.com/stretchr/objx" +) + +func TestMockTestDataConcurrentInitialization(t *testing.T) { + const callers = 32 + for attempt := 0; attempt < 20; attempt++ { + var mocked Mock + maps := make([]objx.Map, callers) + start := make(chan struct{}) + var ready sync.WaitGroup + var done sync.WaitGroup + ready.Add(callers) + done.Add(callers) + for i := 0; i < callers; i++ { + go func(index int) { + defer done.Done() + ready.Done() + <-start + // Map writes remain the caller's responsibility. Only retrieve + // the shared map concurrently in this regression test. + maps[index] = mocked.TestData() + if maps[index] == nil { + t.Error("TestData returned nil") + } + }(i) + } + ready.Wait() + close(start) + done.Wait() + // Writes and reads here are sequential, after every accessor returns. + maps[0]["shared"] = attempt + for i, values := range maps { + if values["shared"] != attempt { + t.Errorf("caller %d did not receive the shared map", i) + } + } + } +}