Skip to content

Commit

Permalink
assert: collect.FailNow() should not panic
Browse files Browse the repository at this point in the history
  • Loading branch information
marshall-lee committed Oct 8, 2023
1 parent 882382d commit ab5d73e
Show file tree
Hide file tree
Showing 3 changed files with 49 additions and 2 deletions.
8 changes: 6 additions & 2 deletions assert/assertions.go
Expand Up @@ -1860,20 +1860,24 @@ func Eventually(t TestingT, condition func() bool, waitFor time.Duration, tick t
// CollectT implements the TestingT interface and collects all errors.
type CollectT struct {
errors []error
failed bool
}

// Errorf collects the error.
func (c *CollectT) Errorf(format string, args ...interface{}) {
c.failed = true
c.errors = append(c.errors, fmt.Errorf(format, args...))
}

// FailNow panics.
func (c *CollectT) FailNow() {
panic("Assertion failed")
c.failed = true
runtime.Goexit()
}

// Reset clears the collected errors.
func (c *CollectT) Reset() {
c.failed = false
c.errors = nil
}

Expand Down Expand Up @@ -1928,8 +1932,8 @@ func EventuallyWithT(t TestingT, condition func(collect *CollectT), waitFor time
tick = nil
collect.Reset()
go func() {
defer func() { ch <- !collect.failed }()
condition(collect)
ch <- len(collect.errors) == 0
}()
case v := <-ch:
if v {
Expand Down
11 changes: 11 additions & 0 deletions assert/assertions_test.go
Expand Up @@ -2786,6 +2786,17 @@ func TestEventuallyWithTTrue(t *testing.T) {
Len(t, mockT.errors, 0)
}

func TestEventuallyWithTFailNow(t *testing.T) {
mockT := new(CollectT)

condition := func(collect *CollectT) {
collect.FailNow()
}

False(t, EventuallyWithT(mockT, condition, 100*time.Millisecond, 20*time.Millisecond))
Len(t, mockT.errors, 1)
}

func TestNeverFalse(t *testing.T) {
condition := func() bool {
return false
Expand Down
32 changes: 32 additions & 0 deletions require/requirements_test.go
Expand Up @@ -5,6 +5,8 @@ import (
"errors"
"testing"
"time"

"github.com/stretchr/testify/assert"
)

// AssertionTesterInterface defines an interface to be used for testing assertion methods
Expand Down Expand Up @@ -681,3 +683,33 @@ func TestErrorAssertionFunc(t *testing.T) {
})
}
}

func TestEventuallyWithTFalse(t *testing.T) {
mockT := new(MockT)

condition := func(collect *assert.CollectT) {
True(collect, false)
}

EventuallyWithT(mockT, condition, 100*time.Millisecond, 20*time.Millisecond)
if !mockT.Failed {
t.Error("Check should fail")
}
}

func TestEventuallyWithTTrue(t *testing.T) {
mockT := new(MockT)

state := 0
condition := func(collect *assert.CollectT) {
defer func() {
state += 1
}()
True(collect, state == 2)
}

EventuallyWithT(mockT, condition, 100*time.Millisecond, 20*time.Millisecond)
if mockT.Failed {
t.Error("Check should pass")
}
}

0 comments on commit ab5d73e

Please sign in to comment.