0

I have a simple python script so.py that runs a subprocess command:

from subprocess import Popen, PIPE, STDOUT

def commandRunner(command):
    process = Popen(command, stdout=PIPE, stderr=PIPE)
    out, err = process.communicate()
    if (err):
        print("there was an error", err)
        exit()
    return out

def main():
    command = "ls -la"
    res = commandRunner(command.split())
    print(res)

if __name__ == '__main__':
    main()

and in my test file test_so.py (adapted from here):

import unittest
from unittest.mock import patch
from so import *
from unittest import mock

class SOTest(unittest.TestCase):
    @patch('so.subprocess.Popen')
    def test_commandRunner(self,mock_cmd):
        process_mock = mock.Mock()
        attrs = {'communicate.return_value': ('out', '')}
        process_mock.configure_mock(**attrs)
        mock_cmd.return_value = process_mock
        command = 'test this out'
        self.assertEqual(commandRunner(command.split()),'out')

if __name__ == '__main__':
    unittest.main()

I get the error ModuleNotFoundError: No module named 'so.subprocess'; 'so' is not a package.

If I instead use @patch('subprocess.Popen') it actually tries to run the command: AssertionError: b'total 164\n-r-xr-xr-x 23 darwin wiff[972 chars]py\n' != 'out'.

How do I unit test this script? All the other answers seem to have python packages instead.

user2883071
  • 960
  • 1
  • 20
  • 50
  • 1
    As you do `from subprocess import Popen`, you have to patch this reference, e.g. `@patch('so.Popen')`, see [where to patch](https://docs.python.org/3/library/unittest.mock.html#id6). – MrBean Bremen Jan 26 '21 at 06:44
  • This was it, why is this the case? anything I can read about? (If you like, make it an answer and ill select it) – user2883071 Jan 26 '21 at 14:48
  • Did you read the documentation I linked in the comment? There are also existing issues where this is explained - for example I answered a related question [here](https://stackoverflow.com/a/62625882/12480730), or check the links in [this answer](https://stackoverflow.com/a/63690318/12480730). – MrBean Bremen Jan 26 '21 at 15:50

0 Answers0