如何使用pytest模拟类属性

Shirantha Madusanka:

我上课是这样的。

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”的自我属性时,

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'?

yedpodtrzitko:

没有属性,你设置stdout为一个实例变量。即使您要模拟它,也要在构造函数(self.stdout = self.channel.makefile('r')中将其覆盖创建包装器/属性,然后猴子包装:

class Upgrade:
    def __init__(self, ssh_client):
        self._stdout = self.channel.makefile('r')

    def get_stdout(self):
        return self._stdout

然后在测试模拟中使用封装方法:

monkeypatch.setattr(Upgrade, 'get_stdout', return_stdout)

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章