python脚本的模拟子进程

2024-10-06 13:44:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个简单的python脚本so.py,它运行一个子流程命令:

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()

在我的测试文件test_so.pyadapted 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()

我得到了错误ModuleNotFoundError: No module named 'so.subprocess'; 'so' is not a package

如果我改为使用@patch('subprocess.Popen'),它实际上会尝试运行以下命令: AssertionError: b'total 164\n-r-xr-xr-x 23 darwin wiff[972 chars]py\n' != 'out'

如何对这个脚本进行单元测试?所有其他答案似乎都有python包


Tags: frompyimportsomaindefunittestout