我正在尝试在以下类中测试read()
方法:
class Channel(sam.Sam):
def __open(self):
try:
self.__channel = open('%s/channel.ini' % os.path.dirname(os.path.realpath(__file__)), 'r+')
except Exception as e:
traceback.print_exc(file = sys.stdout)
raise e
def read(self):
try:
self.__open()
return JSONEncoder().encode({
"status": True,
"channel": self.__channel.read().strip()
})
except Exception as e:
traceback.print_exc(file = sys.stdout)
return JSONEncoder().encode({
"status": False
})
finally:
self.__close()
据我了解,我应该嘲笑file.read()
方法(在self.__channel.read()
,或者可能是os.open()
方法,但我发现的所有例子都没有在类中深入调用os.open()
或file.read()
。
我已经尝试过__builtin__.read = MagicMock(return_value="something")
及其中的许多变体,但其中没有一个甚至有意义。我有点迷失甚至如何开始这个。
这是正确的方式吗?
模拟open
功能;您可以使用mock_open()
utility function提供合适的模拟:
from unittest.mock import mock_open
with patch('your_module.open', mock_open(read_data=JSON_TEST_DATA), create=True) as m:
result = Channel().read()
assert m.assert_called_once_with(expected_file_name)
patch()
调用在open
命名空间中创建一个新的全局your_module
对象,因此当Channel.__open()
方法运行时,它将找到该对象而不是open()
内置函数。
通过将read_data
参数传递给mock_open()
,您可以决定self.__channel.read()
调用返回的内容。