Debian Codegraph @

td/cmp_deeply.go

raw
1 // Copyright (c) 2018, Maxime Soulé
2 // All rights reserved.
3 //
4 // This source code is licensed under the BSD-style license found in the
5 // LICENSE file in the root directory of this source tree.
6
7 package td
8
9 import (
10 "reflect"
11 "strings"
12
13 "github.com/maxatome/go-testdeep/helpers/tdutil"
14 "github.com/maxatome/go-testdeep/internal/color"
15 "github.com/maxatome/go-testdeep/internal/ctxerr"
16 "github.com/maxatome/go-testdeep/internal/flat"
17 "github.com/maxatome/go-testdeep/internal/trace"
18 )
19
20 func init() {
21 trace.Init()
22 trace.IgnorePackage()
23 }
24
25 // stripTrace removes go-testdeep useless calls in a trace returned by
26 // trace.Retrieve() to make it clearer for the reader.
27 func stripTrace(s trace.Stack) trace.Stack {
28 if len(s) == 0 {
29 return s
30 }
31
32 const (
33 tdPkg = "github.com/maxatome/go-testdeep/td"
34 tdhttpPkg = "github.com/maxatome/go-testdeep/helpers/tdhttp"
35 tdsuitePkg = "github.com/maxatome/go-testdeep/helpers/tdsuite"
36 )
37
38 // Remove useless possible (*T).Run() or (*T).RunAssertRequire() first call
39 if s.Match(-1, tdPkg, "(*T).Run.func1", "(*T).RunAssertRequire.func1") {
40 // Remove useless tdhttp (*TestAPI).Run() call
41 //
42 // ✓ xxx Subtest.func1()
43 // ✗ …/tdhttp (*TestAPI).Run.func1
44 // ✗ …/td (*T).Run.func1()
45 if s.Match(-2, tdhttpPkg, "(*TestAPI).Run.func1") {
46 return s[:len(s)-2]
47 }
48
49 // Remove useless tdsuite calls
50 //
51 // ✓ xxx Suite.TestSuite
52 // ✗ reflect Value.call
53 // ✗ reflect Value.Call
54 // ✗ …/tdsuite run.func2
55 // ✗ …/td (*T).Run.func1() or (*T).RunAssertRequire.func1()
56 //
57 // or for PostTest
58 // ✓ xxx Suite.PostTest
59 // ✗ …/tdsuite run.func2.1
60 // ✗ …/tdsuite run.func2
61 // ✗ …/td (*T).Run.func1() or (*T).RunAssertRequire.func1()
62 if s.Match(-2, tdsuitePkg, "run.func*") {
63 // PostTest
64 if s.Match(-3, tdsuitePkg, "run.func*") &&
65 len(s) > 4 &&
66 strings.HasSuffix(s[len(s)-4].Func, ".PostTest") {
67 return s[:len(s)-3]
68 }
69
70 for i := len(s) - 3; i >= 1; i-- {
71 if !s.Match(i, "reflect") {
72 return s[:i+1]
73 }
74 }
75 return nil
76 }
77
78 return s[:len(s)-1]
79 }
80
81 // Remove testing.Cleanup() stack
82 //
83 // ✓ xxx TestCleanup.func2
84 // ✗ testing (*common).Cleanup.func1
85 // ✗ testing (*common).runCleanup
86 // ✗ testing tRunner.func2
87 if s.Match(-1, "testing", "tRunner.func*") &&
88 s.Match(-2, "testing", "(*common).runCleanup") &&
89 s.Match(-3, "testing", "(*common).Cleanup.func1") {
90 return s[:len(s)-3]
91 }
92
93 // Remove tdsuite pre-Setup/BetweenTests/Destroy stack
94 //
95 // ✓ xxx Suite.Destroy
96 // ✗ …/tdsuite run.func1
97 // ✗ …/tdsuite run
98 // ✗ …/tdsuite Run
99 // ✓ xxx TestSuiteDestroy
100 if !s.Match(-1, tdsuitePkg) &&
101 s.Match(-2, tdsuitePkg, "Run") {
102 for i := len(s) - 3; i >= 0; i-- {
103 if !s.Match(i, tdsuitePkg) {
104 s[i+1] = s[len(s)-1]
105 return s[:i+2]
106 }
107 }
108 return s[:1]
109 }
110
111 return s
112 }
113
114 func formatError(t TestingT, isFatal bool, err *ctxerr.Error, args ...any) {
115 t.Helper()
116
117 const failedTest = "Failed test"
118
119 args = flat.Interfaces(args...)
120
121 var buf strings.Builder
122 color.AppendTestNameOn(&buf)
123 if len(args) == 0 {
124 buf.WriteString(failedTest)
125 } else {
126 buf.WriteString(failedTest + " '")
127 tdutil.FbuildTestName(&buf, args...)
128 buf.WriteString("'")
129 }
130 color.AppendTestNameOff(&buf)
131 buf.WriteString("\n")
132
133 err.Append(&buf, "", true)
134
135 // Stask trace
136 if s := stripTrace(trace.Retrieve(0, "testing.tRunner")); s.IsRelevant() {
137 buf.WriteString("\nThis is how we got here:\n")
138 s.Dump(&buf)
139 }
140
141 if isFatal {
142 t.Fatal(buf.String())
143 } else {
144 t.Error(buf.String())
145 }
146 }
147
148 func cmpDeeply(ctx ctxerr.Context, t TestingT, got, expected any,
149 args ...any,
150 ) bool {
151 err := deepValueEqualFinal(ctx,
152 reflect.ValueOf(got), reflect.ValueOf(expected))
153 if err == nil {
154 return true
155 }
156
157 t.Helper()
158 formatError(t, ctx.FailureIsFatal, err, args...)
159 return false
160 }
161
162 // S returns a string based on args as Cmp* functions do with their
163 // own args parameter to name their test. So behind the scenes,
164 // [tdutil.BuildTestName] is used.
165 //
166 // If len(args) > 1 and the first item of args is a string and
167 // contains a '%' rune then [fmt.Fprintf] is used to compose the
168 // returned string, else args are passed to [fmt.Fprint].
169 //
170 // It can be used as a shorter [fmt.Sprintf]:
171 //
172 // t.Run(fmt.Sprintf("Foo #%d", i), func(t *td.T) {})
173 // t.Run(td.S("Foo #%d", i), func(t *td.T) {})
174 //
175 // or to print any values as [fmt.Sprint] handles them:
176 //
177 // a, ok := []int{1, 2, 3}, true
178 // t.Run(fmt.Sprint(a, ok), func(t *td.T) {})
179 // t.Run(td.S(a, ok), func(t *td.T) {})
180 //
181 // The only gain is less characters to type.
182 func S(args ...any) string {
183 return tdutil.BuildTestName(args...)
184 }
185
186 // Cmp returns true if got matches expected. expected can
187 // be the same type as got is, or contains some [TestDeep]
188 // operators. If got does not match expected, it returns false and
189 // the reason of failure is logged with the help of t Error()
190 // method.
191 //
192 // got := "foobar"
193 // td.Cmp(t, got, "foobar") // succeeds
194 // td.Cmp(t, got, td.HasPrefix("foo")) // succeeds
195 //
196 // If t is a [*T] then its Config is inherited, so:
197 //
198 // td.Cmp(td.Require(t), got, 42)
199 //
200 // is the same as:
201 //
202 // td.Require(t).Cmp(got, 42)
203 //
204 // args... are optional and allow to name the test. This name is
205 // used in case of failure to qualify the test. If len(args) > 1 and
206 // the first item of args is a string and contains a '%' rune then
207 // [fmt.Fprintf] is used to compose the name, else args are passed to
208 // [fmt.Fprint]. Do not forget it is the name of the test, not the
209 // reason of a potential failure.
210 func Cmp(t TestingT, got, expected any, args ...any) bool {
211 t.Helper()
212 return cmpDeeply(newContext(t), t, got, expected, args...)
213 }
214
215 // CmpDeeply works the same as [Cmp] and is still available for
216 // compatibility purpose. Use shorter [Cmp] in new code.
217 //
218 // got := "foobar"
219 // td.CmpDeeply(t, got, "foobar") // succeeds
220 // td.CmpDeeply(t, got, td.HasPrefix("foo")) // succeeds
221 func CmpDeeply(t TestingT, got, expected any, args ...any) bool {
222 t.Helper()
223 return cmpDeeply(newContext(t), t, got, expected, args...)
224 }