首页 > 解决方案 > 当我断言一个方法被调用时,如何使用通配符字符串?Python3 模拟

问题描述

当将mock'scall()对象与 一起使用时assert_has_calls,我很难断言给定的字符串已被使用,并且末尾附加了一个未知值。

例如:

被测代码:

mystring = 'a known string with an unknown value: {0}'.format(unknown_value)
method_to_call(mystring)

当前测试代码:

with mock.patch('method_to_call') as mocked_method:
  calls = [call('a known string with and unknown value: {0}'.format(mock.ANY)]
  call_method()
  mocked_method.assert_has_calls(calls)

这给了我一些类似的东西:

AssertionError: Calls not found.
Expected: [call('a known string with and unknown value: <ANY>')]

如何断言给定的字符串已传递给方法但允许未知值?

标签: python-3.xunit-testingmockingwildcardassert

解决方案


您可以使用calleelib 对方法调用中使用的字符串进行部分匹配:

from callee import String, Regex

with mock.patch('method_to_call') as mocked_method:
    call_method()
    mocked_method.assert_called_with(String() & Regex('a known string with an unknown value: .*'))

或者,如果您不想添加另一个库并且您确定您知道调用的顺序,您可以从调用 args 中提取字符串,然后使用正则表达式进行匹配

import re

with mock.patch('method_to_call') as mocked_method:
  call_method()
  argument_string = mocked_method.call_args[0][0]

  pattern = re.compile("a known string with an unknown value: .*")
  assert pattern.match(argument_string)


推荐阅读