mock Django调用视图在哪里?

2024-06-28 19:27:31 发布

您现在位置:Python中文网/ 问答频道 /正文

这是django1.6.8、python2.7和mock库。在

我有一个视图,它使用suds调用远程服务以获取增值税信息(这是一个简化版本):

def sales_tax(self, bundle_slug):
    bundle = get_object_or_404(Bundle, slug=bundle_slug,
                                active=True)

    cloud = TaxCloud(TAXCLOUD_API_ID, TAXCLOUD_API_KEY)
    origin = Address('origin address')
    destination = Address('customer address')
    cart_item = CartItem(bundle.sku, TAXCLOUD_TIC_ONLINE_GAMES,
                        bundle.price, 1)

    try:
        rate_info = cloud.get_rate(origin, destination,
                                    [cart_item],
                                    str(customer.id))

        sales_tax = Decimal(rate_info['sales_tax'])

        response = {'salesTax': locale.currency(sales_tax),
                    'total':  locale.currency(bundle.price + sales_tax)}
    except TaxCloudException as tce:
        response = {
            'error': str(tce)
        }

以下是TaxCloud类中的相关代码:

^{pr2}$

在视图的测试中,我不想调用远程服务。使用this example of a mocked client,我构建了一个哑模拟类(我的ClientMock与答案中的示例完全匹配):

class TaxCloudServiceClientMock(ClientMock):
    """
    Mock object that implements remote side services.
    """

    def Lookup(cls, api_id, api, customer_id, cart_id, cart_items,
               address, origin, flag, setting):
        """
        Stub for remote service.
        """
        return """(200, (LookupRsp){
               ResponseType = "OK"
               Messages = ""
               CartID = "82cabf35faf66d8b197c7040a9f7382b3f61573fc043d73717"
               CartItemsResponse =
                  (ArrayOfCartItemResponse){
                     CartItemResponse[] =
                        (CartItemResponse){
                           CartItemIndex = 1
                           TaxAmount = 0.10875
                        },
                  }
                })"""

在我的测试中,我试图@patchTaxCloud类中使用的Client

@patch('sales.TaxCloud.Client', new=TaxCloudServiceClientMock)
def test_can_retrieve_sales_tax(self):
    from django.core.urlresolvers import reverse

    tax_url = reverse('sales_tax', kwargs={'bundle_slug': self.bundle.slug})
    self.client.login(username=self.user.username, password='testpassword')

    response = self.client.get(tax_url, {'address1': '1234 Blah St',
                                        'city': 'Some City',
                                        'state': 'OH',
                                        'zipcode': '12345',
                                        'country': 'US'},
        HTTP_X_REQUESTED_WITH='XMLHttpRequest')

    self.assertEqual(response.status_code, 200)

不过,远程通话仍在进行中。根据“Where to mock”文档,我正确的目标是sales.TaxCloud.Client,而不是{}。在

是什么原因导致修补程序被忽略/绕过?在


Tags: selfidget远程addressresponsedeforigin