如何模拟 python 的 read()
How to mock python's read()
我正在尝试在以下 class 中测试 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()
方法,但是 none 我的示例我发现在 class.
的深处调用了 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()
调用在您的 your_module
命名空间中创建了一个新的全局 open
对象,因此当 Channel.__open()
方法运行时它会找到 that 对象而不是 open()
内置函数。
通过将 read_data
参数传递给 mock_open()
,您可以指定 self.__channel.read()
调用返回的内容。
我正在尝试在以下 class 中测试 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()
方法,但是 none 我的示例我发现在 class.
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()
调用在您的 your_module
命名空间中创建了一个新的全局 open
对象,因此当 Channel.__open()
方法运行时它会找到 that 对象而不是 open()
内置函数。
通过将 read_data
参数传递给 mock_open()
,您可以指定 self.__channel.read()
调用返回的内容。