python - 模拟内置函数在导入模块中打开

标签 python unit-testing ftp mocking

我想测试是否使用正确的参数调用了 ftp.storbinary() 函数。然而,这是与现场测试不同的模块的一部分。

io.py 模块中我有这个方法(它是类的一部分):

def to_ftp(self, output_path, file_name, host, username, password):
    """Upload file to FTP server."""

    ftp = ftplib.FTP(host)
    ftp.login(username, password)
    full_path = os.path.join(output_path, file_name)
    with open(full_path, "r") as ftp_file:
        ftp.storbinary(" ".join(["STOR", file_name]), ftp_file.read)

我创建了一个 test_io.py 模块,其中包含一系列单元测试。我正在考虑同时修补 openftplib.FTP,因为我正在传递给 ftp.storbinary() ftp_file.read ()

@patch("ppc_model.io.ftplib.FTP")
def test_store_call(self, mock_ftp):
    """The *storbinary* call must use the right arguments."""

    with patch("ppc_model.io.open", mock_open(read_data=None)) as m:
        self.writer.to_ftp(output_path="./output", file_name="output.zip",
                       host="myftp", username="username", password="password")
    mock_ftp.return_value.storbinary.assert_called_once_with(
    "STOR output.zip", m.read())

然而,这会返回一个 AttributeError,因为该模块没有属性 open。我如何确保 Mock 理解我正在尝试模拟内置函数?

是否还有更好的方法来测试我是否将正确的参数传递给 ftp.storbinary?我对 mock 有点陌生。

编辑:我取得了一些进展。我认为问题是我试图修补错误的对象。使用 open 我想我必须修补 builtins.open。有点违反直觉。

@patch("ppc_model.io.ftplib.FTP")
def test_store_call(self, mock_ftp):
    """The *storbinary* call must use the right arguments."""

    with patch("builtins.open", mock_open(read_data=None), create=True) as m:
        self.writer.to_ftp(output_path="./output", file_name="output.zip",
                       host="myftp", username="username", password="password")
    mock_ftp.return_value.storbinary.assert_called_once_with(
    "STOR output.zip", m.read())

不幸的是,现在编译器提示 Mock 对象没有 read 方法。

AttributeError: Mock 对象没有属性 'read'

编辑 2: 按照 RedCraig 的建议,我修补了本地命名空间中的 open 方法并传递给 ftp.storbinary ftp_file 而不是ftp_file.read())。所以当前的单元测试是:

@patch("ppc_model.io.ftplib.FTP")
def test_store_call(self, mock_ftp):
    """The *storbinary* call must use the right arguments."""

with patch("{}.open".format(__name__), mock_open(read_data=None),
           create=True) as m:
    self.writer.to_ftp(output_path="./output", file_name="output.zip",
                   host="myftp", username="username", password="password")
mock_ftp.return_value.storbinary.assert_called_once_with(
"STOR output.zip", m)

以及我要测试的代码:

def to_ftp(self, output_path, file_name, host, username, password):
    """Upload file to FTP server."""

    ftp = ftplib.FTP(host)
    ftp.login(username, password)
    full_path = os.path.join(output_path, file_name)
    with open(full_path, "r") as ftp_file:
        ftp.storbinary(" ".join(["STOR", file_name]), ftp_file)

我得到的当前错误是:

AssertionError: Expected call: storbinary('STOR output.zip', <MagicMock name='open' spec='builtin_function_or_method' id='140210704581632'>)
Actual call: storbinary('STOR output.zip', <_io.TextIOWrapper name='./output/output.zip' mode='r' encoding='UTF-8'>)

最佳答案

AssertionError: Expected call: storbinary('STOR output.zip', )

Actual call: storbinary('STOR output.zip', <_io.TextIOWrapper name='./output/output.zip' mode='r' encoding='UTF-8'>)

对于实际调用,storbinary 被赋予 <_io.TextIOWrapper... 而不是模拟对象。好像 open 的模拟不起作用,也许你的模块名称不正确。

这是 unittest.mock examples ,这个页面有一个模拟打开的例子:

>>> mock = MagicMock(return_value=sentinel.file_handle)
>>> with patch('builtins.open', mock):
...     handle = open('filename', 'r')
...
>>> mock.assert_called_with('filename', 'r')
>>> assert handle == sentinel.file_handle, "incorrect file handle returned"

我尝试在另一个模块中模拟打开并且它有效,将它与 assert_called_once_with() 一起使用时有一个问题。当 patching open mock 使用 MagicMock 对象时,每次调用 open() 都会返回一个新对象。因此,使用 open 样式语句修补 with as m 的测试用例的 m 值将不同于来自 to_ftp 的 open 调用,而 assert_called_once_with() 将失败。

虽然我确信 Mockassert_called_once_with 有更好的方法,但我在模拟 StringIO 时求助于使用 open 对象,以便每次调用都返回相同 StringIO 实例:

import ftplib
import os

from io import StringIO
from unittest import TestCase
from unittest.mock import patch


def to_ftp(output_path, file_name, host, username, password):
    """Upload file to FTP server."""
    ftp = ftplib.FTP(host)
    ftp.login(username, password)
    full_path = os.path.join(output_path, file_name)
    with open(full_path, "r") as ftp_file:
        ftp.storbinary(" ".join(["STOR", file_name]), ftp_file)


class TestOpenMock(TestCase):
    @patch("ftplib.FTP")
    def test_store_call(self, mock_ftp):
        """The *storbinary* call must use the right arguments."""
        open_file = StringIO('test_data')
        with patch('%s.open' % __name__, return_value=open_file):
            to_ftp(output_path="./output", file_name="output.zip",
                   host="myftp", username="username", password="password")

        mock_ftp.return_value.storbinary.assert_called_once_with(
            "STOR output.zip", open_file)

这就过去了。显然,您必须将 '%s.open' % __name__ 更改为包含 to_ftp 的模块。


原始答案(@any so mod:我应该删除这个吗?):

1) 这看起来像您正在寻找的答案: How do I mock an open used in a with statement (using the Mock framework in Python)? 它使用 open 模拟 <local module name>.open

2)

AttributeError: Mock object has no attribute 'read'

它提示读取,因为您将读取方法传递给 storbinary :

ftp.storbinary(" ".join(["STOR", file_name]), ftp_file.read)

并且您的 open ftp_file 模拟实例没有该方法。

3) 您正在检查是否使用 storbinary 调用了 m.read() 但您传入了 m.readm.read() 调用读取方法,而 m.read 是对该方法的引用。

mock_ftp.return_value.storbinary.assert_called_once_with("STOR output.zip", m.read())

4) 查看 ftp.storbinary 的文档,它需要文件对象本身,而不是对文件对象 read 方法的引用。应该是:

ftp.storbinary(" ".join(["STOR", file_name]), ftp_file)

传入(模拟的)文件对象将解决上面的第 3) 点。

关于python - 模拟内置函数在导入模块中打开,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37752485/

相关文章:

python - 如何使用 pandas 进行左连接

c# - 如何在 Silverlight 单元测试框架中记录输出?

ruby - 使用 Ruby SFTP 删除文件 `remove` 和 `remove!`

java - 如何使用 Jsch 递归地 FTP 目录结构?

python - Keras 如何优化没有激活的层上的权重?

python - 从 csv.dictreader 排序和过滤数据

python - 与 Django 的 MySQL 连接错误

eclipse - 模拟 eclipse SWT/JFACE 对话框和小部件

java - 尝试使用 Mockito 模拟 Apache HTTP 客户端时出现的问题

ftp - 上传到 z/OS 的文件中出现意外的换行符