工作中遇到一个问题, 记录一下。
在Python的单元测试中,通常用mock_open 来模拟open,通常用法如下:
import mock
mock.__version__ = 2.0.0
@patch("__builtin__.open", side_effect=IOError)
def test_parse_cc_false(self, mock):
ret, _ = parse_cc()
self.assertEqual(ret, -1)
@patch("__builtin__.open", mock_open(read_data="AA\n CN\tChina\nUS\tUnited States\nCC\tCocos (Keeling) Islands\n"))
def test_parse_cc_true(self):
ret, _ = parse_cc()
self.assertEqual(ret, 0)
在这种用法下,只需要mock_open, 就可以直接mock了 read, readline, readlines.
但是在mock 1.0.1 中,这样的写法只能mock open 函数本身,当调用
例如:f=open('a.txt', 'r') content = f.readlines() 时, content 只能是一个mock对象,而不是一个具体的内容。这个时候就需要手动地把readlines 也进行mock.写法如下:
@patch("__builtin__.open")
def test_parse_cc_true(self, mock):
mock.return_value.readlines.return_value = "AA\n CN\tChina\nUS\tUnited States\nCC\tCocos (Keeling) Islands\n"
ret, _ = parse_cc()
self.assertEqual(ret, 0)