Debian Codegraph @

checkers.go

raw symbols SCIP
1 package check
2
3 import (
4 "fmt"
5 "reflect"
6 "regexp"
7 )
8
9 // -----------------------------------------------------------------------
10 // CommentInterface and Commentf helper, to attach extra information to checks.
11
12 type comment struct {
13 format string
14 args []interface{}
15 }
16
17 // Commentf returns an infomational value to use with Assert or Check calls.
18 // If the checker test fails, the provided arguments will be passed to
19 // fmt.Sprintf, and will be presented next to the logged failure.
20 //
21 // For example:
22 //
23 // c.Assert(v, Equals, 42, Commentf("Iteration #%d failed.", i))
24 //
25 // Note that if the comment is constant, a better option is to
26 // simply use a normal comment right above or next to the line, as
27 // it will also get printed with any errors:
28 //
29 // c.Assert(l, Equals, 8192) // Ensure buffer size is correct (bug #123)
30 //
31 func Commentf(format string, args ...interface{}) CommentInterface {
32 return &comment{format, args}
33 }
34
35 // CommentInterface must be implemented by types that attach extra
36 // information to failed checks. See the Commentf function for details.
37 type CommentInterface interface {
38 CheckCommentString() string
39 }
40
41 func (c *comment) CheckCommentString() string {
42 return fmt.Sprintf(c.format, c.args...)
43 }
44
45 // -----------------------------------------------------------------------
46 // The Checker interface.
47
48 // The Checker interface must be provided by checkers used with
49 // the Assert and Check verification methods.
50 type Checker interface {
51 Info() *CheckerInfo
52 Check(params []interface{}, names []string) (result bool, error string)
53 }
54
55 // See the Checker interface.
56 type CheckerInfo struct {
57 Name string
58 Params []string
59 }
60
61 func (info *CheckerInfo) Info() *CheckerInfo {
62 return info
63 }
64
65 // -----------------------------------------------------------------------
66 // Not checker logic inverter.
67
68 // The Not checker inverts the logic of the provided checker. The
69 // resulting checker will succeed where the original one failed, and
70 // vice-versa.
71 //
72 // For example:
73 //
74 // c.Assert(a, Not(Equals), b)
75 //
76 func Not(checker Checker) Checker {
77 return &notChecker{checker}
78 }
79
80 type notChecker struct {
81 sub Checker
82 }
83
84 func (checker *notChecker) Info() *CheckerInfo {
85 info := *checker.sub.Info()
86 info.Name = "Not(" + info.Name + ")"
87 return &info
88 }
89
90 func (checker *notChecker) Check(params []interface{}, names []string) (result bool, error string) {
91 result, error = checker.sub.Check(params, names)
92 result = !result
93 return
94 }
95
96 // -----------------------------------------------------------------------
97 // IsNil checker.
98
99 type isNilChecker struct {
100 *CheckerInfo
101 }
102
103 // The IsNil checker tests whether the obtained value is nil.
104 //
105 // For example:
106 //
107 // c.Assert(err, IsNil)
108 //
109 var IsNil Checker = &isNilChecker{
110 &CheckerInfo{Name: "IsNil", Params: []string{"value"}},
111 }
112
113 func (checker *isNilChecker) Check(params []interface{}, names []string) (result bool, error string) {
114 return isNil(params[0]), ""
115 }
116
117 func isNil(obtained interface{}) (result bool) {
118 if obtained == nil {
119 result = true
120 } else {
121 switch v := reflect.ValueOf(obtained); v.Kind() {
122 case reflect.Chan, reflect.Func, reflect.Interface, reflect.Map, reflect.Ptr, reflect.Slice:
123 return v.IsNil()
124 }
125 }
126 return
127 }
128
129 // -----------------------------------------------------------------------
130 // NotNil checker. Alias for Not(IsNil), since it's so common.
131
132 type notNilChecker struct {
133 *CheckerInfo
134 }
135
136 // The NotNil checker verifies that the obtained value is not nil.
137 //
138 // For example:
139 //
140 // c.Assert(iface, NotNil)
141 //
142 // This is an alias for Not(IsNil), made available since it's a
143 // fairly common check.
144 //
145 var NotNil Checker = &notNilChecker{
146 &CheckerInfo{Name: "NotNil", Params: []string{"value"}},
147 }
148
149 func (checker *notNilChecker) Check(params []interface{}, names []string) (result bool, error string) {
150 return !isNil(params[0]), ""
151 }
152
153 // -----------------------------------------------------------------------
154 // Equals checker.
155
156 type equalsChecker struct {
157 *CheckerInfo
158 }
159
160 // The Equals checker verifies that the obtained value is equal to
161 // the expected value, according to usual Go semantics for ==.
162 //
163 // For example:
164 //
165 // c.Assert(value, Equals, 42)
166 //
167 var Equals Checker = &equalsChecker{
168 &CheckerInfo{Name: "Equals", Params: []string{"obtained", "expected"}},
169 }
170
171 func (checker *equalsChecker) Check(params []interface{}, names []string) (result bool, error string) {
172 defer func() {
173 if v := recover(); v != nil {
174 result = false
175 error = fmt.Sprint(v)
176 }
177 }()
178 return params[0] == params[1], ""
179 }
180
181 // -----------------------------------------------------------------------
182 // DeepEquals checker.
183
184 type deepEqualsChecker struct {
185 *CheckerInfo
186 }
187
188 // The DeepEquals checker verifies that the obtained value is deep-equal to
189 // the expected value. The check will work correctly even when facing
190 // slices, interfaces, and values of different types (which always fail
191 // the test).
192 //
193 // For example:
194 //
195 // c.Assert(value, DeepEquals, 42)
196 // c.Assert(array, DeepEquals, []string{"hi", "there"})
197 //
198 var DeepEquals Checker = &deepEqualsChecker{
199 &CheckerInfo{Name: "DeepEquals", Params: []string{"obtained", "expected"}},
200 }
201
202 func (checker *deepEqualsChecker) Check(params []interface{}, names []string) (result bool, error string) {
203 return reflect.DeepEqual(params[0], params[1]), ""
204 }
205
206 // -----------------------------------------------------------------------
207 // EqualsIn checker.
208
209 type equalsInChecker struct {
210 *CheckerInfo
211 }
212
213 // The EqualsIn checker verifies that the obtained value is equal to
214 // one of the expected values, according to usual Go semantics for ==.
215 //
216 // For example:
217 //
218 // c.Assert(value, EqualsIn, []interface{}{42, "42"} )
219 //
220 var EqualsIn Checker = &equalsInChecker{
221 &CheckerInfo{Name: "EqualsIn", Params: []string{"obtained", "expected"}},
222 }
223
224 func (checker *equalsInChecker) Check(params []interface{}, names []string) (result bool, error string) {
225 defer func() {
226 if v := recover(); v != nil {
227 result = false
228 error = fmt.Sprint(v)
229 }
230 }()
231 for _, v := range params[1].([]interface{}) {
232 if params[0] == v {
233 return true, ""
234 }
235 }
236 return false, ""
237 }
238
239 // -----------------------------------------------------------------------
240 // EqualsIn checker.
241
242 type deepEqualsInChecker struct {
243 *CheckerInfo
244 }
245
246 // The EqualsIn checker verifies that the obtained value is equal to
247 // one of the expected values, according to usual Go semantics for ==.
248 //
249 // For example:
250 //
251 // c.Assert(value, EqualsIn, []interface{}{42, "42"} )
252 //
253 var DeepEqualsIn Checker = &deepEqualsInChecker{
254 &CheckerInfo{Name: "DeepEqualsIn", Params: []string{"obtained", "expected"}},
255 }
256
257 func (checker *deepEqualsInChecker) Check(params []interface{}, names []string) (result bool, error string) {
258 defer func() {
259 if v := recover(); v != nil {
260 result = false
261 error = fmt.Sprint(v)
262 }
263 }()
264 for _, v := range params[1].([]interface{}) {
265 if reflect.DeepEqual(params[0], v) {
266 return true, ""
267 }
268 }
269 return false, ""
270 }
271
272 // -----------------------------------------------------------------------
273 // HasLen checker.
274
275 type hasLenChecker struct {
276 *CheckerInfo
277 }
278
279 // The HasLen checker verifies that the obtained value has the
280 // provided length. In many cases this is superior to using Equals
281 // in conjunction with the len function because in case the check
282 // fails the value itself will be printed, instead of its length,
283 // providing more details for figuring the problem.
284 //
285 // For example:
286 //
287 // c.Assert(list, HasLen, 5)
288 //
289 var HasLen Checker = &hasLenChecker{
290 &CheckerInfo{Name: "HasLen", Params: []string{"obtained", "n"}},
291 }
292
293 func (checker *hasLenChecker) Check(params []interface{}, names []string) (result bool, error string) {
294 n, ok := params[1].(int)
295 if !ok {
296 return false, "n must be an int"
297 }
298 value := reflect.ValueOf(params[0])
299 switch value.Kind() {
300 case reflect.Map, reflect.Array, reflect.Slice, reflect.Chan, reflect.String:
301 default:
302 return false, "obtained value type has no length"
303 }
304 return value.Len() == n, ""
305 }
306
307 // -----------------------------------------------------------------------
308 // ErrorMatches checker.
309
310 type errorMatchesChecker struct {
311 *CheckerInfo
312 }
313
314 // The ErrorMatches checker verifies that the error value
315 // is non nil and matches the regular expression provided.
316 //
317 // For example:
318 //
319 // c.Assert(err, ErrorMatches, "perm.*denied")
320 //
321 var ErrorMatches Checker = errorMatchesChecker{
322 &CheckerInfo{Name: "ErrorMatches", Params: []string{"value", "regex"}},
323 }
324
325 func (checker errorMatchesChecker) Check(params []interface{}, names []string) (result bool, errStr string) {
326 if params[0] == nil {
327 return false, "Error value is nil"
328 }
329 err, ok := params[0].(error)
330 if !ok {
331 return false, "Value is not an error"
332 }
333 params[0] = err.Error()
334 names[0] = "error"
335 return matches(params[0], params[1])
336 }
337
338 // -----------------------------------------------------------------------
339 // Matches checker.
340
341 type matchesChecker struct {
342 *CheckerInfo
343 }
344
345 // The Matches checker verifies that the string provided as the obtained
346 // value (or the string resulting from obtained.String()) matches the
347 // regular expression provided.
348 //
349 // For example:
350 //
351 // c.Assert(err, Matches, "perm.*denied")
352 //
353 var Matches Checker = &matchesChecker{
354 &CheckerInfo{Name: "Matches", Params: []string{"value", "regex"}},
355 }
356
357 func (checker *matchesChecker) Check(params []interface{}, names []string) (result bool, error string) {
358 return matches(params[0], params[1])
359 }
360
361 func matches(value, regex interface{}) (result bool, error string) {
362 reStr, ok := regex.(string)
363 if !ok {
364 return false, "Regex must be a string"
365 }
366 valueStr, valueIsStr := value.(string)
367 if !valueIsStr {
368 if valueWithStr, valueHasStr := value.(fmt.Stringer); valueHasStr {
369 valueStr, valueIsStr = valueWithStr.String(), true
370 }
371 }
372 if valueIsStr {
373 matches, err := regexp.MatchString("^"+reStr+"$", valueStr)
374 if err != nil {
375 return false, "Can't compile regex: " + err.Error()
376 }
377 return matches, ""
378 }
379 return false, "Obtained value is not a string and has no .String()"
380 }
381
382 // -----------------------------------------------------------------------
383 // Panics checker.
384
385 type panicsChecker struct {
386 *CheckerInfo
387 }
388
389 // The Panics checker verifies that calling the provided zero-argument
390 // function will cause a panic which is deep-equal to the provided value.
391 //
392 // For example:
393 //
394 // c.Assert(func() { f(1, 2) }, Panics, &SomeErrorType{"BOOM"}).
395 //
396 //
397 var Panics Checker = &panicsChecker{
398 &CheckerInfo{Name: "Panics", Params: []string{"function", "expected"}},
399 }
400
401 func (checker *panicsChecker) Check(params []interface{}, names []string) (result bool, error string) {
402 f := reflect.ValueOf(params[0])
403 if f.Kind() != reflect.Func || f.Type().NumIn() != 0 {
404 return false, "Function must take zero arguments"
405 }
406 defer func() {
407 // If the function has not panicked, then don't do the check.
408 if error != "" {
409 return
410 }
411 params[0] = recover()
412 names[0] = "panic"
413 result = reflect.DeepEqual(params[0], params[1])
414 }()
415 f.Call(nil)
416 return false, "Function has not panicked"
417 }
418
419 type panicMatchesChecker struct {
420 *CheckerInfo
421 }
422
423 // The PanicMatches checker verifies that calling the provided zero-argument
424 // function will cause a panic with an error value matching
425 // the regular expression provided.
426 //
427 // For example:
428 //
429 // c.Assert(func() { f(1, 2) }, PanicMatches, `open.*: no such file or directory`).
430 //
431 //
432 var PanicMatches Checker = &panicMatchesChecker{
433 &CheckerInfo{Name: "PanicMatches", Params: []string{"function", "expected"}},
434 }
435
436 func (checker *panicMatchesChecker) Check(params []interface{}, names []string) (result bool, errmsg string) {
437 f := reflect.ValueOf(params[0])
438 if f.Kind() != reflect.Func || f.Type().NumIn() != 0 {
439 return false, "Function must take zero arguments"
440 }
441 defer func() {
442 // If the function has not panicked, then don't do the check.
443 if errmsg != "" {
444 return
445 }
446 obtained := recover()
447 names[0] = "panic"
448 if e, ok := obtained.(error); ok {
449 params[0] = e.Error()
450 } else if _, ok := obtained.(string); ok {
451 params[0] = obtained
452 } else {
453 errmsg = "Panic value is not a string or an error"
454 return
455 }
456 result, errmsg = matches(params[0], params[1])
457 }()
458 f.Call(nil)
459 return false, "Function has not panicked"
460 }
461
462 // -----------------------------------------------------------------------
463 // FitsTypeOf checker.
464
465 type fitsTypeChecker struct {
466 *CheckerInfo
467 }
468
469 // The FitsTypeOf checker verifies that the obtained value is
470 // assignable to a variable with the same type as the provided
471 // sample value.
472 //
473 // For example:
474 //
475 // c.Assert(value, FitsTypeOf, int64(0))
476 // c.Assert(value, FitsTypeOf, os.Error(nil))
477 //
478 var FitsTypeOf Checker = &fitsTypeChecker{
479 &CheckerInfo{Name: "FitsTypeOf", Params: []string{"obtained", "sample"}},
480 }
481
482 func (checker *fitsTypeChecker) Check(params []interface{}, names []string) (result bool, error string) {
483 obtained := reflect.ValueOf(params[0])
484 sample := reflect.ValueOf(params[1])
485 if !obtained.IsValid() {
486 return false, ""
487 }
488 if !sample.IsValid() {
489 return false, "Invalid sample value"
490 }
491 return obtained.Type().AssignableTo(sample.Type()), ""
492 }
493
494 // -----------------------------------------------------------------------
495 // Implements checker.
496
497 type implementsChecker struct {
498 *CheckerInfo
499 }
500
501 // The Implements checker verifies that the obtained value
502 // implements the interface specified via a pointer to an interface
503 // variable.
504 //
505 // For example:
506 //
507 // var e os.Error
508 // c.Assert(err, Implements, &e)
509 //
510 var Implements Checker = &implementsChecker{
511 &CheckerInfo{Name: "Implements", Params: []string{"obtained", "ifaceptr"}},
512 }
513
514 func (checker *implementsChecker) Check(params []interface{}, names []string) (result bool, error string) {
515 obtained := reflect.ValueOf(params[0])
516 ifaceptr := reflect.ValueOf(params[1])
517 if !obtained.IsValid() {
518 return false, ""
519 }
520 if !ifaceptr.IsValid() || ifaceptr.Kind() != reflect.Ptr || ifaceptr.Elem().Kind() != reflect.Interface {
521 return false, "ifaceptr should be a pointer to an interface variable"
522 }
523 return obtained.Type().Implements(ifaceptr.Elem().Type()), ""
524 }