首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >在python3中测试paramiko

在python3中测试paramiko
EN

Stack Overflow用户
提问于 2020-02-24 14:39:55
回答 1查看 1.1K关注 0票数 0

因此,我有一个方法:

代码语言:javascript
复制
def ftp_fetch(self, hostname=None, username=None, password=None, file_name=None):
        source_data = ''
        if hostname and username and password and file_name:
            ssh = paramiko.SSHClient()
            ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
            try:
                ssh.connect(hostname, username=username, password=password)
            except paramiko.SSHException:
                print("Connection Error")
            sftp = ssh.open_sftp()
            source_data = json.loads(
                sftp.file(file_name).read()
            )
            ssh.close()
            return source_data
        return False

..。因此,一项试验:

代码语言:javascript
复制
@patch('paramiko.SSHClient')
def test_ftp_fetch(mock_ssh):
    test_content = '{"date": "06/02/2020", "time": "07:55", "floors":[{"floor": "地面", "capacity": 149, "occupancy": "20"},{"floor": "قبو", "capacity": 184, "occupancy": "20"}]}'
    mock_ssh.open_sftp().file().read().return_string = test_content
    foo = PreProcessor(code="foo")
    response = foo.ftp_fetch()
    assert response == False
    response = foo.ftp_fetch(hostname='http://foo/', username='foo', password = 'bar', file_name = 'baz')
   assert response == json.loads(test_content)

无论我试图用模拟做什么,我都会得到相同的错误:

代码语言:javascript
复制
___________________________________________________________________________ test_ftp_fetch ___________________________________________________________________________

mock_ssh = <MagicMock name='SSHClient' id='139650132358312'>

    @patch('paramiko.SSHClient')
    def test_ftp_fetch(mock_ssh):
        test_content = '{"date": "06/02/2020", "time": "07:55", "floors":[{"floor": "地面", "capacity": 149, "occupancy": "20"},{"floor": "قبو", "capacity": 184, "occupancy": "20"}]}'
        mock_ssh.open_sftp().file().read().return_string = test_content
        foo = PreProcessor(code="foo")
        response = foo.ftp_fetch()
        assert response == False
>       response = foo.ftp_fetch(hostname='http://foo/', username='foo', password = 'bar', file_name = 'baz')

preprocessors/test_preprocessors.py:339: 
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 
preprocessors/preprocessors.py:229: in ftp_fetch
    sftp.file(file_name).read()
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 

s = <MagicMock name='SSHClient().open_sftp().file().read()' id='139650131723376'>, encoding = None, cls = None, object_hook = None, parse_float = None
parse_int = None, parse_constant = None, object_pairs_hook = None, kw = {}
<< snip lots of doc text >>
        if isinstance(s, str):
            if s.startswith('\ufeff'):
                raise JSONDecodeError("Unexpected UTF-8 BOM (decode using utf-8-sig)",
                                      s, 0)
        else:
            if not isinstance(s, (bytes, bytearray)):
                raise TypeError('the JSON object must be str, bytes or bytearray, '
>                               'not {!r}'.format(s.__class__.__name__))
E               TypeError: the JSON object must be str, bytes or bytearray, not 'MagicMock'

/usr/lib/python3.6/json/__init__.py:348: TypeError

所以我的问题很简单:

如何设置模拟,以便sftp返回定义的文本?(我使用python 3.6 & pytest)

(是的,我总是尝试用高阶unicode文本进行测试,即使我不希望它在正常使用中))

EN

Stack Overflow用户

发布于 2020-02-25 08:17:43

为了更好的mocking.

  • Example:

  • 使用MonkeyPatch

代码语言:javascript
复制
def test_user_details(monkeypatch):
        mommy.make('Hallpass', user=user)
        return_data = 
            {
            'user_created':'done'
            }
        monkeypatch.setattr(
            'user.create_user', lambda *args, **kwargs: return_data)
        user_1 = create_user(user="+123456789")
        assert user_1.return_data == return_data

将monkeypatch作为参数传递给测试,并在测试中传递您希望在monkeypatch函数上使用所需的返回数据的所需方法。

确保安装猴子补丁pip install monkeypatch

票数 0
EN
查看全部 1 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60378228

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档