我正在设计测试用例,其中我使用paramiko进行SSH连接.测试用例通常包含paramiko.exec_command()我有一个包装器(调用run_command())的调用.这self.ssh是一个问题paramiko.SSHClient().我在每次调用之前使用装饰器来检查ssh连接.(self.get_ssh()协商连接)
def check_connections(function):
''' A decorator to check SSH connections. '''
def deco(self, *args, **kwargs):
if self.ssh is None:
self.ssh = self.get_ssh()
else:
ret = getattr(self.ssh.get_transport(), 'is_active', None)
if ret is None or (ret is not None and not ret()):
self.ssh = self.get_ssh()
return function(self, *args, **kwargs)
return deco
Run Code Online (Sandbox Code Playgroud)
@check_connections
def run_command(self, command):
''' Executes command via SSH. '''
stdin, stdout, stderr = self.ssh.exec_command(command)
stdin.flush()
stdin.channel.shutdown_write()
ret = stdout.read()
err …Run Code Online (Sandbox Code Playgroud) 我想使用一个接受一个参数的装饰器,检查该参数是否为None,如果是True则让装饰函数运行.
我想在类定义中使用这个装饰器,因为我有一组类方法,它们首先检查特定的类变量是否为None.我认为如果我使用装饰器会更好看.
我想做这样的事情:
# decorator
def variable_tester(arg):
def wrap(f):
def wrapped_f(*args):
if arg is not None:
f(*args)
else:
pass
return wrapped_f
return wrap
# class definition
class my_class(object):
def __init__(self):
self.var = None
@variable_tester(self.var) # This is wrong. How to pass self.var to decorator?
def printout(self):
print self.var
def setvar(self, v):
self.var = v
# testing code
my_instance = my_class()
my_instance.printout() # It should print nothing
my_instance.setvar('foobar')
my_instance.printout() # It should print foobar
Run Code Online (Sandbox Code Playgroud)