【发布时间】:2021-09-16 20:56:32
【问题描述】:
我想使用mock_open 来模拟打开文件的功能,但是,我想知道传递的实际参数:
# module.py
file_path = "path/to/file"
with open(file_path, "r") as f:
contents = f.read()
# test_module.py
from moto import mock_open
from unittest.mock import patch
def test_open():
with patch("module.open", mock_open(
with open(file_path) as f:
contents = f.read()
return contents
):
现在我知道你在想什么了,这完全没用而且很愚蠢,因为它破坏了mock_open 的目的。
但是,我实际上想模拟一个不同的函数,即smart_open,而不是在 S3 上打开文件,而是在本地测试环境中使用它。因此,我想使用file_path 传递给smart_open,然后使用open 来获取实际内容。我也不能直接使用 open,因为传递给 smart_open 的 file_path 的前缀是 s3://,我想去掉它。
本质上,这就是它实际上的样子:
# module.py
from smart_open import open as smart_open
file_path = "s3://path/to/file"
with smart_open(file_path, "r") as f:
contents = f.read()
# test_module.py
from moto import mock_open
from unittest.mock import patch
from utils import preprocess_path
def test_open():
with patch("module.smart_open", mock_open(
# something to pass to mock_open that says to do the following
# get rid of the s3:// in the beginning
file_path = preprocess_path(file_path)
# get the contents using open instead of smart_open
with open(file_path) as f:
contents = f.read()
return contents
):
是否可以使用传递给smart_open 的参数进行一些预处理并调用不同的函数(在本例中为open)?
【问题讨论】:
标签: python python-3.x unit-testing mocking patch