Debian Codegraph @

htesting/hqt/checkers.go

raw
1 // Copyright 2019 The Hugo Authors. All rights reserved.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 // http://www.apache.org/licenses/LICENSE-2.0
7 //
8 // Unless required by applicable law or agreed to in writing, software
9 // distributed under the License is distributed on an "AS IS" BASIS,
10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 // See the License for the specific language governing permissions and
12 // limitations under the License.
13
14 package hqt
15
16 import (
17 "errors"
18 "fmt"
19 "math"
20 "reflect"
21 "strings"
22
23 qt "github.com/frankban/quicktest"
24 "github.com/gohugoio/hugo/htesting"
25 "github.com/google/go-cmp/cmp"
26 "github.com/spf13/cast"
27 )
28
29 // IsSameString asserts that two strings are equal. The two strings
30 // are normalized (whitespace removed) before doing a ==.
31 // Also note that two strings can be the same even if they're of different
32 // types.
33 var IsSameString qt.Checker = &stringChecker{
34 argNames: []string{"got", "want"},
35 }
36
37 // IsSameType asserts that got is the same type as want.
38 var IsSameType qt.Checker = &typeChecker{
39 argNames: []string{"got", "want"},
40 }
41
42 // IsSameFloat64 asserts that two float64 values are equal within a small delta.
43 var IsSameFloat64 = qt.CmpEquals(cmp.Comparer(func(a, b float64) bool {
44 return math.Abs(a-b) < 0.0001
45 }))
46
47 // IsSameNumber asserts that two number values are equal within a small delta.
48 var IsSameNumber = qt.CmpEquals(
49 cmp.Comparer(func(a, b float64) bool {
50 return math.Abs(a-b) < 0.0001
51 }),
52 cmp.Comparer(func(a, b float32) bool {
53 return math.Abs(float64(a)-float64(b)) < 0.0001
54 }),
55 cmp.Comparer(func(a, b int) bool {
56 return a == b
57 }),
58 cmp.Comparer(func(a, b int8) bool {
59 return a == b
60 }),
61 cmp.Comparer(func(a, b int16) bool {
62 return a == b
63 }),
64 cmp.Comparer(func(a, b int32) bool {
65 return a == b
66 }),
67 cmp.Comparer(func(a, b int64) bool {
68 return a == b
69 }),
70 cmp.Comparer(func(a, b uint) bool {
71 return a == b
72 }),
73 cmp.Comparer(func(a, b uint8) bool {
74 return a == b
75 }),
76 cmp.Comparer(func(a, b uint16) bool {
77 return a == b
78 }),
79 cmp.Comparer(func(a, b uint32) bool {
80 return a == b
81 }),
82 cmp.Comparer(func(a, b uint64) bool {
83 return a == b
84 }),
85 )
86
87 type argNames []string
88
89 func (a argNames) ArgNames() []string {
90 return a
91 }
92
93 type typeChecker struct {
94 argNames
95 }
96
97 // Check implements Checker.Check by checking that got and args[0] is of the same type.
98 func (c *typeChecker) Check(got any, args []any, note func(key string, value any)) (err error) {
99 if want := args[0]; reflect.TypeOf(got) != reflect.TypeOf(want) {
100 if _, ok := got.(error); ok && want == nil {
101 return errors.New("got non-nil error")
102 }
103 return errors.New("values are not of same type")
104 }
105 return nil
106 }
107
108 type stringChecker struct {
109 argNames
110 }
111
112 // Check implements Checker.Check by checking that got and args[0] represents the same normalized text (whitespace etc. removed).
113 func (c *stringChecker) Check(got any, args []any, note func(key string, value any)) (err error) {
114 s1, s2 := cast.ToString(got), cast.ToString(args[0])
115
116 if s1 == s2 {
117 return nil
118 }
119
120 s1, s2 = normalizeString(s1), normalizeString(s2)
121
122 if s1 == s2 {
123 return nil
124 }
125
126 return fmt.Errorf("values are not the same text: %s", strings.Join(htesting.DiffStrings(s1, s2), " | "))
127 }
128
129 func normalizeString(s string) string {
130 s = strings.ReplaceAll(s, "\r\n", "\n")
131
132 lines := strings.Split(strings.TrimSpace(s), "\n")
133 for i, line := range lines {
134 lines[i] = strings.Join(strings.Fields(strings.TrimSpace(line)), "")
135 }
136 return strings.Join(lines, "\n")
137 }
138
139 // IsAllElementsEqual asserts that all elements in the slice are equal.
140 var IsAllElementsEqual qt.Checker = &sliceAllElementsEqualChecker{
141 argNames: []string{"got"},
142 }
143
144 type sliceAllElementsEqualChecker struct {
145 argNames
146 }
147
148 func (c *sliceAllElementsEqualChecker) Check(got any, args []any, note func(key string, value any)) (err error) {
149 gotSlice := reflect.ValueOf(got)
150 numElements := gotSlice.Len()
151 if numElements < 2 {
152 return nil
153 }
154 first := gotSlice.Index(0).Interface()
155 // Check that the others are equal to the first.
156 for i := 1; i < numElements; i++ {
157 if diff := cmp.Diff(first, gotSlice.Index(i).Interface()); diff != "" {
158 return fmt.Errorf("element %d is not equal to the first element:\n%s", i, diff)
159 }
160 }
161
162 return nil
163 }
164
165 // DeepAllowUnexported creates an option to allow compare of unexported types
166 // in the given list of types.
167 // see https://github.com/google/go-cmp/issues/40#issuecomment-328615283
168 func DeepAllowUnexported(vs ...any) cmp.Option {
169 m := make(map[reflect.Type]struct{})
170 for _, v := range vs {
171 structTypes(reflect.ValueOf(v), m)
172 }
173 var typs []any
174 for t := range m {
175 typs = append(typs, reflect.New(t).Elem().Interface())
176 }
177 return cmp.AllowUnexported(typs...)
178 }
179
180 func structTypes(v reflect.Value, m map[reflect.Type]struct{}) {
181 if !v.IsValid() {
182 return
183 }
184 switch v.Kind() {
185 case reflect.Pointer:
186 if !v.IsNil() {
187 structTypes(v.Elem(), m)
188 }
189 case reflect.Interface:
190 if !v.IsNil() {
191 structTypes(v.Elem(), m)
192 }
193 case reflect.Slice, reflect.Array:
194 for i := range v.Len() {
195 structTypes(v.Index(i), m)
196 }
197 case reflect.Map:
198 for _, k := range v.MapKeys() {
199 structTypes(v.MapIndex(k), m)
200 }
201 case reflect.Struct:
202 m[v.Type()] = struct{}{}
203 for _, field := range v.Fields() {
204 structTypes(field, m)
205 }
206 }
207 }