在Python中模拟远程主机 [英] Mock a Remote Host in Python

查看:93
本文介绍了在Python中模拟远程主机的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用paramiko编写一些函数,以执行命令并在远程主机上创建文件.我想为他们编写一些单元测试,但是我不知道实现这一目标的最简单方法是什么?这是我设想的代码示例示例:

I am writing some functions, using paramiko, to execute commands and create files on a remote host. I would like to write some unit tests for them, but I don't know what would be the simplest way to achieve this? This is what I envisage as being an example outline of my code:

import os
import paramiko
import pytest

def my_function(hostname, relpath='.', **kwargs):
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ssh.connect(hostname, **kwargs)
    sftp = ssh.open_sftp()
    sftp.chdir(relpath)
    stdin, stdout, stderr = ssh.exec_command("echo hallo > test.txt")

@pytest.fixture("module")
def mock_remote_host():
    # start a remote host here with a local test path
    try:
        yield hostname, testpath, {"username":"bob", "password":"1234"}
    finally:
        # delete the test path
        # close the remote host

def test_my_function(mock_remote_host):
    hostname, dirpath, kwargs = mock_remote_host
    my_function(hostname, **kwargs)
    filepath = os.path.join(dirpath, 'test.txt')
    assert os.path.exists(filepath)

我看过 paramiko测试模块,但对于我的用例而言,它们似乎相当复杂,我不确定如何简化它们.

I have had a look at the paramiko test modules, but they seem quite complex for my use case and I'm not sure how to go about simplifying them.

推荐答案

为回答我自己的问题,我创建了:

To answer my own question, I have created: https://github.com/chrisjsewell/atomic-hpc/tree/master/atomic_hpc/mockssh.

自述文件讨论过的内容;它基于 https://github.com/carletes/mock- ssh-server/tree/master/mockssh ,并基于 https进行了添加(以实现更多的sftp功能) ://github.com/rspivak/sftpserver

As the readme discusses; it is based on https://github.com/carletes/mock-ssh-server/tree/master/mockssh with additions made (to implement more sftp functions) based on https://github.com/rspivak/sftpserver

还进行了以下更改:

  • 修改后的users参数,以便可以使用private_path_key或密码
  • Server上下文管理器中添加了dirname参数,以便在上下文持续时间内将其设置为根路径.
  • 修补了paramiko.sftp_client.SFTPClient.chdir,以修复其在相对路径中的使用.
  • revised users parameter, such that either a private_path_key or password can be used
  • added a dirname parameter to the Server context manager, such that the this will be set as the root path for the duration of the context.
  • patched paramiko.sftp_client.SFTPClient.chdir to fix its use with relative paths.

有关用法,请参见test_mockssh.py.

See test_mockssh.py for example uses.

这篇关于在Python中模拟远程主机的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆