【发布时间】:2020-12-20 03:24:22
【问题描述】:
我有一个类似的课程。
class Upgrade:
def __init__(self, ssh_client):
self.ssh_client = ssh_client
self.channel = self.ssh_client.invoke_shell(width=1000, height=1000)
self.stdin = self.channel.makefile('wb')
self.stdout = self.channel.makefile('r')
def do_upgrade(self):
# execute some commands on paramiko channel
for line in self.stdout:
if str(line).startswith("PLAY RECAP"):
# do something
当我尝试像这样(使用 pytest)模拟名为“stdout”的 self 属性时,
def return_stdout(*args, **kwargs):
stdout = "\n\rSome return value\n\r"
return stdout
monkeypatch.setattr(Upgrade, 'stdout', return_stdout)
我收到以下错误。
> monkeypatch.setattr(Upgrade, 'stdout', return_stdout)
E AttributeError: <class 'Upgrade'> has no attribute 'stdout'
那么,如何使用 pytest 或 pytest-mock 模拟“stdout”?
【问题讨论】:
-
class 没有该属性,您将
a设置为 instance 变量。如果您想为该类模拟它,请先在此处声明它(class MyClass: \n a = None \n def __init__(...,但是构造函数稍后将覆盖该值。您要实现什么目标? -
其实我需要测试do_upgrade函数。类升级: def __init__(self, ssh_client): self.ssh_client = ssh_client self.channel = self.ssh_client.invoke_shell(width=1000, height=1000) self.stdin = self.channel.makefile('wb') self. stdout = self.channel.makefile('r') def do_upgrade(self): for line in self.stdout: logging.info(str(line)) if str(line).startswith("PLAY RECAP"): # do某事
-
请将代码添加到可以格式化/高亮显示的原始问题中,而不是这样。
-
问题已更新
标签: python python-3.x pytest pytest-mock