我应该如何自定义 unittest.mock.mock_open 来处理这段代码?
file: impexpdemo.py
def import_register(register_fn):
with open(register_fn) as f:
return [line for line in f]
我的第一次尝试尝试了read_data
。
class TestByteOrderMark1(unittest.TestCase):
REGISTER_FN = 'test_dummy_path'
TEST_TEXT = ['test text 1\n', 'test text 2\n']
def test_byte_order_mark_absent(self):
m = unittest.mock.mock_open(read_data=self.TEST_TEXT)
with unittest.mock.patch('builtins.open', m):
result = impexpdemo.import_register(self.REGISTER_FN)
self.assertEqual(result, self.TEST_TEXT)
这失败了,大概是因为代码没有使用 read、readline 或 readlines。unittest.mock.mock_open的文档说,“read_data 是文件句柄的 read()、readline() 和 readlines() 方法返回的字符串。对这些方法的调用将从 read_data 获取数据,直到它耗尽“
由于文档没有提示需要什么样的自定义,我尝试return_value
了side_effect
. 都没有奏效。
class TestByteOrderMark2(unittest.TestCase):
REGISTER_FN = 'test_dummy_path'
TEST_TEXT = ['test text 1\n', 'test text 2\n']
def test_byte_order_mark_absent(self):
m = unittest.mock.mock_open()
m().side_effect = self.TEST_TEXT
with unittest.mock.patch('builtins.open', m):
result = impexpdemo.import_register(self.REGISTER_FN)
self.assertEqual(result, self.TEST_TEXT)