如何在__init__中实例化模拟类属性?

时间:2016-01-21 11:15:30

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

我正在尝试模拟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):
    def test_auth_vk(self, mock_get):
         ... etc ...
        auth_token = 'ceeecdfe0eb4bf68ceeecdfe0eb4bf68ceeecdfe0eb4bf68652530774ced6cbc8cba0'
        token = user.auth_token.key
        self.client.defaults['HTTP_AUTHORIZATION'] = 'Token {}'.format(token)
        with patch.object(accounts.auth_backends.vk_backend.VKAuth, 'api'): #point where we're mocking
            response = self.client.post(reverse('auth-social', kwargs=dict(backend='vk')), dict(access_token=auth_token), follow=True)

在上面基于SNView类的视图中调用'auth-social'时创建了VKAuth类的实例:

class SNView(generics.GenericAPIView):
    serializer_class = serializers.AuthSocialSerializer
    permission_classes = (rest_permissions.IsAuthenticated)

    def post(self, request, backend, *args, **kwargs):
        s = self.get_serializer(data=request.DATA)

        if s.is_valid():
            auth_backends = {
                'vk': VKAuth,
                'facebook': FBAuth
            }

            if backend in auth_backends:
                auth_backend = auth_backends[backend](access_token=s.data['access_token'], user=self.request.user)

我收到错误:

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

我应该写什么,而不是当前的patch.object到达api.friends.get并嘲笑它?

UPD:

更确切地说,我想要一些相当于:

    auth_token = 'ceeecdfe0eb4bf68ceeecdfe0eb4bf68ceeecdfe0eb4bf68652530774ced6cbc8cba0'
    user = User.objects.get(id = 2)
    vk_auth = VKAuth(auth_token, user)

    vk_ids=[111111,2222222,3333333,44444444]
    vk_auth.authenticate()
    vk_auth.api.friends = MagicMock(name='get', return_value=None)
    vk_auth.api.friends.get = MagicMock(name='get', return_value=vk_ids)
    data = vk_auth.follow()

但是在我们通过self.client.post()向django-rest-framework api发出请求之前,我就嘲笑它。

谢谢!

1 个答案:

答案 0 :(得分:4)

你正在修补错误的东西。在VKAuth

self.api = vk.API(self.session)

api属性添加到VKAuth self 对象。当你打电话

patch.object(accounts.auth_backends.vk_backend.VKAuth, 'api')

您正在修补api类的VKAuth静态属性,而不是对象属性。

您应该修改vk.API

with patch('vk.API', autospec=True) as mock_api:
    response = self.client.post(reverse('auth-social', kwargs=dict(backend='vk')), dict(access_token=auth_token), follow=True)

注意:

  1. 只有在您确实知道为什么需要它而非简单patch时才使用patch.object
  2. autospec=True不是强制性的,而是I strongly encourage to use it
  3. patch上下文中self.api将等于mock_api.return_value,因为来电vk.API(self.session)就像来电mock_api();换句话说,mock_api是用于替换vk.API引用的模拟对象。
  4. 看看where to patch,你会发现它非常有用。
  5. 现在,如果您希望通过某种行为填充mock_api.return_value,可以在with上下文中对其进行配置:

    with patch('vk.API', autospec=True) as mock_api:
        m_api = mock_api.return_value
        m_api.friends.return_value = None
        m_api.friends.get.return_value = vk_ids
        .... Your test