我很难理解如何使用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.
我做错了什么?