Django - 在模型上模拟save方法

时间:2014-12-27 13:37:36

标签: python django unit-testing mocking

关于Django单元测试的初学者问题我还在这里^^

我正在尝试测试模型的保存功能,而不是实际调用保存。

以下是我想测试的方法:

from django.db import models
from django.contrib.auth import models as auth_model
from allauth.socialaccount import models as allauth_model

class KangaUserManager(models.Manager):
    def create(self, username, email, password, last_name, first_name, request, registered=True, send_confirmation=True):
        kanga_user = KangaUser()
        kanga_user.user = auth_model.User.objects.create_user(
            username=username,
            email=email,
            password=password,
            first_name=first_name,
            last_name=last_name
        )
        kanga_user.preferred_language = translation.get_language()
        kanga_user.registered = registered
        kanga_user.save()

        return kanga_user

这是测试

@mock.patch('model.models.KangaUser')
@mock.patch('django.contrib.auth.models.User')
def test_create(self, UserMock, KangaUserMock):
    # Mocking configuration
    # User
    UserMock.objects = mock.MagicMock()
    UserMock.objects.create_user = mock.MagicMock()
    user_return_value = User(id=1)
    UserMock.objects.create_user.return_value = user_return_value

     # Test
    kangauser_manager = models.KangaUserManager()
    kanga_user = kangauser_manager.create(self.username, self.email, self.password, self.last_name, self.first_name, self.request, self.registered, self.send_confirmation)

    # Checks
    # create_user called with good parameters
    UserMock.objects.create_user.assert_called_with(username=self.username, email=self.email, password=self.password, first_name=self.first_name, last_name=self.last_name)
    # KangaUser 
    self.assertTrue(models.KangaUser.save.called)

第一个测试(UserMock.objects.create_user.assert_called_with)没问题,但是对于第二个测试,我总是得到“AssertionError:False is not true”

1 个答案:

答案 0 :(得分:7)

经过一些谷歌搜索,我发现了一些有用的东西:

@mock.patch.object(models.KangaUser, 'save')
@mock.patch('django.contrib.auth.models.User')
def test_create(self, user_class_mock, kangauser_save_mock):
    # Mocking configuration
    # User
    user_class_mock.objects = mock.MagicMock()
    user_class_mock.objects.create_user = mock.MagicMock()
    user_class_mock.objects.create_user.return_value = User(id=1)

    # Test
    kangauser_manager = models.KangaUserManager()
    kanga_user = kangauser_manager.create(self.username, self.email, self.password, self.last_name, self.first_name, self.request, self.registered, self.send_confirmation)

    # Checks
    # create_user called with good parameters
    user_class_mock.objects.create_user.assert_called_with(username=self.username, email=self.email, password=self.password, first_name=self.first_name, last_name=self.last_name)
    # KangaUser 
    self.assertTrue(kangauser_save_mock.called)

所以,诀窍是使用@ mock.patch.object!