【发布时间】:2013-06-03 00:29:13
【问题描述】:
我很难理解如何使用 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.
我做错了什么?
【问题讨论】:
-
模拟文档有一个example for mocking properties 使用
PropertyMock。也许这会有所帮助? -
with patch('tracker.models.PlayingHistoryAudit._set_password', new_callable=PropertyMock) as mock_password:也不能解决问题:( -
请注意,该示例并未模拟 setter,而是模拟属性本身,即
patch('tracker.models.PlayingHistoryAudit.password', ..)... hmm,但刚刚意识到可能不适合检查 setter 是否被调用。 -
没错!我想检查二传手是否正确地完成了它的工作。也许检查它的方法是在赋值后查找 _password 属性。
-
更改测试并确定设置器(即 _set_password)通过测试值是否符合您的期望来执行您期望的操作可能是最简单的。
标签: python unit-testing python-mock