如何模拟python的read()

时间:2015-08-04 13:26:57

标签: python unit-testing mocking

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

这是否正确?

1 个答案:

答案 0 :(得分: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()来电所返回的内容。