如何在 Python3 中模拟没有读取权限的文件?

How to mock a file with no read permission in Python3?

如何修改以下代码使测试通过??

import unittest
import unittest.mock as mock


def read_file(file_name):
    '''
        returns: tuple(error_code, data)
                 error_code = 1: file found, data will be read and returned.
                 error_code = 2: file not found, data is None.
                 error_code = 3: file found by cannot read it.
    '''
    try:
        with open(file_name) as fh:
            data = fh.read()
        return 1, data
    except FileNotFoundError:
        return 2, None
    except PermissionError:
        return 3, None


class TestReadFile(unittest.TestCase):
    @mock.patch('builtins.open', mock.mock_open(read_data=b''))
    def test_file_permission(self):
        err_code, data = read_file('file_name')
        assertEqual(err_code, 3)

我试着阅读这篇文章:https://docs.python.org/3/library/unittest.html 但找不到任何解决方案。

您在程序中使用的逻辑是正确的,但问题是您在某些地方使用了错误的标识符:

1) unittest 没有 class Test,它有 TestCase

2) 您要测试的函数名为 read_file(),但在调用它时,您调用的是 file_read()

3) mock.mock_open() 的关键字参数不是 data,而是 read_data.

这是包含建议更改的代码:

import unittest
import unittest.mock as mock


def read_file(file_name):
    '''
        returns: tuple(error_code, data)
                 error_code = 1: file found, data will be read and returned.
                 error_code = 2: file not found, data is None.
                 error_code = 3: file found by cannot read it.
    '''
    try:
        with open(file_name) as fh:
            data = fh.read()
        return 1, data
    except FileNotFoundError:
        return 2, None
    except PermissionError:
        return 3, None


class TestReadFile(unittest.TestCase):
    @mock.patch('builtins.open', mock.mock_open(read_data=''))
    def test_file_permission(self):
        err_code, data = read_file('file_name')
        assertEqual(err_code, 3)