Debian Codegraph @

checker.go

raw
1 // Licensed under the MIT license, see LICENSE file for details.
2
3 package quicktest
4
5 import (
6 "encoding/json"
7 "errors"
8 "fmt"
9 "reflect"
10 "regexp"
11 "strings"
12
13 "github.com/google/go-cmp/cmp"
14 "github.com/google/go-cmp/cmp/cmpopts"
15 "github.com/kr/pretty"
16 )
17
18 // Checker is implemented by types used as part of Check/Assert invocations.
19 type Checker interface {
20 // Check checks that the obtained value (got) is correct with respect to
21 // the checker's arguments (args). On failure, the returned error is
22 // printed along with the checker arguments and any key-value pairs added
23 // by calling the note function. Values are pretty-printed unless they are
24 // of type Unquoted.
25 //
26 // When the check arguments are invalid, Check may return a BadCheck error,
27 // which suppresses printing of the checker arguments. Values added with
28 // note are still printed.
29 //
30 // If Check returns ErrSilent, neither the checker arguments nor the error
31 // are printed. Again, values added with note are still printed.
32 Check(got interface{}, args []interface{}, note func(key string, value interface{})) error
33
34 // ArgNames returns the names of all required arguments, including the
35 // mandatory got argument and any additional args.
36 ArgNames() []string
37 }
38
39 // Equals is a Checker checking equality of two comparable values.
40 //
41 // For instance:
42 //
43 // c.Assert(answer, qt.Equals, 42)
44 //
45 // Note that the following will fail:
46 //
47 // c.Assert((*sometype)(nil), qt.Equals, nil)
48 //
49 // Use the IsNil checker below for this kind of nil check.
50 var Equals Checker = &equalsChecker{
51 argNames: []string{"got", "want"},
52 }
53
54 type equalsChecker struct {
55 argNames
56 }
57
58 // Check implements Checker.Check by checking that got == args[0].
59 func (c *equalsChecker) Check(got interface{}, args []interface{}, note func(key string, value interface{})) (err error) {
60 defer func() {
61 // A panic is raised when the provided values are not comparable.
62 if r := recover(); r != nil {
63 err = fmt.Errorf("%s", r)
64 }
65 }()
66 want := args[0]
67 if got == want {
68 return nil
69 }
70
71 // Customize error message for non-nil errors.
72 if _, ok := got.(error); ok && want == nil {
73 return errors.New("got non-nil error")
74 }
75
76 // Show error types when comparing errors with different types.
77 if got, ok := got.(error); ok {
78 if want, ok := want.(error); ok {
79 gotType := reflect.TypeOf(got)
80 wantType := reflect.TypeOf(want)
81 if gotType != wantType {
82 note("got type", Unquoted(gotType.String()))
83 note("want type", Unquoted(wantType.String()))
84 }
85 }
86 return errors.New("values are not equal")
87 }
88
89 // Show line diff when comparing different multi-line strings.
90 if got, ok := got.(string); ok {
91 if want, ok := want.(string); ok {
92 isMultiLine := func(s string) bool {
93 i := strings.Index(s, "\n")
94 return i != -1 && i < len(s)-1
95 }
96 if isMultiLine(got) || isMultiLine(want) {
97 diff := cmp.Diff(strings.SplitAfter(got, "\n"), strings.SplitAfter(want, "\n"))
98 note("line diff (-got +want)", Unquoted(diff))
99 }
100 }
101 }
102
103 return errors.New("values are not equal")
104 }
105
106 // CmpEquals returns a Checker checking equality of two arbitrary values
107 // according to the provided compare options. See DeepEquals as an example of
108 // such a checker, commonly used when no compare options are required.
109 //
110 // Example calls:
111 //
112 // c.Assert(list, qt.CmpEquals(cmpopts.SortSlices), []int{42, 47})
113 // c.Assert(got, qt.CmpEquals(), []int{42, 47}) // Same as qt.DeepEquals.
114 func CmpEquals(opts ...cmp.Option) Checker {
115 return &cmpEqualsChecker{
116 argNames: []string{"got", "want"},
117 opts: opts,
118 }
119 }
120
121 type cmpEqualsChecker struct {
122 argNames
123 opts cmp.Options
124 }
125
126 // Check implements Checker.Check by checking that got == args[0] according to
127 // the compare options stored in the checker.
128 func (c *cmpEqualsChecker) Check(got interface{}, args []interface{}, note func(key string, value interface{})) (err error) {
129 defer func() {
130 // A panic is raised in some cases, for instance when trying to compare
131 // structs with unexported fields and neither AllowUnexported nor
132 // cmpopts.IgnoreUnexported are provided.
133 if r := recover(); r != nil {
134 err = BadCheckf("%s", r)
135 }
136 }()
137 want := args[0]
138 if diff := cmp.Diff(got, want, c.opts...); diff != "" {
139 // Only output values when the verbose flag is set.
140 note("error", Unquoted("values are not deep equal"))
141 note("diff (-got +want)", Unquoted(diff))
142 note("got", SuppressedIfLong{got})
143 note("want", SuppressedIfLong{want})
144 return ErrSilent
145 }
146 return nil
147 }
148
149 // DeepEquals is a Checker deeply checking equality of two arbitrary values.
150 // The comparison is done using the github.com/google/go-cmp/cmp package.
151 // When comparing structs, by default no exported fields are allowed. CmpEquals
152 // can be used when more customized compare options are required.
153 //
154 // Example call:
155 //
156 // c.Assert(got, qt.DeepEquals, []int{42, 47})
157 var DeepEquals = CmpEquals()
158
159 // ContentEquals is like DeepEquals but any slices in the compared values will
160 // be sorted before being compared.
161 var ContentEquals = CmpEquals(cmpopts.SortSlices(func(x, y interface{}) bool {
162 // TODO frankban: implement a proper sort function.
163 return pretty.Sprint(x) < pretty.Sprint(y)
164 }))
165
166 // Matches is a Checker checking that the provided string or fmt.Stringer
167 // matches the provided regular expression pattern.
168 //
169 // For instance:
170 //
171 // c.Assert("these are the voyages", qt.Matches, "these are .*")
172 // c.Assert(net.ParseIP("1.2.3.4"), qt.Matches, "1.*")
173 // c.Assert("my multi-line\nnumber", qt.Matches, regexp.MustCompile(`my multi-line\n(string|number)`))
174 var Matches Checker = &matchesChecker{
175 argNames: []string{"got value", "regexp"},
176 }
177
178 type matchesChecker struct {
179 argNames
180 }
181
182 // Check implements Checker.Check by checking that got is a string or a
183 // fmt.Stringer and that it matches args[0].
184 func (c *matchesChecker) Check(got interface{}, args []interface{}, note func(key string, value interface{})) error {
185 pattern := args[0]
186 switch v := got.(type) {
187 case string:
188 return match(v, pattern, "value does not match regexp", note)
189 case fmt.Stringer:
190 return match(v.String(), pattern, "value.String() does not match regexp", note)
191 }
192 note("value", got)
193 return BadCheckf("value is not a string or a fmt.Stringer")
194 }
195
196 func checkFirstArgIsError(got interface{}, note func(key string, value interface{})) error {
197 if got == nil {
198 return errors.New("got nil error but want non-nil")
199 }
200 _, ok := got.(error)
201 if !ok {
202 note("got", got)
203 return BadCheckf("first argument is not an error")
204 }
205 return nil
206 }
207
208 // ErrorMatches is a Checker checking that the provided value is an error whose
209 // message matches the provided regular expression pattern.
210 //
211 // For instance:
212 //
213 // c.Assert(err, qt.ErrorMatches, "bad wolf .*")
214 // c.Assert(err, qt.ErrorMatches, regexp.MustCompile("bad wolf .*"))
215 var ErrorMatches Checker = &errorMatchesChecker{
216 argNames: []string{"got error", "regexp"},
217 }
218
219 type errorMatchesChecker struct {
220 argNames
221 }
222
223 // Check implements Checker.Check by checking that got is an error whose
224 // Error() matches args[0].
225 func (c *errorMatchesChecker) Check(got interface{}, args []interface{}, note func(key string, value interface{})) error {
226 if err := checkFirstArgIsError(got, note); err != nil {
227 return err
228 }
229
230 gotErr := got.(error)
231 return match(gotErr.Error(), args[0], "error does not match regexp", note)
232 }
233
234 // PanicMatches is a Checker checking that the provided function panics with a
235 // message matching the provided regular expression pattern.
236 //
237 // For instance:
238 //
239 // c.Assert(func() {panic("bad wolf ...")}, qt.PanicMatches, "bad wolf .*")
240 // c.Assert(func() {panic("bad wolf ...")}, qt.PanicMatches, regexp.MustCompile(`bad wolf .*`))
241 var PanicMatches Checker = &panicMatchesChecker{
242 argNames: []string{"function", "regexp"},
243 }
244
245 type panicMatchesChecker struct {
246 argNames
247 }
248
249 // Check implements Checker.Check by checking that got is a func() that panics
250 // with a message matching args[0].
251 func (c *panicMatchesChecker) Check(got interface{}, args []interface{}, note func(key string, value interface{})) (err error) {
252 f := reflect.ValueOf(got)
253 if f.Kind() != reflect.Func {
254 note("got", got)
255 return BadCheckf("first argument is not a function")
256 }
257 ftype := f.Type()
258 if ftype.NumIn() != 0 {
259 note("function", got)
260 return BadCheckf("cannot use a function receiving arguments")
261 }
262
263 defer func() {
264 r := recover()
265 if r == nil {
266 err = errors.New("function did not panic")
267 return
268 }
269 msg := fmt.Sprint(r)
270 note("panic value", msg)
271 err = match(msg, args[0], "panic value does not match regexp", note)
272 }()
273
274 f.Call(nil)
275 return nil
276 }
277
278 // IsNil is a Checker checking that the provided value is nil.
279 //
280 // For instance:
281 //
282 // c.Assert(got, qt.IsNil)
283 //
284 // As a special case, if the value is nil but implements the
285 // error interface, it is still considered to be non-nil.
286 // This means that IsNil will fail on an error value that happens
287 // to have an underlying nil value, because that's
288 // invariably a mistake.
289 // See https://golang.org/doc/faq#nil_error.
290 var IsNil Checker = &isNilChecker{
291 argNames: []string{"got"},
292 }
293
294 type isNilChecker struct {
295 argNames
296 }
297
298 // Check implements Checker.Check by checking that got is nil.
299 func (c *isNilChecker) Check(got interface{}, args []interface{}, note func(key string, value interface{})) (err error) {
300 if got == nil {
301 return nil
302 }
303 value := reflect.ValueOf(got)
304 _, isError := got.(error)
305 if canBeNil(value.Kind()) && value.IsNil() {
306 if isError {
307 // It's an error with an underlying nil value.
308 return fmt.Errorf("error containing nil value of type %T. See https://golang.org/doc/faq#nil_error", got)
309 }
310 return nil
311 }
312 if isError {
313 return errors.New("got non-nil error")
314 }
315 return errors.New("got non-nil value")
316 }
317
318 // IsNotNil is a Checker checking that the provided value is not nil.
319 // IsNotNil is the equivalent of qt.Not(qt.IsNil)
320 //
321 // For instance:
322 //
323 // c.Assert(got, qt.IsNotNil)
324 var IsNotNil Checker = &notChecker{
325 Checker: IsNil,
326 }
327
328 // HasLen is a Checker checking that the provided value has the given length.
329 //
330 // For instance:
331 //
332 // c.Assert([]int{42, 47}, qt.HasLen, 2)
333 // c.Assert(myMap, qt.HasLen, 42)
334 var HasLen Checker = &hasLenChecker{
335 argNames: []string{"got", "want length"},
336 }
337
338 type hasLenChecker struct {
339 argNames
340 }
341
342 // Check implements Checker.Check by checking that len(got) == args[0].
343 func (c *hasLenChecker) Check(got interface{}, args []interface{}, note func(key string, value interface{})) (err error) {
344 v := reflect.ValueOf(got)
345 switch v.Kind() {
346 case reflect.Array, reflect.Chan, reflect.Map, reflect.Slice, reflect.String:
347 default:
348 note("got", got)
349 return BadCheckf("first argument has no length")
350 }
351 want, ok := args[0].(int)
352 if !ok {
353 note("length", args[0])
354 return BadCheckf("length is not an int")
355 }
356 length := v.Len()
357 note("len(got)", length)
358 if length != want {
359 return fmt.Errorf("unexpected length")
360 }
361 return nil
362 }
363
364 // Implements checks that the provided value implements an interface. The
365 // interface is specified with a pointer to an interface variable.
366 //
367 // For instance:
368 //
369 // var rc io.ReadCloser
370 // c.Assert(myReader, qt.Implements, &rc)
371 var Implements Checker = &implementsChecker{
372 argNames: []string{"got", "want interface pointer"},
373 }
374
375 type implementsChecker struct {
376 argNames
377 }
378
379 var emptyInterface = reflect.TypeOf((*interface{})(nil)).Elem()
380
381 // Check implements Checker.Check by checking that got implements the
382 // interface pointed to by args[0].
383 func (c *implementsChecker) Check(got interface{}, args []interface{}, note func(key string, value interface{})) (err error) {
384 if got == nil {
385 note("error", Unquoted("got nil value but want non-nil"))
386 note("got", got)
387 return ErrSilent
388 }
389
390 if args[0] == nil {
391 return BadCheckf("want a pointer to an interface variable but nil was provided")
392 }
393 wantType := reflect.TypeOf(args[0])
394 if wantType.Kind() != reflect.Ptr {
395 note("want", Unquoted(wantType.String()))
396 return BadCheckf("want a pointer to an interface variable but a non-pointer value was provided")
397 } else if wantType.Elem().Kind() != reflect.Interface {
398 note("want pointer type", Unquoted(wantType.Elem().String()))
399 return BadCheckf("want a pointer to an interface variable but a pointer to a concrete type was provided")
400 } else if wantType.Elem() == emptyInterface {
401 note("want pointer type", Unquoted(wantType.Elem().String()))
402 return BadCheckf("all types implement the empty interface, want a pointer to a variable that isn't the empty interface")
403 }
404
405 gotType := reflect.TypeOf(got)
406 if !gotType.Implements(wantType.Elem()) {
407 note("error", Unquoted("got value does not implement wanted interface"))
408 note("got", got)
409 note("want interface", Unquoted(wantType.Elem().String()))
410 return ErrSilent
411 }
412
413 return nil
414 }
415
416 // Satisfies is a Checker checking that the provided value, when used as
417 // argument of the provided predicate function, causes the function to return
418 // true. The function must be of type func(T) bool, having got assignable to T.
419 //
420 // For instance:
421 //
422 // // Check that an error from os.Open satisfies os.IsNotExist.
423 // c.Assert(err, qt.Satisfies, os.IsNotExist)
424 //
425 // // Check that a floating point number is a not-a-number.
426 // c.Assert(f, qt.Satisfies, math.IsNaN)
427 var Satisfies Checker = &satisfiesChecker{
428 argNames: []string{"arg", "predicate function"},
429 }
430
431 type satisfiesChecker struct {
432 argNames
433 }
434
435 // Check implements Checker.Check by checking that args[0](got) == true.
436 func (c *satisfiesChecker) Check(got interface{}, args []interface{}, note func(key string, value interface{})) (err error) {
437 // Original code at
438 // <https://github.com/juju/testing/blob/master/checkers/bool.go>.
439 predicate := args[0]
440 f := reflect.ValueOf(predicate)
441 ftype := f.Type()
442 if ftype.Kind() != reflect.Func || ftype.NumIn() != 1 || ftype.NumOut() != 1 || ftype.Out(0).Kind() != reflect.Bool {
443 note("predicate function", predicate)
444 return BadCheckf("predicate function is not a func(T) bool")
445 }
446 v, t := reflect.ValueOf(got), ftype.In(0)
447 if !v.IsValid() {
448 if !canBeNil(t.Kind()) {
449 note("predicate function", predicate)
450 return BadCheckf("cannot use nil as type %v in argument to predicate function", t)
451 }
452 v = reflect.Zero(t)
453 } else if !v.Type().AssignableTo(t) {
454 note("arg", got)
455 note("predicate function", predicate)
456 return BadCheckf("cannot use value of type %v as type %v in argument to predicate function", v.Type(), t)
457 }
458 if f.Call([]reflect.Value{v})[0].Interface().(bool) {
459 return nil
460 }
461 return fmt.Errorf("value does not satisfy predicate function")
462 }
463
464 // IsTrue is a Checker checking that the provided value is true.
465 // The value must have a boolean underlying type.
466 //
467 // For instance:
468 //
469 // c.Assert(true, qt.IsTrue)
470 // c.Assert(myBoolean(false), qt.IsTrue)
471 var IsTrue Checker = &boolChecker{
472 want: true,
473 }
474
475 // IsFalse is a Checker checking that the provided value is false.
476 // The value must have a boolean underlying type.
477 //
478 // For instance:
479 //
480 // c.Assert(false, qt.IsFalse)
481 // c.Assert(IsValid(), qt.IsFalse)
482 var IsFalse Checker = &boolChecker{
483 want: false,
484 }
485
486 type boolChecker struct {
487 want bool
488 }
489
490 // Check implements Checker.Check by checking that got == c.want.
491 func (c *boolChecker) Check(got interface{}, args []interface{}, note func(key string, value interface{})) (err error) {
492 v := reflect.ValueOf(got)
493 if v.IsValid() && v.Kind() == reflect.Bool {
494 if v.Bool() != c.want {
495 return fmt.Errorf("value is not %v", c.want)
496 }
497 return nil
498 }
499 note("value", got)
500 return BadCheckf("value does not have a bool underlying type")
501 }
502
503 // ArgNames implements Checker.ArgNames.
504 func (c *boolChecker) ArgNames() []string {
505 return []string{"got"}
506 }
507
508 // Not returns a Checker negating the given Checker.
509 //
510 // For instance:
511 //
512 // c.Assert(got, qt.Not(qt.IsNil))
513 // c.Assert(answer, qt.Not(qt.Equals), 42)
514 func Not(checker Checker) Checker {
515 return &notChecker{
516 Checker: checker,
517 }
518 }
519
520 type notChecker struct {
521 Checker
522 }
523
524 // Check implements Checker.Check by checking that the stored checker fails.
525 func (c *notChecker) Check(got interface{}, args []interface{}, note func(key string, value interface{})) (err error) {
526 if nc, ok := c.Checker.(*notChecker); ok {
527 return nc.Checker.Check(got, args, note)
528 }
529 err = c.Checker.Check(got, args, note)
530 if IsBadCheck(err) {
531 return err
532 }
533 if err != nil {
534 return nil
535 }
536 if c.Checker == IsNil {
537 return errors.New("got nil value but want non-nil")
538 }
539 return errors.New("unexpected success")
540 }
541
542 // Contains is a checker that checks that a map, slice, array
543 // or string contains a value. It's the same as using
544 // Any(Equals), except that it has a special case
545 // for strings - if the first argument is a string,
546 // the second argument must also be a string
547 // and strings.Contains will be used.
548 //
549 // For example:
550 //
551 // c.Assert("hello world", qt.Contains, "world")
552 // c.Assert([]int{3,5,7,99}, qt.Contains, 7)
553 var Contains Checker = &containsChecker{
554 argNames: []string{"container", "want"},
555 }
556
557 type containsChecker struct {
558 argNames
559 }
560
561 // Check implements Checker.Check by checking that got contains args[0].
562 func (c *containsChecker) Check(got interface{}, args []interface{}, note func(key string, value interface{})) error {
563 if got, ok := got.(string); ok {
564 want, ok := args[0].(string)
565 if !ok {
566 return BadCheckf("strings can only contain strings, not %T", args[0])
567 }
568 if strings.Contains(got, want) {
569 return nil
570 }
571 return errors.New("no substring match found")
572 }
573 return Any(Equals).Check(got, args, note)
574 }
575
576 // Any returns a Checker that uses the given checker to check elements
577 // of a slice or array or the values from a map. It succeeds if any element
578 // passes the check.
579 //
580 // For example:
581 //
582 // c.Assert([]int{3,5,7,99}, qt.Any(qt.Equals), 7)
583 // c.Assert([][]string{{"a", "b"}, {"c", "d"}}, qt.Any(qt.DeepEquals), []string{"c", "d"})
584 //
585 // See also All and Contains.
586 func Any(c Checker) Checker {
587 return &anyChecker{
588 argNames: append([]string{"container"}, c.ArgNames()[1:]...),
589 elemChecker: c,
590 }
591 }
592
593 type anyChecker struct {
594 argNames
595 elemChecker Checker
596 }
597
598 // Check implements Checker.Check by checking that one of the elements of
599 // got passes the c.elemChecker check.
600 func (c *anyChecker) Check(got interface{}, args []interface{}, note func(key string, value interface{})) error {
601 iter, err := newIter(got)
602 if err != nil {
603 return BadCheckf("%v", err)
604 }
605 for iter.next() {
606 // For the time being, discard the notes added by the sub-checker,
607 // because it's not clear what a good behaviour would be.
608 // Should we print all the failed check for all elements? If there's only
609 // one element in the container, the answer is probably yes,
610 // but let's leave it for now.
611 err := c.elemChecker.Check(
612 iter.value().Interface(),
613 args,
614 func(key string, value interface{}) {},
615 )
616 if err == nil {
617 return nil
618 }
619 if IsBadCheck(err) {
620 return BadCheckf("at %s: %v", iter.key(), err)
621 }
622 }
623 return errors.New("no matching element found")
624 }
625
626 // All returns a Checker that uses the given checker to check elements
627 // of slice or array or the values of a map. It succeeds if all elements
628 // pass the check.
629 // On failure it prints the error from the first index that failed.
630 //
631 // For example:
632 //
633 // c.Assert([]int{3, 5, 8}, qt.All(qt.Not(qt.Equals)), 0)
634 // c.Assert([][]string{{"a", "b"}, {"a", "b"}}, qt.All(qt.DeepEquals), []string{"c", "d"})
635 //
636 // See also Any and Contains.
637 func All(c Checker) Checker {
638 return &allChecker{
639 argNames: append([]string{"container"}, c.ArgNames()[1:]...),
640 elemChecker: c,
641 }
642 }
643
644 type allChecker struct {
645 argNames
646 elemChecker Checker
647 }
648
649 // Check implement Checker.Check by checking that all the elements of got
650 // pass the c.elemChecker check.
651 func (c *allChecker) Check(got interface{}, args []interface{}, notef func(key string, value interface{})) error {
652 iter, err := newIter(got)
653 if err != nil {
654 return BadCheckf("%v", err)
655 }
656 for iter.next() {
657 // Store any notes added by the checker so
658 // we can add our own note at the start
659 // to say which element failed.
660 var notes []note
661 err := c.elemChecker.Check(
662 iter.value().Interface(),
663 args,
664 func(key string, val interface{}) {
665 notes = append(notes, note{key, val})
666 },
667 )
668 if err == nil {
669 continue
670 }
671 if IsBadCheck(err) {
672 return BadCheckf("at %s: %v", iter.key(), err)
673 }
674 notef("error", Unquoted("mismatch at "+iter.key()))
675 if err != ErrSilent {
676 // If the error's not silent, the checker is expecting
677 // the caller to print the error and the value that failed.
678 notef("error", Unquoted(err.Error()))
679 notef("first mismatched element", iter.value().Interface())
680 }
681 for _, n := range notes {
682 notef(n.key, n.value)
683 }
684 return ErrSilent
685 }
686 return nil
687 }
688
689 // JSONEquals is a checker that checks whether a byte slice
690 // or string is JSON-equivalent to a Go value. See CodecEquals for
691 // more information.
692 //
693 // It uses DeepEquals to do the comparison. If a more sophisticated
694 // comparison is required, use CodecEquals directly.
695 //
696 // For instance:
697 //
698 // c.Assert(`{"First": 47.11}`, qt.JSONEquals, &MyStruct{First: 47.11})
699 var JSONEquals = CodecEquals(json.Marshal, json.Unmarshal)
700
701 type codecEqualChecker struct {
702 argNames
703 marshal func(interface{}) ([]byte, error)
704 unmarshal func([]byte, interface{}) error
705 deepEquals Checker
706 }
707
708 // CodecEquals returns a checker that checks for codec value equivalence.
709 //
710 // It expects two arguments: a byte slice or a string containing some
711 // codec-marshaled data, and a Go value.
712 //
713 // It uses unmarshal to unmarshal the data into an interface{} value.
714 // It marshals the Go value using marshal, then unmarshals the result into
715 // an interface{} value.
716 //
717 // It then checks that the two interface{} values are deep-equal to one
718 // another, using CmpEquals(opts) to perform the check.
719 //
720 // See JSONEquals for an example of this in use.
721 func CodecEquals(
722 marshal func(interface{}) ([]byte, error),
723 unmarshal func([]byte, interface{}) error,
724 opts ...cmp.Option,
725 ) Checker {
726 return &codecEqualChecker{
727 argNames: argNames{"got", "want"},
728 marshal: marshal,
729 unmarshal: unmarshal,
730 deepEquals: CmpEquals(opts...),
731 }
732 }
733
734 func (c *codecEqualChecker) Check(got interface{}, args []interface{}, note func(key string, value interface{})) error {
735 var gotContent []byte
736 switch got := got.(type) {
737 case string:
738 gotContent = []byte(got)
739 case []byte:
740 gotContent = got
741 default:
742 return BadCheckf("expected string or byte, got %T", got)
743 }
744 wantContent := args[0]
745 wantContentBytes, err := c.marshal(wantContent)
746 if err != nil {
747 return BadCheckf("cannot marshal expected contents: %v", err)
748 }
749 var wantContentVal interface{}
750 if err := c.unmarshal(wantContentBytes, &wantContentVal); err != nil {
751 return BadCheckf("cannot unmarshal expected contents: %v", err)
752 }
753 var gotContentVal interface{}
754 if err := c.unmarshal([]byte(gotContent), &gotContentVal); err != nil {
755 return fmt.Errorf("cannot unmarshal obtained contents: %v; %q", err, gotContent)
756 }
757 return c.deepEquals.Check(gotContentVal, []interface{}{wantContentVal}, note)
758 }
759
760 // argNames helps implementing Checker.ArgNames.
761 type argNames []string
762
763 // ArgNames implements Checker.ArgNames by returning the argument names.
764 func (a argNames) ArgNames() []string {
765 return a
766 }
767
768 // match checks that the given error message matches the given pattern.
769 func match(got string, pattern interface{}, msg string, note func(key string, value interface{})) error {
770 if actualRegex, ok := pattern.(*regexp.Regexp); ok {
771 if actualRegex.MatchString(got) {
772 return nil
773 }
774 return errors.New(msg)
775 }
776 regex, ok := pattern.(string)
777 if !ok {
778 note("regexp", pattern)
779 return BadCheckf("regexp is not a string")
780 }
781 matches, err := regexp.MatchString("^("+regex+")$", got)
782 if err != nil {
783 note("regexp", regex)
784 return BadCheckf("cannot compile regexp: %s", err)
785 }
786 if matches {
787 return nil
788 }
789 return errors.New(msg)
790 }
791
792 // canBeNil reports whether a value or type of the given kind can be nil.
793 func canBeNil(k reflect.Kind) bool {
794 switch k {
795 case reflect.Chan, reflect.Func, reflect.Interface, reflect.Map, reflect.Ptr, reflect.Slice:
796 return true
797 }
798 return false
799 }