2015-11-05 55 views
2

我真的很喜歡mock的定點值。在你只想寫一行代碼的最小單元測試的情況下,不要使用隨機無意義的數字。對mock.sentinel對象的操作

但是,下面的

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之內)?

是否有一些黑客可以使用?或者,只有使用示例性數字才能做到最好?

回答

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)