2016-01-13 54 views
1

我试图嘲弄在VKAuth类中的 “self.api.friends.get” 的方法:如何在django中模拟外部API?

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' 

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

回答

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) 

如果你不能只传递一个auth后端代码,查找它被实例化的地方,嘲笑那个地方。

+0

但是如果我想测试它不是直接将参数传递给类实例,而是使用初始化此实例的django-rest-framework?换句话说,如果测试方法和我检查响应,我会调用“response = self.client.post(reverse('app-social-auth',{”access_token“:”blablabla“})”。 – paus

+0

您应该查找'social_auth'实例化你后端的地方,并嘲笑那个实例如果你想出了具体的例子,我会尽力帮助。 –

+0

它在类AuthSocialView中的accounts.views中实例化为method“ auth_backends = {'vk':VKAuth,'脸谱':FBAuth}“ – paus