2013-11-28 131 views
14

我嘗試測試一些不返回任何內容但將結果保存到數據庫的代碼。通過嘲諷的保存方法,我想檢查是否東西都被正確處理:如何在Python中用對象的模擬方法調用self?

def mock_save(self): 
    assert(self.attr, 'dest_val') 
with mock.patch.object(Item, "save", create=True) as save: 
    save.side_effect = mock_save 
    func_to_call() //in func_to_call, I call item.save() 

但是,似乎這是不允許的。它表示參數不匹配的數量。

如果我做了def mock_save(),它將不起作用。

我該如何參考模擬方法所執行的對象呢? (我看到它在另一個線程這是適用於初始化方法,它可以直接從類中調用)

回答

14

你需要autospec=True

def mock_save(self): 
    assert self.attr == 'dest_val' 
with mock.patch.object(Item, "save", autospec=True) as save: 
    save.side_effect = mock_save 
    func_to_call() 
0

有時你只是想檢查一個方法被調用,但是你無法控制類的實例化或調用的方法。這裏有一種方法可以節省一些時間,以避免任何人遇到這種模式:

# first get a reference to the original unbound method we want to mock 
original_save = Item.save 
# then create a wrapper whose main purpose is to record a reference to `self` 
# when it will be passed, then delegates the actual work to the unbound method 
def side_fx(self, *a, **kw): 
    side_fx.self = self 
    return original_save(self, *a, **kw) 
# you're now ready to play 
with patch.object(Item, 'save', autospec=True, side_effect=side_fx) as mock_save: 
    data = "the data" 
    # your "system under test" 
    instance = SomeClass() 
    # the method where your mock is used 
    instance.some_method(data) 

    # you now want to check if it was indeed called with all the proper arguments 
    mock_save.assert_called_once_with(side_fx.self, data) 
相關問題