【问题标题】:Place custom argument matcher on mock called multiple times将自定义参数匹配器放置在多次调用的模拟上
【发布时间】:2022-01-26 04:31:19
【问题描述】:

假设我有以下代码sn-p:

# 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)
  ...

我想写一个关于 bar 模拟 foo 的单元测试,并对参数寄予期望。这是我尝试过的

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"))),
      )

当我运行它时,它一直告诉我'foo' does not contain all of ('', ({'property_1': 'hello'},), {}) in its call list, found ...

我在这里做错了什么?

【问题讨论】:

    标签: python unit-testing testing mocking python-unittest


    【解决方案1】:

    我错了

    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"))),
        )
    

    应该是

    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")))
            ]
        )
    

    (基本上调用需要作为列表传入)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多