From c39cca759a7cff76bb3bf4e0020bd3652798dd9e Mon Sep 17 00:00:00 2001 From: pducolin Date: Thu, 28 Sep 2023 00:09:14 +0200 Subject: [PATCH] [assertions] early return recovering on panic in EventuallyWithT This allows for early return from EventuallyWithT assertions, allowing for keeping the error trace --- assert/assertions.go | 9 +++++++++ assert/assertions_test.go | 20 ++++++++++++++++++++ 2 files changed, 29 insertions(+) diff --git a/assert/assertions.go b/assert/assertions.go index 719164e7e..0abc4e0a5 100644 --- a/assert/assertions.go +++ b/assert/assertions.go @@ -1912,6 +1912,7 @@ func EventuallyWithT(t TestingT, condition func(collect *CollectT), waitFor time collect := new(CollectT) ch := make(chan bool, 1) + failed := make(chan struct{}, 1) timer := time.NewTimer(waitFor) defer timer.Stop() @@ -1928,6 +1929,11 @@ func EventuallyWithT(t TestingT, condition func(collect *CollectT), waitFor time tick = nil collect.Reset() go func() { + defer func() { + if r := recover(); r != nil { + failed <- struct{}{} + } + }() condition(collect) ch <- len(collect.errors) == 0 }() @@ -1936,6 +1942,9 @@ func EventuallyWithT(t TestingT, condition func(collect *CollectT), waitFor time return true } tick = ticker.C + case <-failed: + collect.Copy(t) + return Fail(t, "Require assertion failed", msgAndArgs...) } } } diff --git a/assert/assertions_test.go b/assert/assertions_test.go index 40e372015..8f58e0ffc 100644 --- a/assert/assertions_test.go +++ b/assert/assertions_test.go @@ -2786,6 +2786,26 @@ func TestEventuallyWithTTrue(t *testing.T) { Len(t, mockT.errors, 0) } +func TestEventuallyWithTFailNow(t *testing.T) { + mockT := new(CollectT) + + state := 0 + condition := func(collect *CollectT) { + defer func() { + state += 1 + }() + if state == 2 { + collect.Errorf("early failed") + collect.FailNow() + } + True(collect, state == 2) + } + + False(t, EventuallyWithT(mockT, condition, 100*time.Millisecond, 20*time.Millisecond)) + Len(t, mockT.errors, 2) + Equal(t, "early failed", mockT.errors[0].Error()) +} + func TestNeverFalse(t *testing.T) { condition := func() bool { return false