...
1 package assert
2
3 import (
4 "fmt"
5 "reflect"
6 )
7
8
9 func isOrdered(t TestingT, object interface{}, allowedComparesResults []CompareType, failMessage string, msgAndArgs ...interface{}) bool {
10 objKind := reflect.TypeOf(object).Kind()
11 if objKind != reflect.Slice && objKind != reflect.Array {
12 return false
13 }
14
15 objValue := reflect.ValueOf(object)
16 objLen := objValue.Len()
17
18 if objLen <= 1 {
19 return true
20 }
21
22 value := objValue.Index(0)
23 valueInterface := value.Interface()
24 firstValueKind := value.Kind()
25
26 for i := 1; i < objLen; i++ {
27 prevValue := value
28 prevValueInterface := valueInterface
29
30 value = objValue.Index(i)
31 valueInterface = value.Interface()
32
33 compareResult, isComparable := compare(prevValueInterface, valueInterface, firstValueKind)
34
35 if !isComparable {
36 return Fail(t, fmt.Sprintf("Can not compare type \"%s\" and \"%s\"", reflect.TypeOf(value), reflect.TypeOf(prevValue)), msgAndArgs...)
37 }
38
39 if !containsValue(allowedComparesResults, compareResult) {
40 return Fail(t, fmt.Sprintf(failMessage, prevValue, value), msgAndArgs...)
41 }
42 }
43
44 return true
45 }
46
47
48
49
50
51
52 func IsIncreasing(t TestingT, object interface{}, msgAndArgs ...interface{}) bool {
53 return isOrdered(t, object, []CompareType{compareLess}, "\"%v\" is not less than \"%v\"", msgAndArgs...)
54 }
55
56
57
58
59
60
61 func IsNonIncreasing(t TestingT, object interface{}, msgAndArgs ...interface{}) bool {
62 return isOrdered(t, object, []CompareType{compareEqual, compareGreater}, "\"%v\" is not greater than or equal to \"%v\"", msgAndArgs...)
63 }
64
65
66
67
68
69
70 func IsDecreasing(t TestingT, object interface{}, msgAndArgs ...interface{}) bool {
71 return isOrdered(t, object, []CompareType{compareGreater}, "\"%v\" is not greater than \"%v\"", msgAndArgs...)
72 }
73
74
75
76
77
78
79 func IsNonDecreasing(t TestingT, object interface{}, msgAndArgs ...interface{}) bool {
80 return isOrdered(t, object, []CompareType{compareLess, compareEqual}, "\"%v\" is not less than or equal to \"%v\"", msgAndArgs...)
81 }
82
View as plain text