如何在Python中模拟这个单元测试?

时间:2015-11-06 02:02:38

标签: python unit-testing magicmock

这是我要测试的方法。在这个测试方法(test_get_all_products)中,我想传递一个产品列表和一个由dal标识的DB调用的模拟响应。

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实际上是Mock对象本身,而不是返回值(product_sku_cost)我期待着。

请帮我弄清楚我上面做错了什么。

1 个答案:

答案 0 :(得分: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是一个类,则在创建autospec时使用instance=True