Debian Codegraph @

doc.go

raw
1 // Licensed under the MIT license, see LICENSE file for details.
2
3 /*
4 Package quicktest provides a collection of Go helpers for writing tests.
5
6 Quicktest helpers can be easily integrated inside regular Go tests, for
7 instance:
8
9 import qt "github.com/frankban/quicktest"
10
11 func TestFoo(t *testing.T) {
12 t.Run("numbers", func(t *testing.T) {
13 c := qt.New(t)
14 numbers, err := somepackage.Numbers()
15 c.Assert(err, qt.IsNil)
16 c.Assert(numbers, qt.DeepEquals, []int{42, 47})
17 })
18 t.Run("bad wolf error", func(t *testing.T) {
19 c := qt.New(t)
20 numbers, err := somepackage.Numbers()
21 c.Assert(err, qt.ErrorMatches, "bad wolf")
22 })
23 t.Run("nil", func(t *testing.T) {
24 c := qt.New(t)
25 got := somepackage.MaybeNil()
26 c.Assert(got, qt.IsNil, qt.Commentf("value: %v", somepackage.Value))
27 })
28 }
29
30 # Assertions
31
32 An assertion looks like this, where qt.Equals could be replaced by any
33 available checker. If the assertion fails, the underlying Fatal method is
34 called to describe the error and abort the test.
35
36 c := qt.New(t)
37 c.Assert(someValue, qt.Equals, wantValue)
38
39 If you don’t want to abort on failure, use Check instead, which calls Error
40 instead of Fatal:
41
42 c.Check(someValue, qt.Equals, wantValue)
43
44 For really short tests, the extra line for instantiating *qt.C can be avoided:
45
46 qt.Assert(t, someValue, qt.Equals, wantValue)
47 qt.Check(t, someValue, qt.Equals, wantValue)
48
49 The library provides some base checkers like Equals, DeepEquals, Matches,
50 ErrorMatches, IsNil and others. More can be added by implementing the Checker
51 interface. Below, we list the checkers implemented by the package in alphabetical
52 order.
53
54 # All
55
56 All returns a Checker that uses the given checker to check elements of slice or
57 array or the values of a map. It succeeds if all elements pass the check.
58 On failure it prints the error from the first index that failed.
59
60 For example:
61
62 c.Assert([]int{3, 5, 8}, qt.All(qt.Not(qt.Equals)), 0)
63 c.Assert([][]string{{"a", "b"}, {"a", "b"}}, qt.All(qt.DeepEquals), []string{"c", "d"})
64
65 See also Any and Contains.
66
67 # Any
68
69 Any returns a Checker that uses the given checker to check elements of a slice
70 or array or the values from a map. It succeeds if any element passes the check.
71
72 For example:
73
74 c.Assert([]int{3,5,7,99}, qt.Any(qt.Equals), 7)
75 c.Assert([][]string{{"a", "b"}, {"c", "d"}}, qt.Any(qt.DeepEquals), []string{"c", "d"})
76
77 See also All and Contains.
78
79 # CmpEquals
80
81 CmpEquals checks equality of two arbitrary values according to the provided
82 compare options. DeepEquals is more commonly used when no compare options are
83 required.
84
85 Example calls:
86
87 c.Assert(list, qt.CmpEquals(cmpopts.SortSlices), []int{42, 47})
88 c.Assert(got, qt.CmpEquals(), []int{42, 47}) // Same as qt.DeepEquals.
89
90 # CodecEquals
91
92 CodecEquals returns a checker that checks for codec value equivalence.
93
94 func CodecEquals(
95 marshal func(interface{}) ([]byte, error),
96 unmarshal func([]byte, interface{}) error,
97 opts ...cmp.Option,
98 ) Checker
99
100 It expects two arguments: a byte slice or a string containing some
101 codec-marshaled data, and a Go value.
102
103 It uses unmarshal to unmarshal the data into an interface{} value.
104 It marshals the Go value using marshal, then unmarshals the result into
105 an interface{} value.
106
107 It then checks that the two interface{} values are deep-equal to one another,
108 using CmpEquals(opts) to perform the check.
109
110 See JSONEquals for an example of this in use.
111
112 # Contains
113
114 Contains checks that a map, slice, array or string contains a value. It's the
115 same as using Any(Equals), except that it has a special case for strings - if
116 the first argument is a string, the second argument must also be a string and
117 strings.Contains will be used.
118
119 For example:
120
121 c.Assert("hello world", qt.Contains, "world")
122 c.Assert([]int{3,5,7,99}, qt.Contains, 7)
123
124 # ContentEquals
125
126 ContentEquals is is like DeepEquals but any slices in the compared values will be sorted before being compared.
127
128 For example:
129
130 c.Assert([]string{"c", "a", "b"}, qt.ContentEquals, []string{"a", "b", "c"})
131
132 # DeepEquals
133
134 DeepEquals checks that two arbitrary values are deeply equal.
135 The comparison is done using the github.com/google/go-cmp/cmp package.
136 When comparing structs, by default no exported fields are allowed.
137 If a more sophisticated comparison is required, use CmpEquals (see below).
138
139 Example call:
140
141 c.Assert(got, qt.DeepEquals, []int{42, 47})
142
143 # Equals
144
145 Equals checks that two values are equal, as compared with Go's == operator.
146
147 For instance:
148
149 c.Assert(answer, qt.Equals, 42)
150
151 Note that the following will fail:
152
153 c.Assert((*sometype)(nil), qt.Equals, nil)
154
155 Use the IsNil checker below for this kind of nil check.
156
157 # ErrorAs
158
159 ErrorAs checks that the error is or wraps a specific error type. If so, it
160 assigns it to the provided pointer. This is analogous to calling errors.As.
161
162 For instance:
163
164 // Checking for a specific error type
165 c.Assert(err, qt.ErrorAs, new(*os.PathError))
166
167 // Checking fields on a specific error type
168 var pathError *os.PathError
169 if c.Check(err, qt.ErrorAs, &pathError) {
170 c.Assert(pathError.Path, Equals, "some_path")
171 }
172
173 # ErrorIs
174
175 ErrorIs checks that the error is or wraps a specific error value. This is
176 analogous to calling errors.Is.
177
178 For instance:
179
180 c.Assert(err, qt.ErrorIs, os.ErrNotExist)
181
182 # ErrorMatches
183
184 ErrorMatches checks that the provided value is an error whose message matches
185 the provided regular expression.
186
187 For instance:
188
189 c.Assert(err, qt.ErrorMatches, `bad wolf .*`)
190
191 # HasLen
192
193 HasLen checks that the provided value has the given length.
194
195 For instance:
196
197 c.Assert([]int{42, 47}, qt.HasLen, 2)
198 c.Assert(myMap, qt.HasLen, 42)
199
200 # Implements
201
202 Implements checks that the provided value implements an interface. The
203 interface is specified with a pointer to an interface variable.
204
205 For instance:
206
207 var rc io.ReadCloser
208 c.Assert(myReader, qt.Implements, &rc)
209
210 # IsFalse
211
212 IsFalse checks that the provided value is false.
213 The value must have a boolean underlying type.
214
215 For instance:
216
217 c.Assert(false, qt.IsFalse)
218 c.Assert(IsValid(), qt.IsFalse)
219
220 # IsNil
221
222 IsNil checks that the provided value is nil.
223
224 For instance:
225
226 c.Assert(got, qt.IsNil)
227
228 As a special case, if the value is nil but implements the
229 error interface, it is still considered to be non-nil.
230 This means that IsNil will fail on an error value that happens
231 to have an underlying nil value, because that's
232 invariably a mistake. See https://golang.org/doc/faq#nil_error.
233
234 So it's just fine to check an error like this:
235
236 c.Assert(err, qt.IsNil)
237
238 # IsNotNil
239
240 IsNotNil is a Checker checking that the provided value is not nil.
241 IsNotNil is the equivalent of qt.Not(qt.IsNil)
242
243 For instance:
244
245 c.Assert(got, qt.IsNotNil)
246
247 # IsTrue
248
249 IsTrue checks that the provided value is true.
250 The value must have a boolean underlying type.
251
252 For instance:
253
254 c.Assert(true, qt.IsTrue)
255 c.Assert(myBoolean(false), qt.IsTrue)
256
257 # JSONEquals
258
259 JSONEquals checks whether a byte slice or string is JSON-equivalent to a Go
260 value. See CodecEquals for more information.
261
262 It uses DeepEquals to do the comparison. If a more sophisticated comparison is
263 required, use CodecEquals directly.
264
265 For instance:
266
267 c.Assert(`{"First": 47.11}`, qt.JSONEquals, &MyStruct{First: 47.11})
268
269 # Matches
270
271 Matches checks that a string or result of calling the String method
272 (if the value implements fmt.Stringer) matches the provided regular expression.
273
274 For instance:
275
276 c.Assert("these are the voyages", qt.Matches, `these are .*`)
277 c.Assert(net.ParseIP("1.2.3.4"), qt.Matches, `1.*`)
278
279 # Not
280
281 Not returns a Checker negating the given Checker.
282
283 For instance:
284
285 c.Assert(got, qt.Not(qt.IsNil))
286 c.Assert(answer, qt.Not(qt.Equals), 42)
287
288 # PanicMatches
289
290 PanicMatches checks that the provided function panics with a message matching
291 the provided regular expression.
292
293 For instance:
294
295 c.Assert(func() {panic("bad wolf ...")}, qt.PanicMatches, `bad wolf .*`)
296
297 # Satisfies
298
299 Satisfies checks that the provided value, when used as argument of the provided
300 predicate function, causes the function to return true. The function must be of
301 type func(T) bool, having got assignable to T.
302
303 For instance:
304
305 // Check that an error from os.Open satisfies os.IsNotExist.
306 c.Assert(err, qt.Satisfies, os.IsNotExist)
307
308 // Check that a floating point number is a not-a-number.
309 c.Assert(f, qt.Satisfies, math.IsNaN)
310
311 # Deferred Execution
312
313 The testing.TB.Cleanup helper provides the ability to defer the execution of
314 functions that will be run when the test completes. This is often useful for
315 creating OS-level resources such as temporary directories (see c.Mkdir).
316
317 When targeting Go versions that don't have Cleanup (< 1.14), the same can be
318 achieved using c.Defer. In this case, to trigger the deferred behavior, calling
319 c.Done is required. For instance, if you create a *C instance at the top level,
320 you’ll have to add a defer to trigger the cleanups at the end of the test:
321
322 defer c.Done()
323
324 However, if you use quicktest to create a subtest, Done will be called
325 automatically at the end of that subtest. For example:
326
327 func TestFoo(t *testing.T) {
328 c := qt.New(t)
329 c.Run("subtest", func(c *qt.C) {
330 c.Setenv("HOME", c.Mkdir())
331 // Here $HOME is set the path to a newly created directory.
332 // At the end of the test the directory will be removed
333 // and HOME set back to its original value.
334 })
335 }
336
337 The c.Patch, c.Setenv, c.Unsetenv and c.Mkdir helpers use t.Cleanup for
338 cleaning up resources when available, and fall back to Defer otherwise.
339 */
340 package quicktest