Skip to content

Commit

Permalink
treat panic as test failure
Browse files Browse the repository at this point in the history
  • Loading branch information
ysmood committed May 27, 2021
1 parent 6508188 commit 127fd04
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 5 deletions.
21 changes: 16 additions & 5 deletions each.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ package got

import (
"reflect"
"runtime/debug"
"strings"
)

// Skip current test
Expand Down Expand Up @@ -44,10 +46,11 @@ func Each(t Testable, iteratee interface{}) (count int) {
runVal.Call([]reflect.Value{
reflect.ValueOf(method.Name),
reflect.MakeFunc(cbType, func(args []reflect.Value) []reflect.Value {
doSkip(args[0], method)
t := args[0].Interface().(Testable)
doSkip(t, method)
count++
res := itVal.Call(args)
return callMethod(method, res[0])
return callMethod(t, method, res[0])
}),
})
}
Expand Down Expand Up @@ -99,14 +102,22 @@ func normalizeIteratee(t Testable, iteratee interface{}) reflect.Value {
return itVal
}

func callMethod(method reflect.Method, receiver reflect.Value) []reflect.Value {
func callMethod(t Testable, method reflect.Method, receiver reflect.Value) []reflect.Value {
args := make([]reflect.Value, method.Type.NumIn())
args[0] = receiver

for i := 1; i < len(args); i++ {
args[i] = reflect.New(method.Type.In(i)).Elem()
}

defer func() {
if err := recover(); err != nil {
loc := strings.TrimLeft(strings.Split(string(debug.Stack()), "\n")[8], "\t")
t.Logf("panic: %v\n%s", err, loc)
t.Fail()
}
}()

method.Func.Call(args)

return []reflect.Value{}
Expand Down Expand Up @@ -145,9 +156,9 @@ func filterMethods(typ reflect.Type) []reflect.Method {
return methods
}

func doSkip(t reflect.Value, method reflect.Method) {
func doSkip(t Testable, method reflect.Method) {
if method.Type.NumIn() > 1 && method.Type.In(1) == skipType {
t.Interface().(Testable).SkipNow()
t.SkipNow()
}
}

Expand Down
20 changes: 20 additions & 0 deletions each_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -71,3 +71,23 @@ type Err struct {
}

func (s Err) A(int) {}

func TestPanicAsFailure(t *testing.T) {
as := got.New(t)

m := &mock{t: t}
it := func(t *mock) PanicAsFailure { return PanicAsFailure{} }
as.Eq(got.Each(m, it), 2)
as.True(m.failed)
as.Has(m.msg, "panic: err")
}

type PanicAsFailure struct {
}

func (p PanicAsFailure) A() {
panic("err")
}

func (p PanicAsFailure) B() {
}

0 comments on commit 127fd04

Please sign in to comment.