2015-11-06 105 views
1

這是我想測試的方法。在這個測試方法(test_get_all_products)中,我想傳遞一個dal標識的DB調用的產品列表和模擬響應。如何在Python中模擬這個單元測試?

def get_all_user_standalone_products(all_products, dal): 
standalone_products = [] 
if all_products is not None: 
    all_products = all_products['userRenewableProduct'] 
    for product in all_products: 
     sku_id = product.get('skuID', 0) 
     sku_cost_id = product.get('skuCostID', 0) 
     standalone_product = which_standalone_product(sku_id) 

     if product.get('isDisabled') or standalone_product is None: 
      continue 

     product['productType'] = standalone_product['name'] 

     sku_cost_data = dal.skucosts.get_costs_for_sku_cost_id(
      sku_cost_id) 
     product['termMonths'] = sku_cost_data['termMonths'] 

     upgrade_sku_ids = standalone_product.get(
      'upgrade_sku_ids', []) 
     if len(upgrade_sku_ids) > 0: 
      product['canUpgrade'] = True 

     product['upgradeSkus'] = upgrade_sku_ids 
     standalone_products.append(product) 
return standalone_products 

這是我的測試

product_sku_cost= { 
     u'testPriceSetID':u'', 
     u'skuID':88, 
     u'currencyTypeID':1, 
     u'termMonths':1, 
     u'dateCreated': u'2015-10-07T17:03:00 Z', 
     u'skuCostID':2840, 
     u'cost':9900, 
     u'skuTypeID':13, 
     u'dateModified': u'2015-10-07T17:03:00 Z', 
     u'isDefault':True, 
     u'name':u'Product'} 

@patch('model.dal') 
def test_get_all_products(self, dal): 
     # this is my mock - I want it to return the dictionary above. 
     dal.SKUCosts.get_costs_for_sku_cost_id.return_value = product_sku_cost 
     products = get_all_user_standalone_products(renewable_products, dal) 

     assert products[0]['canUpgrade'] is True 
     assert products[0]['termMonths'] == 1 

但是,當我斷言產品[0] [ 'termMonths'] == 1這是從嘲笑的對象,它失敗,因爲termMonths實際上是模擬對象本身,而不是我期待的返回值(product_sku_cost)。

請幫我弄清楚我上面做錯了什麼。

回答

0

這只是一個TYPO錯誤:嘗試將SKUCost更改爲skucost,在此配置dal。所以配置行成爲:

dal.skucsts.get_costs_for_sku_cost_id.return_value = product_sku_cost 

反正有在測試其他一些問題:你並不需要在您的測試補丁任何東西,因爲你傳遞dal對象,並沒有使用model.dal參考。我不知道什麼model.dal,但如果你想要做的是有相同的簽名/屬性你可以使用create_autospec來構建它。

您的測試可以是:

def test_get_all_products(self, dal): 
    # this is my mock - I want it to return the dictionary above. 
    dal = create_autospec(model.dal) 
    dal.skucosts.get_costs_for_sku_cost_id.return_value = product_sku_cost 
    ... 

如果model.dal是一類使用instance=True當您創建autospec。

相關問題