🐛 Fix race condition in TestWaitForErrorFirstErrSet using synctest

This commit is contained in:
Dan Jones 2025-11-13 16:01:53 -06:00
commit 7a2583c8e4

View file

@ -3,6 +3,7 @@ package waiterr_test
import ( import (
"errors" "errors"
"testing" "testing"
"testing/synctest"
"github.com/nalgeon/be" "github.com/nalgeon/be"
@ -104,22 +105,21 @@ func TestWaitForErrorPanic(t *testing.T) {
_ = we.WaitForError() _ = we.WaitForError()
} }
func TestWaitForErrorFirstErrSet(t *testing.T) { func TestWaitForErrorFirstErrSet(tt *testing.T) {
we := new(waiterr.WaitErr) we := new(waiterr.WaitErr)
expectedErr := errors.New("pre-set error") expectedErr := errors.New("pre-set error")
// Manually set firstErr (requires reflection or a way to access unexported fields) synctest.Test(tt, func(t *testing.T) {
// For testing purposes, we can simulate this by calling Go with an error first we.Go(func() error { return expectedErr })
we.Go(func() error { return expectedErr }) // synctest.Wait ensures that the gorouting has finished before anything else.
we.Go(func() error { return errors.New("another error") }) synctest.Wait()
we.Go(func() error { return nil })
// Wait for a short period to ensure the first error is processed we.Go(func() error { return errors.New("another error") })
// In a real scenario, this might be handled by a channel or more robust synchronization synctest.Wait()
// For this test, we'll rely on the Go routine scheduling to set firstErr quickly
_ = we.WaitForError() // Call once to ensure firstErr is set internally
// Now call WaitForError again, expecting it to return the already set firstErr we.Go(func() error { return nil })
actualErr := we.WaitForError()
be.Err(t, actualErr, expectedErr) actualErr := we.WaitForError()
be.Err(t, actualErr, expectedErr)
})
} }