Python Forum

Full Version: How to mock an object that is created during function call?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello,

i tried to create a python test for a subprocess call. Below i created a minimalistic example.

# myModule.py
import subprocess

def isScriptVersioned():
    isVersioned = False
    command = ["svn", "info"]
    process = subprocess.Popen(command, bufsize=1, universal_newlines=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
        for line in iter(process.stdout.readline, ''):
            # Extract path by parsing the svn output vis regex
            if(re.search(r'URL: (\S*)', line)):
                isVersioned = True
    return isVersioned   
I would like to mock the process.stdout.readline string but i have no idea how to access this variable. Here are some things i tried:

# my test module
def mockreturn():
    return "//my//path//Application"

# 1. try
def test_isScriptVersioned(monkeypatch):
    monkeypatch.setattr(subprocess.Popen.stdout.readline, "//my//path//Application")
    assert utilities.isScriptVersioned() == "True"

# 2. try
def test_isScriptVersioned(monkeypatch):
    monkeypatch.setattr(subprocess.Popen.stdout, "readline", mockreturn)
    assert utilities.isScriptVersioned() == "True"

# 3. try
def test_isScriptVersioned(monkeypatch):
    monkeypatch.setattr(process.stdout.readline, "//my//path//Application")
    assert utilities.isScriptVersioned() == "True"
I think at this points its clear that i am just doing try and error and looking for some explanation on whats going on here and how to solve it.