首页 > 解决方案 > 如何在 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但找不到任何解决方案。

标签: python-3.xmockingpython-unittest

解决方案


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

1)unittest没有类Test,它有TestCase

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

3) 关键字参数mock.mock_open()is not data, but 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)

推荐阅读