0

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)
Ryan
  • 219
  • 3
  • 12
  • 1
    Shouldn't it be `mymodule.transfer`? I mean, `mocker.patch('mymodule.transfer.Popen')` etc. – hoefling Jul 05 '18 at 13:26
  • You are right it is... But i have no idea why as in my `__init__.py` I have `from mymodule.transferfile import *` so I thought it would be in the shortform. If you could explain why / point me at an article that explains why I would appreciate it. – Ryan Jul 05 '18 at 13:53
  • 1
    Patching should always occur in the module where the patched mocks should be used; the [Where to patch](https://docs.python.org/3/library/unittest.mock.html#where-to-patch) section from stdlib docs explains this. – hoefling Jul 05 '18 at 15:44

0 Answers0