小编Chr*_*ell的帖子

用 Python 模拟远程主机

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

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)
Run Code Online (Sandbox Code Playgroud)

看过 paramiko …

python unit-testing mocking remote-server paramiko

4
推荐指数
2
解决办法
6274
查看次数

标签 统计

mocking ×1

paramiko ×1

python ×1

remote-server ×1

unit-testing ×1