callset.go 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. // Copyright 2011 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. // callSet represents a set of expected calls, indexed by receiver and method
  16. // name.
  17. type callSet map[interface{}]map[string][]*Call
  18. // Add adds a new expected call.
  19. func (cs callSet) Add(call *Call) {
  20. methodMap, ok := cs[call.receiver]
  21. if !ok {
  22. methodMap = make(map[string][]*Call)
  23. cs[call.receiver] = methodMap
  24. }
  25. methodMap[call.method] = append(methodMap[call.method], call)
  26. }
  27. // Remove removes an expected call.
  28. func (cs callSet) Remove(call *Call) {
  29. methodMap, ok := cs[call.receiver]
  30. if !ok {
  31. return
  32. }
  33. sl := methodMap[call.method]
  34. for i, c := range sl {
  35. if c == call {
  36. // quick removal; we don't need to maintain call order
  37. if len(sl) > 1 {
  38. sl[i] = sl[len(sl)-1]
  39. }
  40. methodMap[call.method] = sl[:len(sl)-1]
  41. break
  42. }
  43. }
  44. }
  45. // FindMatch searches for a matching call. Returns nil if no call matched.
  46. func (cs callSet) FindMatch(receiver interface{}, method string, args []interface{}) *Call {
  47. methodMap, ok := cs[receiver]
  48. if !ok {
  49. return nil
  50. }
  51. calls, ok := methodMap[method]
  52. if !ok {
  53. return nil
  54. }
  55. // Search through the unordered set of calls expected on a method on a
  56. // receiver.
  57. for _, call := range calls {
  58. // A call should not normally still be here if exhausted,
  59. // but it can happen if, for instance, .Times(0) was used.
  60. // Pretend the call doesn't match.
  61. if call.exhausted() {
  62. continue
  63. }
  64. if call.matches(args) {
  65. return call
  66. }
  67. }
  68. return nil
  69. }