python - 对mock.sentinel对象的操作

标签 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'

我明白为什么:对哨兵对象的操作不能计算为表达式是有道理的。

是否有某种技术可以做到这一点(最好在模拟中)?

有什么我可以使用的技巧吗?或者您能做的最好的事情就是使用示例数字?

最佳答案

也许最简单的方法是使用 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)

关于python - 对mock.sentinel对象的操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33545870/

相关文章:

python - 使用谷歌python的街道城市反向地理编码

c# - 我的类(class)有 30 个属性,单元测试很痛苦不是吗?

ios - XC测试 : Can expectationForPredicate fulfill on async variable change?

linux - 占用空间小的 VMWare Linux 镜像

unit-testing - 我如何模拟grails domain.refresh()

javascript - CasperJS 测试覆盖率

python - Tkinter 'label' 小部件 - 换行符随机添加空格

python - 即使安装了 Pandas 也无法工作

python - virtualenv:指定在系统范围和本地使用哪些包

unit-testing - 如何忽略缺少 'else' 的分支覆盖