Skip to content

Commit

Permalink
[assertions] early return recovering on panic in EventuallyWithT
Browse files Browse the repository at this point in the history
This allows for early return from EventuallyWithT assertions, allowing for keeping the error trace
  • Loading branch information
pducolin committed Sep 27, 2023
1 parent 882382d commit c39cca7
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 0 deletions.
9 changes: 9 additions & 0 deletions assert/assertions.go
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand All @@ -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
}()
Expand All @@ -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...)
}
}
}
Expand Down
20 changes: 20 additions & 0 deletions assert/assertions_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down

0 comments on commit c39cca7

Please sign in to comment.