How to mock an object that is created during function call? - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: How to mock an object that is created during function call? (/thread-24112.html) |
How to mock an object that is created during function call? - Schlangenversteher - Jan-31-2020 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 isVersionedI 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. |