如何在python使用PyTest进行测试时模拟对象?

2024-09-28 01:25:55 发布

您现在位置: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对象,并将自己的字符串写入process.stdout.readline。 我知道我可以使用monkeypatch.setattr模拟单个变量,但我不知道如何模拟对象,甚至是从其他类继承的对象。有没有办法告诉我的mock返回一个可以访问“process.stdout.readline”的虚拟数据结构


Tags: 对象falsetruereadlinereturndefstdoutprocess

热门问题