2013-06-27 95 views
3

我試圖讓模擬庫返回一個特定的模擬對象與補丁。無論我嘗試什麼,如果我在'with'子句中實例化一個新對象,我會得到一個通用Mock對象,而不是我自定義的對象。Python模擬庫不返回正確的模擬對象的'補丁'

這是一個使用我的代碼記錄爲例:

import logging 

    my_mock = Mock() 
    my_mock.id = 'i-12341234' 

    with patch('logging.PlaceHolder', new=my_mock) as mockobj: 
     print mockobj.id   # correctly prints 'i-12341234' 

     newobj = logging.PlaceHolder(None) 
     print newobj.id   # prints <Mock name='mock().id' id='47607184'> 

我怎樣才能模擬每logging.Placeholder的新實例被實例化時my_mock回報?

事實證明,繼承Mock並使用new_callable工作傳遞它。由於我花時間試圖讓版本達到上述工作狀態,所以我仍然感激並回答。

+0

你有沒有看[這也許相關的問題(http://stackoverflow.com/questions/9980962/mocking-a-classs-construction)? – bdesham

回答

0
import logging 
from mock import Mock, patch 

my_mock = Mock() 
my_mock.id = 'i-12341234' 

with patch('logging.PlaceHolder', new=my_mock) as mockobj: 
    mockobj.return_value = mockobj # <-- added this line. 
    print mockobj.id 
    newobj = logging.PlaceHolder(None) 
    print newobj.id 

替代

import logging 
from mock import Mock, patch 

my_mock = Mock() 
my_mock.id = 'i-12341234' 
my_mock.return_value = my_mock # <--- 

with patch('logging.PlaceHolder', new=my_mock) as mockobj: 
    assert mockobj.id == 'i-12341234' 
    newobj = logging.PlaceHolder(None) 
    assert newobj.id == 'i-12341234' 
+0

這與我的代碼有什麼不同?(除了導入Mock&patch?) – user1491250

+0

@ user1491250,我添加了一行。對代碼進行了評論。 – falsetru

+0

@ user1491250,你編寫補丁'loggin.PlaceHolder',但不修補'logging.PlaceHolder()'。 – falsetru