'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?
Solution 1:[1]
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)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | flakes |
