【问题标题】:How to mock an external api in django?如何在 django 中模拟外部 api?
【发布时间】:2016-01-13 13:16:24
【问题描述】:

我正在尝试模拟 VKAuth 类中的“self.api.friends.get”方法:

import vk

class VKAuth(object):
    def __init__(self, access_token, user):
        self.session = vk.Session(access_token = access_token)
        self.api = vk.API(self.session)

    def follow(self):
        vk_friends = self.api.friends.get()

来自测试模块test_views.py:

from mock import patch
from ..auth_backends.vk_backend import VKAuth

class AddUsersToList(TestCase):
    @patch.object(VKAuth.api.friends, 'get')
    def test_auth_vk(self, mock_get):
         ... etc ...

我在测试过程中遇到错误:

AttributeError: <class 'accounts.auth_backends.vk_backend.VKAuth' doens't have the attribute 'api'

我做错了什么?如何在这个类结构中访问这个方法?

【问题讨论】:

    标签: python django unit-testing mocking python-mock


    【解决方案1】:

    你试图模拟一个类本身,而不是它的实例。并且该类没有api 属性,因为它是在您的__init__() 中创建的。将您的代码更改为:

    def test_auth_vk(self, mock_get):
        vk_auth = VKAuth(access_token, user)
        with mock.patch('vk_auth.api.friends') as friends_mock:
            friends_mock.get.return_value = None
            # Invoke the code that calls your api, passing the "vk_auth" variable as a backend.
            # ...
            friends_mock.mock.get.assert_called_with(your_arguments)
    

    如果您不能只将身份验证后端传递给您的代码,请查找实例化它的位置并模拟该位置。

    【讨论】:

    • 但是如果我想测试它不是直接将参数传递给类实例,而是使用初始化这个实例的 django-rest-framework 怎么办?换句话说,如果测试方法和我检查响应,我在里面调用“ response = self.client.post(reverse('app-social-auth', {"access_token": "blablabla"}) ”。
    • 您应该查找social_auth 实例化您的后端并模拟该实例的位置。如果您提出具体示例,我会尽力提供帮助。
    • 它在方法 post 的类 AuthSocialView 内的 accounts.views 中实例化为“ auth_backends = { 'vk' : VKAuth, 'facebook' : FBAuth } ”
    • 下面我们实例化它:auth_backends[backend](access_token = s.data['access_token'], user=self.request.user)
    • 那么,我想,你应该模拟上层对象,或者像urllib这样的传输层对象。您要测试哪种特定功能?
    猜你喜欢
    • 1970-01-01
    • 2011-08-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-17
    • 2016-05-17
    • 2022-06-30
    • 1970-01-01
    相关资源
    最近更新 更多