I need to be able to mock Popen, but none of the examples on stack overflow seem to be working for me. I tried the suggestions here but it keeps raising an exception:
Traceback (most recent call last):
File "/Users/me/workspace/workdir/src/mymodule/transferfile.py", line 23, in sftp
p = Popen(cmd, shell=False, stdin=PIPE, stdout=PIPE, stderr=PIPE)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py", line 710, in __init__
errread, errwrite)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py", line 1335, in _execute_child
raise child_exception
E OSError: [Errno 9] Bad file descriptor
File: mymodule/transfer.py:
from subprocess import PIPE, Popen
def sftp(cmdstr):
cmd = ["sftp", "-b", "-", "stfp_server"]
p = Popen(cmd, shell=False, stdin=PIPE, stdout=PIPE, stderr=PIPE)
if p.returncode is None:
stdout, stderr = p.communicate(cmdstr)
test file:
def test_sftp(mocker):
# Attempt 1
mocker.patch('mymodule.Popen.communicate', autospec=True)
mocker.patch('mymodule.Popen', autospec=True)
mocker.patch('mymodule.PIPE', autospec=True)
# Attempt 2
mocker.patch('subprocess.Popen.communicate', autospec=True)
mocker.patch('subprocess.Popen', autospec=True)
mocker.patch('subprocess.PIPE', autospec=True)
cmdstr = "ls"
mymodule.sftp(cmdstr)