python - mocking subprocess.Popen dependant on import style -
when attempting mock popen can succeed if importing of subprocess matches in both unit test code , main module code.
given following module listdir.py:
from subprocess import popen, pipe def listdir(dir): cmd = ['ls', dir] pc = popen(cmd, stdout=pipe, stderr=pipe) out, err = pc.communicate() if pc.returncode != 0: raise exception return out
and following unit test code test_listdir.py
import subprocess import listdir import mock @mock.patch.object(subprocess, 'popen', autospec=true) def test_listdir(mock_popen): mock_popen.return_value.returncode = 0 mock_popen.return_value.communicate.return_value = ("output", "error") listdir.listdir("/fake_dir")
for reason popen not being mocked, due import style being different between 2 python modules, , running test raises exception.
if change listdir.py import of subproces e.g.
import subprocess def listdir(dir): cmd = ['ls', dir] pc = subprocess.popen(cmd, stdout=subprocess.pipe, stderr=subprocess.pipe) out, err = pc.communicate() if pc.returncode != 0: raise listingerrorexception return out
then "output" returned in test.
anyone care shed light on why, preference have subprocess import popen, pipe in both modules, can't mock.
you need patch copy of popen in listdir, not 1 imported. so, instead of @mock.patch.object(subprocess, 'popen', autospec=true)
, try @mock.patch.object(listdir, 'popen', autospec=true)
see doc more info: http://www.voidspace.org.uk/python/mock/patch.html#where-to-patch
Comments
Post a Comment