python-3.x - 当我断言一个方法被调用时,如何使用通配符字符串?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>')]
如何断言给定的字符串已传递给方法但允许未知值?
解决方案
您可以使用callee
lib 对方法调用中使用的字符串进行部分匹配:
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)
推荐阅读
- ios - 如何在 iOS 中应用 JSON API 谷歌云存储来获取版本化对象?
- powerbi - 寻求帮助绘制条形图的变化 - 几乎是一个盒须图
- r - 在ggplot中移动具有相同美学但不同数据的图例条目的顺序
- python - 如何在python中格式化输出字符串?
- c - 如果我将函数调用的结果作为参数传递,它会保存在哪里?
- linux - cronjob 未在 Docker 容器中运行 throw Dockerfile
- java - 如何将 ResulSet 多个值转换为 Java 对象
- mongodb - 如果交换值,Mongo db 复合唯一键不起作用
- html - 无论里面的数据如何,都创建相等的表格布局
- python - 未能加载原生 TensorFlow 运行时(MrCNN 实现的 tensorflow 兼容性)