【问题标题】:Get the argument passed to mock_open and call a different function for mock获取传递给 mock_open 的参数并为 mock 调用不同的函数
【发布时间】: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_openfile_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


    【解决方案1】:

    执行以下操作:

    @mock.patch("blah.blah.boto3.Session")
    def test_open(m_session):
        m_open = mock.mock_open()
        with patch("module.smart_open", m_open, create=True):
            do_writing_function()
            m_open.return_value.write.assert_called_once_with(expected_stuff)
    
    

    基本上你用 mock_open 修补 smart_open 的 open,然后你可以读到 mock_open 的 write 是用什么调用的。 call_args_list 也应该在这里工作。

    我自己修补了 boto3.Session 以避免处理我的模块中的会话内容,但由于 open 被模拟,您实际上不会尝试在测试中从给定文件路径打开任何内容。

    在我的例子中,我也有我的 open()/write 在一个单独的函数中,你可能也想这样做。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-04-02
      • 1970-01-01
      • 2015-08-10
      • 2011-03-04
      • 2021-04-13
      • 2015-08-20
      • 1970-01-01
      相关资源
      最近更新 更多