简体   繁体   中英

Place custom argument matcher on mock called multiple times

Let's say I have the following code snippet:

# foo.py
class FooClass:
  def foo(req: ComplexRequestObject) -> resp:
    ...

# bar.py
def bar(f: FooClass, ...):
  # gen req_1 and req_2 somehow
  resp_1 = f.foo(req_1)
  resp_2 = f.foo(req_2)
  ...

I want to write a unittest on bar mocking out foo, and place expectations on the arguments. Here is what I tried

def partially_equals(self: ComplexRequestObject, other: ComplexRequestObject):
    return self.property_1 == other.property_1


class Matcher(object):
    def __init__(self, compare, some_obj):
        self.compare = compare
        self.some_obj = some_obj

    def __eq__(self, other):
        return self.compare(self.some_obj, other)

# Now in the test itself

  def test_thing_1(self):
      # call bar
      bar(mock_foo_class, ...)
      mock_foo_class.foo.assert_has_calls(
          call(Matcher(partially_equals, ComplexRequestObject(property_1="hello"))),
          call(Matcher(partially_equals, ComplexRequestObject(property_1="hello"))),
      )

When I run this, it keeps telling me that 'foo' does not contain all of ('', ({'property_1': 'hello'},), {}) in its call list, found...

What am I doing wrong here?

I had a typo

def test_thing_1(self):
    # call bar
    bar(mock_foo_class, ...)
    mock_foo_class.foo.assert_has_calls(
        call(Matcher(partially_equals, ComplexRequestObject(property_1="hello"))),
        call(Matcher(partially_equals, ComplexRequestObject(property_1="hello"))),
    )

Should be

def test_thing_1(self):
    # call bar
    bar(mock_foo_class, ...)
    mock_foo_class.foo.assert_has_calls(
        [
            call(Matcher(partially_equals, ComplexRequestObject(property_1="hello"))),
            call(Matcher(partially_equals, ComplexRequestObject(property_1="hello")))
        ]
    )

(Basically the calls needed to be passed in as a list)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM