2013-10-07 76 views
0

我正在測試使用動態創建函數的返回值的代碼。 我需要確保我正在測試的代碼調用一個名爲'email_invoice'與欺騙性數據...模擬測試動態函數的返回值

動態創建的函數命中遠程系統,所以我僞造呼叫的結果。

class MyTest(unittest2.Test): 

    def setUp(self): 

     patcher = mock.patch('soc.product.views.API') 
     patch = patcher.start() 

     self.order_id = 'fake_order_id' 

     # The `API` class has methods that are dynamically created. 
     # The method `API.CreateOrder` needs to be patched to return `self.order_id` 
     # When testing that a resulting method is called, I get a failed assertion: 

     #AssertionError: Expected call: email_invoice(<User: User(id=46, merchant_id=503579)>, 'fake123123123') 
     #Actual call: email_invoice(<User: User(id=46, merchant_id=503575)>, <MagicMock name='API().CreateOrder().OrderID' id='140700602174736'>) 

     # soc.product.views.API.CreateOrder => self.order_id 
     CreateOrderResult = mock.NonCallableMock() 
     CreateOrderResult.OrderId = self.order_id 
     patch.CreateOrder = mock.Mock() 
     patch.CreateOrder.return_value = CreateOrderResult 


    def test_that_stuff_out_homie(self): 

     ... doing stuff ... 

     user = ... a result of doing stuff ... 

     self.patches['email_invoice'].assert_called_once_with(user, self.order_id) 

因爲它提到,斷言失敗是這樣的:

AssertionError: Expected call: email_invoice(<User: User(id=46, merchant_id=503579)>, 'fake123123123') 
Actual call: email_invoice(<User: User(id=46, merchant_id=503575)>, <MagicMock name='API().CreateOrder().OrderID' id='140700602174736'>) 

那麼,什麼是測試這一點,正確的/正確的方法是什麼?

+1

您正在將'self.order_id'分配給'OrderId',但是通過'OrderID'從API獲取id(注意字符串末尾的大寫) –

+0

將此作爲答案並且我可以接受... –

回答

1

您分配self.order_idOrderId,但得到的OrderID從API的ID(注意在字符串末尾的大寫)。

+0

是的。我認爲這將是一個問題,因爲我不能使用補丁的auto_spec功能:P –

+0

啊,雖然錯字是一個問題,但是發生的事情是,當創建方法時,suds客戶端覆蓋補丁(或者至少繞過該修補程序通過使用動態__getattr__) –

+1

您也可以修補該方法,或者將客戶端附加的函數修補到「CreateOrder」屬性。 –