【问题标题】:How to check for mock calls with wildcards?如何使用通配符检查模拟呼叫?
【发布时间】:2014-03-04 22:36:27
【问题描述】:

我正在编写单元测试,并想检查具有函数对象的调用,如下所示:

call(u'mock', u'foobar', <function <lambda> at 0x1ea99b0>, 10)

如何在不复制 lambda 的情况下检查 call() 是否具有我想要的所有参数?

编辑:我想澄清一下我正在使用mock 库,这里是:http://mock.readthedocs.org/en/latest/。我上面显示的call 是对MagicMock 对象的调用,我想使用assert_has_calls 检查它。

【问题讨论】:

    标签: python unit-testing


    【解决方案1】:

    我终于知道如何做我想做的事了。基本上,当使用assert_has_calls 时,我希望一个参数匹配,而不管它是什么(因为我无法在测试期间每次都重新创建lambda)。

    方法是使用mock.ANY

    因此,在我的示例中,这可以匹配调用:

    mocked_object.assert_has_calls([
       call('mock', 'foobar', mock.ANY, 10)
    ])
    

    【讨论】:

      【解决方案2】:

      如果您想要比 mock.ANY 更细的粒度,您可以创建自己的验证器类以用于调用比较,例如 assert_has_calls、assert_call_once_with 等。

      class MockValidator(object):
      
          def __init__(self, validator):
              # validator is a function that takes a single argument and returns a bool.
              self.validator = validator
      
          def __eq__(self, other):
              return bool(self.validator(other))
      

      可以这样使用:

      import mock
      my_mock = mock.Mock()
      my_mock('foo', 8)
      
      # Raises AssertionError.
      my_mock.assert_called_with('foo', MockValidator(lambda x: isinstance(x, str)))
      
      # Does not raise AssertionError.
      my_mock.assert_called_with('foo', MockValidator(lambda x: isinstance(x, int)))
      

      【讨论】:

        【解决方案3】:

        不确定您是如何构建call,但如果是某种args

        # IN THE CASE WE'RE DOING call(*args)
        
        if all([len(args) == 4,isinstance(args[0],str),
               isinstance(args[1],str), hasattr(args[2],'__call__'),
               isinstance(args[3],int)]):
            # PASS
        else:
            # FAIL
        

        如果您过分担心输入不是函数的可调用输入,并且觉得它会默默地通过单元测试:

        from types import FunctionType
        
        isinstance(lambda x: x,FunctionType) # True
        

        【讨论】:

        • 我的一般测试方法是使用mockobject.assert_has_calls([(call('foo', 'bar', 'bla')])。我假设我不能在这里使用类似的东西?
        • @RohanDhruva 恐怕我不关注
        • 这是我用来测试通话的:voidspace.org.uk/python/mock/…
        猜你喜欢
        • 2021-04-07
        • 2020-08-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-04-22
        相关资源
        最近更新 更多