如何解决如何使用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
似乎是一个实现类?
相关链接:
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。