【问题标题】:How to mock class attributes using pytest如何使用 pytest 模拟类属性
【发布时间】: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


【解决方案1】:

class 没有该属性,您将 stdout 设置为 instance 变量。即使你模拟它,你也会在构造函数中覆盖它(self.stdout = self.channel.makefile('r'))。创建一个包装器/属性,然后用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)

【讨论】:

    猜你喜欢
    • 2011-01-31
    • 1970-01-01
    • 2018-12-12
    • 2021-01-07
    • 1970-01-01
    • 2021-11-11
    • 2020-03-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多