Python Mockito参数捕获器

3

我一直在使用Python mockitohttps://code.google.com/p/mockito-python/来测试我的代码。

到目前为止,Python mockito似乎只提供了两个匹配器:contains()和any()https://code.google.com/p/mockito-python/wiki/Matchers

我想知道如何编写代码以便可以捕获整个参数。

例如,如果我的代码是:

deleteSqlStatement = "DELETE from %s WHERE lower(z_id)=lower('%s') and y_id=%s" \
                         % (self.SOME_TABLE, zId, yId)
cursor.execute(deleteSqlStatement)

目前,我在验证方面所能做的只有:
verify(self.cursor_mock, times=1).execute(contains("DELETE"))

如果我能够捕获传递给execute的整个参数字符串,那就太好了。有什么建议吗?

你考虑过只使用Python模拟来完成这个吗?这样做只需要一个模拟就可以了,非常容易。 - Thomasleveil
2个回答

4

我想你可以自己实现一个[匹配器]来捕获参数。

class Captor(Matcher):

  def matches(self, arg):
    self.value = arg
    return True

  def getValue(self):
    return self.value

然后在你的测试中使用它:

captor = Captor()
verify(self.cursor_mock, times=1).execute(captor)
self.assertEqual("expected query", captor.getValue())

1
我曾经尝试验证复杂的参数,但遇到了问题。目前Mockito不像unittest.mock中的call_args那样方便地从模拟对象中获取调用参数。 最终我使用了(在我看来)第二好的方法,即mockito.matchers.arg_that(predicate),可以通过自定义方法验证参数。

https://mockito-python.readthedocs.io/en/latest/the-matchers.html#mockito.matchers.arg_that

因此,在您的示例中,我们可以将验证步骤重写为:

verify(self.cursor_mock, times=1).execute(arg_that(lambda sql: verify_sql(sql))

然后是自定义验证方法,可以验证任何你想要的内容:

def verify_sql(the_sql):
    if the_sql.startswith('SELECT'):
        return True
    else:
        return False


另一个例子(永远不会有足够的Mockito示例)

在我的情况下,我必须验证正确的输入,包括时间戳,是否发送到模拟的boto3客户端:

verify(boto3_client_mock).put_object_tagging(Bucket="foo-bucket",
                                         Key="foo-prefix", 
                                         Tagging=[{'Key':'tag1', 'Value': 'value1'}, 
                                                  {'Key': 'timestamp', 'Value': '1581670796'}])

这件事情让它变得棘手的是时间戳,所以常规匹配无法奏效。
但使用arg_that变得相当简单:
verify(boto3_client_mock).put_object_tagging(Bucket=ANY, 
                                             Key=ANY, 
                                             Tagging=arg_that(lambda tag_list: verify_tagset(tag_list)))


def verify_tagset(tagset):
    for tag in tagset['TagSet']:
        # Some verification in here
        if yadda:
            return True
    return False

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接