matchers.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. //go:generate mockgen -destination mock_matcher/mock_matcher.go github.com/golang/mock/gomock Matcher
  2. // Copyright 2010 Google Inc.
  3. //
  4. // Licensed under the Apache License, Version 2.0 (the "License");
  5. // you may not use this file except in compliance with the License.
  6. // You may obtain a copy of the License at
  7. //
  8. // http://www.apache.org/licenses/LICENSE-2.0
  9. //
  10. // Unless required by applicable law or agreed to in writing, software
  11. // distributed under the License is distributed on an "AS IS" BASIS,
  12. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. // See the License for the specific language governing permissions and
  14. // limitations under the License.
  15. package gomock
  16. import (
  17. "fmt"
  18. "reflect"
  19. )
  20. // A Matcher is a representation of a class of values.
  21. // It is used to represent the valid or expected arguments to a mocked method.
  22. type Matcher interface {
  23. // Matches returns whether x is a match.
  24. Matches(x interface{}) bool
  25. // String describes what the matcher matches.
  26. String() string
  27. }
  28. type anyMatcher struct{}
  29. func (anyMatcher) Matches(x interface{}) bool {
  30. return true
  31. }
  32. func (anyMatcher) String() string {
  33. return "is anything"
  34. }
  35. type eqMatcher struct {
  36. x interface{}
  37. }
  38. func (e eqMatcher) Matches(x interface{}) bool {
  39. return reflect.DeepEqual(e.x, x)
  40. }
  41. func (e eqMatcher) String() string {
  42. return fmt.Sprintf("is equal to %v", e.x)
  43. }
  44. type nilMatcher struct{}
  45. func (nilMatcher) Matches(x interface{}) bool {
  46. if x == nil {
  47. return true
  48. }
  49. v := reflect.ValueOf(x)
  50. switch v.Kind() {
  51. case reflect.Chan, reflect.Func, reflect.Interface, reflect.Map,
  52. reflect.Ptr, reflect.Slice:
  53. return v.IsNil()
  54. }
  55. return false
  56. }
  57. func (nilMatcher) String() string {
  58. return "is nil"
  59. }
  60. type notMatcher struct {
  61. m Matcher
  62. }
  63. func (n notMatcher) Matches(x interface{}) bool {
  64. return !n.m.Matches(x)
  65. }
  66. func (n notMatcher) String() string {
  67. // TODO: Improve this if we add a NotString method to the Matcher interface.
  68. return "not(" + n.m.String() + ")"
  69. }
  70. // Constructors
  71. func Any() Matcher { return anyMatcher{} }
  72. func Eq(x interface{}) Matcher { return eqMatcher{x} }
  73. func Nil() Matcher { return nilMatcher{} }
  74. func Not(x interface{}) Matcher {
  75. if m, ok := x.(Matcher); ok {
  76. return notMatcher{m}
  77. }
  78. return notMatcher{Eq(x)}
  79. }