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

问题描述

我的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 ",user,pwd)
            self.ssh = paramiko.SSHClient()
            self.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
            if user and pwd:
                self.ssh.connect(host,22,pwd,timeout=10)
            else:
                self.ssh.connect(host,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",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类?

解决方法

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

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

相关链接:

Python's builtin mock module

pytest module's mock wrapper

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...