如何使用pytest在paramiko SSHClient()中模拟“连接”

时间:2020-08-28 07:53:22

标签: python python-3.x pytest paramiko

我的util类是这样的。

class SSHUtils(object):
    def __init__(self, host, user=None, pwd=None):
        try:
            self.host = host
            logging.info(" Creating SSH session - %s, user name - %s & pswd - %s ", host, user, pwd)
            self.ssh = paramiko.SSHClient()
            self.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
            if user and pwd:
                self.ssh.connect(host, 22, user, pwd, timeout=10)
            else:
                self.ssh.connect(host, 22, timeout=10)

            transport = self.ssh.get_transport()
            transport.set_keepalive(30)
            channel = self.ssh.invoke_shell()  # nosec

            self.stdin = channel.makefile('wb')
            self.stdout = channel.makefile('r')

            logging.info(" Created SSH session - %s", host)
        except Exception as error:
            logging.error("Failed to create SSH sesssion to server - %s, %s", host, error)
            raise Exception("Failed to create SSH sesssion to server - " + host + " exception - " + str(error))

    def __del__(self):
        try:
            logging.info(" Delete SSH session - %s", self.host)
            self.ssh.close()
        except Exception as error:
            logging.info(" Exception while Delete SSH session - %s", self.host)

我尝试使用此灯具来模拟此类。

@pytest.fixture
def get_util_client(*args, **kwargs):
    ssh = SSHUtils("130b:tde9:5043:5000::4", "b", "c")
    return ssh

但是当我试图在测试功能中使用它时,出现了波纹管错误。

Exception: Failed to create SSH sesssion to server - 130b:tde9:5043:5000::4 exception - [Errno None] Unable to connect to port 22 on 130b:tde9:5043:5000::4

我的问题是如何在pytest中模拟SSHUtils类?

1 个答案:

答案 0 :(得分:1)

当前,get_util_client中没有模拟事件,因为您只是实例化实际的SSHUtils对象。您将需要使用pytest-mock或python的内置mock模块(mock.patch装饰器或方法)。

在使用SSHUtils作为其组成部分的更高级别的类上可能也需要进行模拟,因为SSHUtils似乎是一个实现类?

相关链接:

Python's builtin mock module

pytest module's mock wrapper