[英]python mocking configobj's return value
I have a method that I would like to create a unittest for. 我有一种方法想要为其创建单元测试。 ConfigObj is just a library for parsing config files.
ConfigObj只是用于解析配置文件的库。 The method is very simple:
方法很简单:
from configobj import ConfigObj
def read_name():
conf = ConfigObj('/data/myfile')
return conf['name']
conf['name'] returns a string value of the 'name' setting in the file. conf ['name']返回文件中'name'设置的字符串值。 I am trying to write a unit test to mock this return behavior, but I am running into a "KeyError" on conf['name'].
我试图编写一个单元测试来模拟这种返回行为,但是我在conf ['name']上遇到了“ KeyError”问题。 It doesn't look like the conf instance was mocked at all.
看起来conf实例根本没有被嘲笑。
My test so far: 到目前为止,我的测试:
@mock.patch('configobj.ConfigObj')
def test_read_name(self, mock_configobj):
config = mock_configobj.return_value
config.__getitem__.side_effect = 'tom'
self.assertEqual(read_name(), 'tom')
As it turns out it was very simple 事实证明,这非常简单
@patch('configobj.ConfigObj.__getitem__', return_value='tom')
def test_get_name(self, mock_configobj)
self.assertEqual(read_name(), 'tom')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.