[TIP] Mocking a socket object
Sylvain Hellegouarch
sh at defuze.org
Mon Feb 20 01:21:03 PST 2012
On Sat, Feb 18, 2012 at 11:23 PM, Michael Foord <michael at voidspace.org.uk>wrote:
>
> On 18 Feb 2012, at 12:50, Sylvain Hellegouarch wrote:
>
> > Hi all,
> >
> > In the process of adding more coverage to WebSocket For Python [1], I
> was looking at creating a mock of a socket class. The idea would then be to
> write a bunch of mocks that would simply hand me bytes at the pace I need
> whenever I call the recv(size) method on the mocked socket.
> >
> > I'm not familiar enough with the complexity of mocking a built-in object
> like socket and I'm welcoming ideas or tools to achieve this.
> >
> > Here's a snippet of something I'd like, more or less:
> >
> > # -*- coding: utf-8 -*-
> > import socket
> > import unittest
> >
> > from ws4py.websocket import WebSocket
> >
> > class TestWebSocket(unittest.TestCase):
> > def setUp(self):
> > self.sock = MOCK_SOCKET_SOMEHOW(socket.socket)
> > self.ws = WebSocket(self.sock, None, None)
> >
> > def tearDown(self):
> > self.sock.close()
> > self.sock = None
> >
> > class TestFraming(TestWebSocket):
> > def test_case_1_1_1(self):
> > # Pretend next is a valid frame
> > bytes = "..."
> >
> > # Need to replace recv so that it reads from bytes above
> > self.sock.recv = ...
> > # Run is a blocking method that blocks on recv()
> > self.sock.run()
> >
>
>
>
> There are quite a few different approaches that are possible, depending on
> precisely what WebSocket does with the socket object. In general it *looks*
> like a mock object that has the socket api but isn't a real socket will do
> fine.
>
> In your last line do you mean "self.ws.run()"? It doesn't look like socket
> objects have a run method.
>
>
> Using mock you could do:
>
> from mock import MagicMock
>
> self.sock = MagicMock(name='socket', spec=socket.socket)
>
>
> Then later:
>
> self.sock.recv.return_value = bytes
>
>
> Hope that helps,
>
>
Thanks Michael. definitely does give me something to munch on. I'll report
back once I have found the right balance.
--
- Sylvain
http://www.defuze.org
http://twitter.com/lawouach
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.idyll.org/pipermail/testing-in-python/attachments/20120220/c507c9d1/attachment.html>
More information about the testing-in-python
mailing list