如何模拟python的read()

问题描述 投票:2回答:1

我正在尝试在以下类中测试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")及其中的许多变体,但其中没有一个甚至有意义。我有点迷失甚至如何开始这个。

这是正确的方式吗?

python unit-testing mocking
1个回答
3
投票

模拟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()调用返回的内容。

© www.soinside.com 2019 - 2024. All rights reserved.