各位版友好
本人目前想用Python的mock來測試subprocess.run()
看了一些網路資料,但還是試不出來
在common.py欲測試的function為check(),內容如下:
import subprocess
def check():
cmd = ["python3", "is_corrupted.py"]
process = subprocess.run(cmd, stderr=subprocess.PIPE, check=False)
if process.stderr:
return "str(process.stderr)"
elif process.returncode == 1:
return "corrupted"
return "pass"
本人在另一個檔案test.py用mock寫的測試函數為:
import unittest
import subprocess
from unittest import mock
from common import check
Class UT(unittest.TestCase):
@mock.patch(subprocess.run)
def test_check(self, mock_subprocess_run):
mock_rc = mock.MagicMock()
mock_subprocess_run.return_value = mock_rc
mock_rc.stderr.return_value = b'stderr message'
self.assertEqual(check(), "stderr message")
if __name__ == "__main__":
unittest.main()
得到以下錯誤:
======================================================================
FAIL: test_check (__main__.UT)