Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
777 views
in Technique[技术] by (71.8m points)

unit testing - Mocking subprocess of a python script

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 -r-xr-xr-x 23 darwin wiff[972 chars]py ' != 'out'.

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

question from:https://stackoverflow.com/questions/65896824/mocking-subprocess-of-a-python-script

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...