python - mocking subprocess Process terminate -
i couldn't find question one. i'm having difficulty understanding how mock out returned value of subprocess.popen can validate terminate called when try stop it. server.py class looks this:
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()
my test class looks this. want know terminate called when stop called when run test nose says terminate called 0 times. understanding of patch replaces implementation of subprocess.popen , available methods.
from unittest import testcase server import server 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()
you need mock popen
that's used code you're testing. patch path be:
@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()
however, terminate
called on return value of subprocess.popen()
need become:
mock_subprocess.return_value.terminate.assert_called_once_with()
Comments
Post a Comment