1

これは私がテストしたい方法です。このテスト メソッド (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

しかし、モック オブジェクトからの products[0]['termMonths'] == 1 をアサートすると、termMonths は実際にはモック オブジェクト自体であり、期待していた戻り値 (product_sku_cost) ではないため、失敗します。

上記で私が間違っていることを理解するのを手伝ってください。

4

1 に答える 1

0

これは単なる TYPO エラーです。構成した場所に変更SKUCostしてみてください。したがって、構成行は次のようになります。skucostdal

dal.skucsts.get_costs_for_sku_cost_id.return_value = product_sku_cost

dalとにかく、テストには他にもいくつかの問題があります。オブジェクトを渡していて参照を使用していないため、テストにパッチを当てる必要はありませんmodel.dalmodel.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
   ...

ifmodel.dalは、instance=Trueautospec を作成するときに使用するクラスです。

于 2015-11-06T12:46:44.567 に答える