当我断言用它调用方法时,如何通配字符串? Python3 模拟
How do I wildcard a string when I'm asserting a method is called with it? Python3 mock
在 assert_has_calls
中使用 mock
的 call()
对象时,我很难断言给定的字符串已被使用,并且末尾附加了一个未知值。
例如:
被测代码:
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>')]
如何断言给定的字符串已传递给方法但允许未知值?
您可以使用 callee
库对方法调用中使用的字符串进行部分匹配:
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: .*'))
或者,如果您不想添加另一个库并且您确定知道调用的顺序,您可以从调用参数中提取字符串,然后使用正则表达式进行匹配
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)
在 assert_has_calls
中使用 mock
的 call()
对象时,我很难断言给定的字符串已被使用,并且末尾附加了一个未知值。
例如:
被测代码:
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>')]
如何断言给定的字符串已传递给方法但允许未知值?
您可以使用 callee
库对方法调用中使用的字符串进行部分匹配:
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: .*'))
或者,如果您不想添加另一个库并且您确定知道调用的顺序,您可以从调用参数中提取字符串,然后使用正则表达式进行匹配
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)