Python 对mock.sentinel对象的操作
我非常喜欢Python 对mock.sentinel对象的操作,python,unit-testing,testing,mocking,Python,Unit Testing,Testing,Mocking,我非常喜欢mock的哨兵值。在您只想编写一行的最小单元测试的情况下,最好不要使用无意义的随机数 然而,以下情况 from mock import sentinel, patch def test_multiply_stuff(): with patch('module.data_source1',return_value=sentinel.source1): with patch('module.data_source1',return_value=sentinel.s
mock
的哨兵值。在您只想编写一行的最小单元测试的情况下,最好不要使用无意义的随机数
然而,以下情况
from mock import sentinel, patch
def test_multiply_stuff():
with patch('module.data_source1',return_value=sentinel.source1):
with patch('module.data_source1',return_value=sentinel.source1):
assert function(module.data_source1,
module_data2) == sentinel.source1 * sentinel.source2
不起作用。你会得到
TypeError: unsupported operand type(s) for *: '_SentinelObject' and '_SentinelObject'
我理解原因:哨兵对象上的操作不能计算为表达式是有道理的
是否有某种技术可以做到这一点(最好是在mock
中)
有什么我可以用的技巧吗?或者,仅仅使用示例性数字是最好的选择?也许最简单的方法是使用
id(sentinel\u对象)
而不是sentinel本身:
from mock import sentinel, patch
def test_multiply_stuff():
with patch('module.data_source1',return_value=sentinel.source1):
with patch('module.data_source2',return_value=sentinel.source2):
assert function(id(module.data_source1), id(module.data_source2) == id(sentinel.source1) * id(sentinel.source2)