Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/297.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 模拟子进程进程终止_Python_Unit Testing - Fatal编程技术网

Python 模拟子进程进程终止

Python 模拟子进程进程终止,python,unit-testing,Python,Unit Testing,我找不到一个和这个完全一样的问题。我很难理解如何模拟subprocess.Popen的返回值,以便在尝试停止时验证terminate是否被调用。server.py类如下所示: import os import subprocess class Server(object): def start(self): devnull = open(os.devnull, 'w') self.proc = subprocess.Popen(['python', '

我找不到一个和这个完全一样的问题。我很难理解如何模拟subprocess.Popen的返回值,以便在尝试停止时验证terminate是否被调用。server.py类如下所示:

import os
import subprocess

class Server(object):

    def start(self):
        devnull = open(os.devnull, 'w')
        self.proc = subprocess.Popen(['python', '-c', 'import time; time.sleep(10);print "This message should not appear"'], stdout=devnull, stderr=devnull)

    def stop(self):
        if self.proc:
            self.proc.terminate()
我的测试课是这样的。我想知道调用stop时调用了terminate,但是当我使用nose运行测试时,它说terminate被调用了0次。我对补丁的理解是,它取代了subprocess.Popen和所有可用方法的实现

from unittest import TestCase
from server import Server
from mock import patch, MagicMock, Mock

class ServerTest(TestCase):

    @patch("subprocess.Popen")
    @patch('__builtin__.open')
    def test_stop_when_running(self, mock_open, mock_subprocess):
        server = Server()
        server.start()
        server.stop()
        mock_subprocess.terminate.assert_called_once_with()

您需要模拟正在测试的代码实际使用的
Popen
。因此,修补程序路径为:

@patch("server.subprocess.Popen")
@patch('server.__builtin__.open')
def test_stop_when_running(self, mock_open, mock_subprocess):
    server = Server()
    server.start()
    server.stop()
    mock_subprocess.terminate.assert_called_once_with()
但是,对
subprocess.Popen()
的返回值调用
terminate
,因此它需要变成:

mock_subprocess.return_value.terminate.assert_called_once_with()
试试这个:

server.proc.terminate.assert\u用()调用一次