mock.sentinel对象的操作

时间:2015-11-05 13:31:14

标签: 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.source1):
            assert function(module.data_source1,
                            module_data2) == sentinel.source1 * sentinel.source2

不起作用。你会得到

TypeError: unsupported operand type(s) for *: '_SentinelObject' and '_SentinelObject'

我理解为什么:对Sentinel对象的操作无法评估表达式是有意义的。

是否有某种技术可以做到(最好在mock内)?

我可以使用一些黑客吗?或者你最好只使用示例性数字?

1 个答案:

答案 0 :(得分:2)

也许最简单的方法是使用id(sentinel_object)代替哨兵本身:

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)
相关问题