我需要能够模拟Popen,但是堆栈溢出的所有示例似乎都不适合我。我尝试了建议here,但它不断引发异常:
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
文件: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)
测试文件:
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)