首页 > 解决方案 > python - 使用PyTest进行python测试时如何模拟对象?

问题描述

在测试期间,我需要模拟一个对象。我目前正在使用 Pytest 和 monkeypatch 进行模拟。

示例函数:

def isGccInstalled():
    gccInstallationFound = False
    command = ['gcc', '-v']
    process = subprocess.Popen(command, bufsize=1, universal_newlines=True, 
                               stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
    if process.stdout.readline:
        gccInstallationFound = True        
    return gccInstallationFound 

我对该功能的测试:

def mock_subprocess_Popen(*args, **kwargs):
    return

def test_getSwBlockType(monkeypatch):
    monkeypatch.setattr(subprocess, "Popen", mock_subprocess_Popen)
    assert isGccInstalled() == "False"

我需要以某种方式模拟流程对象并将我自己的字符串写入 process.stdout.readline。我知道我可以使用 monkeypatch.setattr 模拟单个变量,但我不知道如何模拟对象甚至是从其他类继承的对象。有没有办法告诉我的模拟返回一个可以访问“process.stdout.readline”的虚拟数据结构?

标签: pythontestingmockingpytest

解决方案


推荐阅读