【问题标题】:Operations on mock.sentinel objects对 mock.sentinel 对象的操作
【发布时间】:2015-11-05 13:31:13
【问题描述】:

我真的很喜欢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 内)?

我可以使用一些技巧吗?还是仅使用模范数字是您能做的最好的事情?

【问题讨论】:

    标签: python unit-testing testing mocking


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多