模拟修补的类方法不起作用

时间:2016-01-20 16:53:02

标签: python django django-rest-framework python-mock django-unittest

我正在使用Django和DRF以及python mock。我想要做的是测试我的观点并模拟一个序列化器和一些方法。

这就是我所拥有的:

views.py

from gmm_mobile.v1.serializers import RegisterParticipationSerializer
from gmm_mobile.v1.exceptions import GameOrCampaignDoesNotExist
from gmm_util.header import Header
from gmm_util.response import ResponseUtils
from gmm_util.permissions import MobileTokenPermission
from gmm_util.permissions import MobileTokenAuthentication

class ParticipantViewMobile(APIView):
    permission_classes = (MobileTokenPermission, )
    authentication_classes = (MobileTokenAuthentication, )

    def post(self, request, service_id, campaign_id):
        try:
            environment_info = Header.get_environment_info(request)

            request.data[Field.GAME_SERVICE_ID] = service_id
            request.data[Field.CAMPAIGN] = campaign_id
            request.data[Field.LOCATION] = environment_info

            participation_serializer = RegisterParticipationSerializer(data=request.data)
            participation_serializer.is_valid(raise_exception=True)
            participation_serializer.save()

            return ResponseUtils.created()
        except Http404:
            raise GameOrCampaignDoesNotExist()

serializers.py

class RegisterParticipationSerializer(serializers.ModelSerializer):
    location = LocationSerializer(many=False)
    campaign = serializers.IntegerField()
    game_service_id = serializers.CharField(max_length=254)

    class Meta:
        model = Participation
        fields = (Field.PK, Field.EMAIL, Field.GPG_ID, Field.DATE, Field.LOCATION, Field.INFO, Field.CAMPAIGN,
                  Field.GAME_SERVICE_ID, Field.GCM_ID)
        read_only_fields = (Field.GCM_ID,)

test_views.py

from mock import patch
from django.core.urlresolvers import reverse
from rest_framework.test import APITestCase, APIRequestFactory
from rest_framework import status
from rest_framework.exceptions import ValidationError

from gmm_mobile.v1.views import ParticipantViewMobile
from gmm_mobile.v1.urls import CONSULT_PARTICIPANT
from gmm_push.environment_configuration import EnvironmentConfiguration
from gmm_util.util_test import JsonObjects

class ParticipantViewMobileTests(APITestCase):

    factory = APIRequestFactory()
    url = reverse(PARTICIPANT_MOBILE, kwargs={'service_id': 1, 'campaign_id': 1})

    def setUp(self):
        self.view = ParticipantViewMobile.as_view()

    @patch('gmm_mobile.v1.views.RegisterParticipationSerializer')
    def test__post__invalid_data__status_400(self, mock_serializer):
        # Arrange
        mock_serializer.is_valid.side_effect = ValidationError({})
        request = self.factory.post(
            self.url,
            {},
            HTTP_X_ENV=JsonObjects.environment_info_1(),
            HTTP_X_TOKEN=EnvironmentConfiguration.get_token(False),
            format='json')
        # Act
        response = self.view(request, 1, 1)
        # Assert
        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)

但是当我运行测试时,side_effect无效。当我更改测试中的.is_valid时,它对ParticipantViewMobile.post无效。

如果我@patch('gmm_mobile.v1.views.RegisterParticipationSerializer.is_valid')mock_serializer.side_effect = ValidationError({})它有效,但我不想要,因为有些情况我需要模拟多个方法,例如{{1} }和.save

我还尝试更改导入样式.is_validviews.py,但它仍然无法正常工作。

我做错了什么或遗失了什么?

编辑1:

我在视图上放置了打印件以试图了解发生了什么:

test_views.py

输出:

def post(self, request, service_id, campaign_id):
    try:
        environment_info = Header.get_environment_info(request)

        request.data[Field.GAME_SERVICE_ID] = service_id
        request.data[Field.CAMPAIGN] = campaign_id
        request.data[Field.LOCATION] = environment_info

        participation_serializer = RegisterParticipationSerializer(data=request.data)
        print RegisterParticipationSerializer.is_valid.side_effect
        print participation_serializer.is_valid.side_effect
        participation_serializer.is_valid(raise_exception=True)
        participation_serializer.save()

        return ResponseUtils.created()
    except Http404:
        raise GameOrCampaignDoesNotExist()

因此,当我创建{} None 的实例时,我丢失了模拟方法。怎么避免这个?

1 个答案:

答案 0 :(得分:2)

你的模拟不起作用,因为你是在模拟类,而不是从类生成的实例。试试这个:

mock_instance = Mock()
mock_instance.is_valid.side_effect = ValidationError({})
mock_serializer.return_value = mock_instance