如何在使用 python 命令执行脚本时模拟 python 脚本中的函数

Cur*_*hie 6 python subprocess mocking python-unittest

我正在尝试使用子进程(Python27)通过 python 命令测试 python 脚本。当我这样测试时,有没有办法模拟脚本中使用的函数?

例如,

示例.py

import example1

if __name__ == '__main__':
   result = example1.testfunction()
   print result

Run Code Online (Sandbox Code Playgroud)

示例1.py

def testfunction():
   print "testing"
   return True

Run Code Online (Sandbox Code Playgroud)

我想测试example.py像这样的脚本 test_example.py

import unittest
import subprocess
import mock
from mock import patch


class Example(unittest.TestCase):

    @patch('example1.testfunction')
    def test_example_script(self, mock_testfunction):
        mock_testfunction.returnvalue = False
        cmd = ["python", "example.py"]
        task = subprocess.Popen(cmd)
        stdout, stderr = task.communicate()
        print stdout
        self.assertFalse(stdout)

Run Code Online (Sandbox Code Playgroud)

基本上,该补丁在我的代码中不起作用,我得到的输出是

True
AssertionError: True is not false

Run Code Online (Sandbox Code Playgroud)

有没有办法模拟testfunction()in example1.py

我可以强制testfunction()返回False以便我的输出是吗False