Refactor TestGt to also include Lt, Ge, Le, Eq and Ne

This commit is contained in:
bep 2015-01-20 16:38:08 +01:00
parent 1348caa6de
commit f77f2a9b40

View file

@ -6,39 +6,96 @@ import (
"fmt" "fmt"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"html/template" "html/template"
"path"
"reflect" "reflect"
"runtime"
"testing" "testing"
) )
type tstNoStringer struct { type tstNoStringer struct {
} }
func TestGt(t *testing.T) { type tstCompareType int
const (
tstEq tstCompareType = iota
tstNe
tstGt
tstGe
tstLt
tstLe
)
func tstIsEq(tp tstCompareType) bool {
return tp == tstEq || tp == tstGe || tp == tstLe
}
func tstIsGt(tp tstCompareType) bool {
return tp == tstGt || tp == tstGe
}
func tstIsLt(tp tstCompareType) bool {
return tp == tstLt || tp == tstLe
}
func TestCompare(t *testing.T) {
for _, this := range []struct {
tstCompareType
funcUnderTest func(a, b interface{}) bool
}{
{tstGt, Gt},
{tstLt, Lt},
{tstGe, Ge},
{tstLe, Le},
{tstEq, Eq},
{tstNe, Ne},
} {
doTestCompare(t, this.tstCompareType, this.funcUnderTest)
}
}
func doTestCompare(t *testing.T, tp tstCompareType, funcUnderTest func(a, b interface{}) bool) {
for i, this := range []struct { for i, this := range []struct {
left interface{} left interface{}
right interface{} right interface{}
leftShouldWin bool expectIndicator int
}{ }{
{5, 8, false}, {5, 8, -1},
{8, 5, true}, {8, 5, 1},
{5, 5, false}, {5, 5, 0},
{-2, 1, false}, {-2, 1, -1},
{2, -5, true}, {2, -5, 1},
{0.0, 1.23, false}, {0.0, 1.23, -1},
{1.23, 0.0, true}, {1.23, 0.0, 1},
{"8", "5", true}, {"5", "5", 0},
{"5", "0001", true}, {"8", "5", 1},
{[]int{100, 99}, []int{1, 2, 3, 4}, false}, {"5", "0001", 1},
{[]int{100, 99}, []int{1, 2, 3, 4}, -1},
} { } {
leftIsBigger := Gt(this.left, this.right) result := funcUnderTest(this.left, this.right)
if leftIsBigger != this.leftShouldWin { success := false
var which string
if leftIsBigger { if this.expectIndicator == 0 {
which = "expected right to be bigger, but left was" if tstIsEq(tp) {
success = result
} else { } else {
which = "expected left to be bigger, but right was" success = !result
} }
t.Errorf("[%d] %v compared to %v: %s", i, this.left, this.right, which) }
if this.expectIndicator < 0 {
success = result && (tstIsLt(tp) || tp == tstNe)
success = success || (!result && !tstIsLt(tp))
}
if this.expectIndicator > 0 {
success = result && (tstIsGt(tp) || tp == tstNe)
success = success || (!result && (!tstIsGt(tp) || tp != tstNe))
}
if !success {
t.Errorf("[%d][%s] %v compared to %v: %t", i, path.Base(runtime.FuncForPC(reflect.ValueOf(funcUnderTest).Pointer()).Name()), this.left, this.right, result)
} }
} }
} }