[Tutor] Mocking with "mock" in unit testing
James Chapman
james at uplinkzero.com
Thu Jan 16 11:32:02 CET 2014
Hi all
I have a question regarding mocking in unit testing.
Let's assume I have the following class:
-------------------------------------------
import subprocess
class Pinger(object):
def ping_host(self, host_to_ping):
cmd_string = 'ping %s' % (host_to_ping)
cmd_args = cmd_string.split()
proc = subprocess.Popen(cmd_args, shell=True)
proc.wait()
if proc.returncode != 1:
raise Exception('Error code was: %d' % (proc.returncode))
-------------------------------------------
In my unittest I don't want to run the ping command, (It might not be
available on the build system) I merely want to check that a call to
subprocess.Popen is made and that the parameters are what I expect?
So far I have this, but it doesn't work and I suspect it's way off!!
-------------------------------------------
import mock
import unittest
from tutor_q import Pinger
class Test_Pinger(unittest.TestCase):
def test_ping_host(self):
pinger = Pinger()
assert pinger
subprocess = mock.Mock()
subprocess.Popen.return_value = 0
subprocess.assert_called_once_with(['ping','localhost'])
pinger.ping_host('127.0.0.1')
if __name__ == '__main__':
unittest.main()
-------------------------------------------
Can anyone point me in the right direction on how to mock up these
subprocess calls?
Thanks
James
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20140116/69345d21/attachment.html>
More information about the Tutor
mailing list