1

我很难理解如何使用unittest.mock库。
我有这个模型:

from django.db import models

class Data(models.Model):
    field1 = models.CharField(max_length=50)
    field2 = models.CharField(max_length=50)
    // ... more fields

    _PASSWORD_KEY = 'some_random_password_key'
    _password = models.CharField(max_length=255, db_column='password')

    def _set_password(self, raw_password):
        """
        Encode raw_password and save as self._password
        """
        // do some Vigenère magic

    def _get_password(self):
        """
        Decode encrypted password with _PASSWORD_KEY and return the original.
        """
        return raw_password

    password = property(_get_password, _set_password)

我想测试_set_password当我这样做时调用的那个data = Data(password='password')
我手动确认它被调用了,但是这个单元测试失败了(我从 unittest.mock 文档的例子中得到):

from mock import patch
from someapp.models import Data

def test_set_password_is_called(self):
    with patch.object(Data, '_set_password') as password_method:
        data = Data(password='password123')

    password_method.assert_called_once_with('password123')

使用此消息:

Failure
Traceback (most recent call last):
  File "/Users/walkman/project/someapp/tests.py", line 75, in test_set_password_is_called
    password_method.assert_called_once_with('password123')
  File "/usr/local/lib/python2.7/site-packages/mock.py", line 845, in assert_called_once_with
    raise AssertionError(msg)
AssertionError: Expected to be called once. Called 0 times.

我做错了什么?

4

1 回答 1

0

因为密码是一个属性,属性类 getter 和 setter 上的属性在调用堆栈中使用,所以您最终不会调用类上的修补属性。您可以更改测试,类似于此处所述

http://www.voidspace.org.uk/python/weblog/arch_d7_2011_06_04.shtml

注意这有效

class Test(object):

def test(self):
    return self.test2()


def test2(self):
    print("This was Called")

和测试

with patch.object(Test, 'test2') as mock_method:
    d = Test()
    d.test()

mock_method.assert_called()
于 2013-06-03T10:23:18.290 回答