vendredi 7 février 2020

How to mock an object while python testing with PyTest?

during testing i need to mock an object. I am currently using Pytest and monkeypatch for mocking.

example function:

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 

My test of the function:

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

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

I need to somehow mock the process object and write my own string into process.stdout.readline. I am aware that i can mock single variables using monkeypatch.setattr, but i don't know how to mock objects or even objects that inherit from other classes. Is there a way to tell my mock to return a dummy data structure with a "process.stdout.readline" accessible?

Aucun commentaire:

Enregistrer un commentaire