matchers.go 2.2 KB

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