python - 如何为接受文件路径作为参数的方法实现 python 单元测试?
问题描述
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 数据。
解决方案
您需要从 mock 模块查看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')
推荐阅读
- complex-event-processing - 如何创建一个 Esper 语句并自动设置订阅者,这样我就不会错过任何更新?
- node.js - 如何从 npm 安装 vue cli 而不会出现任何错误?
- jwt - 如何在 Keycloak 中拥有除 JWT 之外的另一种令牌格式?
- apache-nifi - Apache NiFi 进程间通信
- composer-php - 作曲家和共享主机
- c# - Linq 选择具有匹配子项的父/父记录
- java - 如何在 Java 中使用正则表达式捕获多次出现的组
- json - 如何测试 FeignClient 解组?
- shell - 如何从 SONAME 字段中提取共享库版本?
- python - numpy.where() 返回空数组而不是替换