Customizing unittest.mock.mock_open for iteration

前端 未结 3 1617

How should I customize unittest.mock.mock_open to handle this code?

file: impexpdemo.py
def import_register(register_fn):
    with open(register_fn) as f:
           


        
3条回答
  •  情歌与酒
    2020-12-01 11:02

    As of Python 3.6, the mocked file-like object returned by the unittest.mock_open method doesn't support iteration. This bug was reported in 2014 and it is still open as of 2017.

    Thus code like this silently yields zero iterations:

    f_open = unittest.mock.mock_open(read_data='foo\nbar\n')
    f = f_open('blah')
    for line in f:
      print(line)
    

    You can work around this limitation via adding a method to the mocked object that returns a proper line iterator:

    def mock_open(*args, **kargs):
      f_open = unittest.mock.mock_open(*args, **kargs)
      f_open.return_value.__iter__ = lambda self : iter(self.readline, '')
      return f_open
    

提交回复
热议问题