# file: cisco_driver.py
class myClass:
def __init__(self, run_commands):
self.run_commands = run_commands
def myFunction(self, interface_name):
command = f"show interface status {interface_name}"
output = self.run_commands(command)
return output
- 函数
myFunction
以接口名作为输入,例如:myFunction("Gig1/1/1")
- 然后生成一个命令,在本例中为:
show interface status Gig1/1/1
- 然后使用
run_commands
SSH到设备,执行命令,并检索其输出
为了进行pytest测试,我想测试生成的命令,且不该命令的执行。我想绕过run_commands
并返回命令本身,而不是它的输出。
我怎样才能做到这一点?这可能吗?我能嘲笑一下吗?Monkeypatch吗?
我想让它像这样运行:
def myFunction(interface_name):
command = f"show interface status {interface_name}"
return command
我玩了一下,找到了一个解决方案:
# pytest_file
def test_case():
# Initialize new instance of class
# Use None since "run_commands" will be bypassed
new_instance = myClass(None)
# New function that will replace the existing run_commands function
def mock_run_commands(command)
# Original behavior of run_commands is to create an SSH connection
# Instead, I want it to return the same command
return command
# Redefine run_commands to my customized function
new_instance.run_commands = mock_run_commands
# Pass param through class method
# This will return "show interface status Gig1/1/1"
selected_command = new_instance.myFunction("Gig1/1/1")
# Compare the command produced by class method with what expected outcome
assert selected_command == expected_command