【问题标题】:How to assert_called_with the first call if the method has been called twice in another method?如果该方法在另一个方法中被调用了两次,如何在第一次调用时断言调用?
【发布时间】:2014-05-07 02:50:40
【问题描述】:

例如在 t.py 中

def a(obj):
  print obj

def b():
  a(1)
  a(2)

然后:

from t import b

with patch('t.a') as m:
  b()
  m.assert_called_with(1)

我明白了:

AssertionError: Expected call: a(1)
Actual call: a(2)

【问题讨论】:

    标签: python magicmock


    【解决方案1】:

    最直接的方法是从mock.call_args_list 获取第一项并检查它是否被1 调用:

    call_args_list

    这是按顺序对模拟对象进行的所有调用的列表 (所以列表的长度就是它被调用的次数)。

    assert m.call_args_list[0] == call(1)
    

    其中call 是从mock 导入的:from mock import call

    另外,mock_calls 也可以代替 call_args_list

    另一种选择是使用assert_any_call()

    m.assert_any_call(1)
    

    【讨论】:

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