python-3.x - 你如何在 python 中模拟多个文件打开和读取?
问题描述
我在 Python 中有以下类:
# lib/filesum.py
class FileSum(object):
def __init__(self, path1, path2, path3):
self.path1 = path1
self.path2 = path2
self.path3 = path3
self.a = int(open(self.path1).read().strip())
self.b = int(open(self.path2).read().strip())
def save_sum(self):
s = self.a + self.b
open(self.path3, mode='w').write(str(s))
我想编写一个单元测试来测试该save_sum()
方法。如何模拟两个调用 open 和一个为不同文件编写的调用,而不必在运行测试时在那里有实际文件?我想忽略(而不是模拟)与除了这 3 个文件之外的任何其他文件的任何交互。
编辑:
我的尝试是:
def mock_file_open(filename, mode='r'):
if filename == "a.txt":
content = "3"
elif filename == 'b.txt':
content = "2"
else:
# I want to leave all other file interactions alone but
#this causes infinite resursion
return open(filename, mode=mode)
file_object = mock.mock_open(read_data=content).return_value
file_object.__iter__.return_value = content
return file_object
...
with mock.patch('builtins.open', new=mock_file_open):
...
解决方案
推荐阅读
- laravel - Laravel 旧图像未使用 getOriginal 方法删除
- scala - 在 Spark 上训练 Kmeans 算法失败
- python - python中函数参数中的“或”是什么意思?
- .htaccess - 通过 RewriteCond 和 .htaccess 对 RewriteRule 进行分组
- android - 缺少必需的参数“名称”并且没有 android:defaultValue
- php - Doctrine COALESCE、SUM 和 Subtract 导致语法错误:预期的 Doctrine\ORM\Query\Lexer::T_FROM, got '-'
- java - 使用 java 在 apche_beam 中编写 tfrecords
- scala - 如何使用 Kafka、Alpakka Kafka、Play Framework 和 Websocket 处理 POST 请求?
- php - 在大型数据输入期间防止 sqlite3_php 数据库锁定的最佳实践?
- java - 链接选项