我正在尝试对一个SFTP helper类进行单元测试,该类调用pysftp模块。我想模拟来自pysftp的实际网络调用,这样就不会有任何副作用,只需确保类使用正确的参数正确地调用底层SFTP方法。在
以下是迄今为止我的代码的一个简单示例:
import pysftp
import unittest
import mock
class SFTPHelper(object):
def __init__(self, host, username, password, files_dir):
self.host = host
self.username = username
self.password = password
self.files_dir = files_dir
def list_files(self):
with pysftp.Connection(
self.host,
username=self.username,
password=self.password) as sftp:
return sftp.listdir(self.files_dir)
class TestSFTPHelper(unittest.TestCase):
@mock.patch('pysftp.Connection')
def test_list_files(self, mock_connection):
sftp_helper = SFTPHelper('somehost', 'someuser', 'somepassword', '/some/files/dir')
sftp_helper.list_files()
# this assertion passes
mock_connection.assert_called_with(
'somehost', password='somepassword', username='someuser')
# this assertion does not pass
mock_connection.listdir.assert_called_with('/some/files/dir')
断言错误:
^{pr2}$我假设它不起作用,因为我需要断言函数是在实例上调用的,但是我如何获得pysftp.连接在我的方法里用过的?在
您可以将mock配置为返回一个定义了
__enter__
和__exit__
方法的新模拟对象。例如:此外,您可能需要使用:
^{pr2}$而不是:
作为补充说明,您还可以将示例中
assert_called_with
的两种用法都替换为assert_called_once_with
。在最终结果:
相关问题 更多 >
编程相关推荐