python-3.x - 如何在 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
没有类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)
推荐阅读
- angular - 在 Angular 中使用可见性属性而不是 display 有条件地显示元素
- amazon-web-services - 尝试在 Amazon EFS 上创建文件夹时权限被拒绝
- node.js - 带有 puppeteer 的谷歌云功能不起作用,即使它在 firebase 函数模拟器中工作
- abap - 使桌子可定制/可移动?
- java - 无法获得带有所选文件名称的完整真实路径
- flutter - 如何在脚手架中有多种背景颜色?
- javascript - 从 queue() 到 Promise
- sql - SQL Server 临时表重新创建
- firebase - 使用 Flutter Web 刷新后如何维护 Firebase 身份验证?
- javascript - 如何通过鼠标悬停在javascript上交换html的div?