【问题标题】:how do i implement a python unit-test for a method which accepts filepath as argument?我如何为接受文件路径作为参数的方法实现 python 单元测试?
【发布时间】:2023-03-18 23:21:01
【问题描述】:
class A:
    def read_json(self,file_json_path):
        try:
            with open(file_json_path) as fd:
                content = json.dumps(fd)
         except IOError:
            print 'exception while opening a file %s\n'%(file_json_path)

我是 python 新手,谁能指导我,如何模拟打开文件和读取 json 数据。

【问题讨论】:

  • 我会使用一个已知的小型 json 文件,并且您会知道相对路径,因为 testdata 文件夹可能是测试所在的子文件夹。
  • 您应该使用临时文件。关闭后它会立即删除它。

标签: python python-unittest


【解决方案1】:

您需要从模拟模块查看mock_open。它可以让你修补内置的 open 方法来伪造读/写。

如果有这个功能(注意我改变了你的功能):

def read_json(file_json_path):
    try:
        with open(file_json_path) as fd:
            content = json.load(fd)
            return content
    except IOError:
        print('exception while opening a file %s\n' % (file_json_path))

您可以通过以下方式轻松测试该功能:

def test_read_json():
    from unittest.mock import mock_open, patch

    m = mock_open(read_data = '{"key": "value"}')
    with patch('__main__.open', m):
        result = read_json('fake_file')
        assert result == {'key': 'value'}
    m.assert_called_once_with('fake_file')

【讨论】:

  • 请多一点上下文给你回答。解释为什么使用 mock_open 是个好主意,如果你能提供一些相同的代码 sn-ps 会非常有帮助
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-05-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多