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

时间:2016-06-10 15:55:17

标签: 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吗?我有点嘲笑。

编辑:我取得了一些进展。我认为问题是我试图修补错误的对象。使用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 object has no attribute 'read'

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

@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'>)

1 个答案:

答案 0 :(得分:1)

  

AssertionError:预期调用:storbinary('STOR output.zip',)

     

实际调用:storbinary('STOR output.zip',&lt; _io.TextIOWrapper name ='。/ output / output.zip'mode ='r'noding ='UTF-8'&gt;)

实际调用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"

我尝试在另一个模块中模拟open并且它有效,当与assert_called_once_with()一起使用时有一个问题。修补open mock时使用MagicMock对象,每次调用open()都会返回一个新对象。因此,使用open样式语句修补with as m的测试用例与[{1}}广告m的公开调用相比,to_ftp的值不同。

虽然我确信assert_called_once_with()Mock有更好的方法,但在模拟assert_called_once_with时我使用StringIO对象,以便每次调用都返回< em>相同的 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__的模块。

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

1)这看起来像你正在寻找的答案: How do I mock an open used in a with statement (using the Mock framework in Python)? 它使用to_ftp嘲笑open

2)

  

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

它正在抱怨读取,因为您将读取方法传递给<local module name>.open

storbinary

并且您的模拟的open ftp.storbinary(" ".join(["STOR", file_name]), ftp_file.read) 实例没有该方法。

3)您正在检查ftp_file是否已使用storbinary进行了调用,但您正在传递m.read()m.read调用read方法,而m.read()是方法的引用。

m.read

4)查看ftp.storbinary的文档,它期望文件对象本身,而不是对文件对象mock_ftp.return_value.storbinary.assert_called_once_with("STOR output.zip", m.read()) 方法的引用。它应该是:

read

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

相关问题