问题描述
我的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
似乎是一个实现类?
相关链接: