![](/img/trans.png)
[英]Python unittest.mock: patched class method called but assertion fails
[英]How to unittest that a django model method called with unittest.mock?
我很难理解如何使用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)
我想测试在执行data = Data(password='password')
时是否调用了_set_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.
我做错了什么?
因为密码是一个属性,并且属性类的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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.