如何使用 pytest 模拟 class 属性

How to mock class attributes using pytest

我有一个 class 类似的东西。

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

当我尝试像这样模拟名为 'stdout' 的自我属性时(使用 pytest),

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 没有属性,您正在将 stdout 设置为 实例 变量.即使你模拟它,你也会在构造函数中覆盖它 (self.stdout = self.channel.makefile('r'))。创建一个 wrapper/property,然后用 monkeypatch 代替:

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)