<br><br><div class="gmail_quote">On Sat, Feb 18, 2012 at 11:23 PM, Michael Foord <span dir="ltr"><<a href="mailto:michael@voidspace.org.uk">michael@voidspace.org.uk</a>></span> wrote:<br><blockquote class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex">
<div><div></div><div class="h5"><br>
On 18 Feb 2012, at 12:50, Sylvain Hellegouarch wrote:<br>
<br>
> Hi all,<br>
><br>
> 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.<br>
><br>
> 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.<br>
><br>
> Here's a snippet of something I'd like, more or less:<br>
><br>
> # -*- coding: utf-8 -*-<br>
> import socket<br>
> import unittest<br>
><br>
> from ws4py.websocket import WebSocket<br>
><br>
> class TestWebSocket(unittest.TestCase):<br>
> def setUp(self):<br>
> self.sock = MOCK_SOCKET_SOMEHOW(socket.socket)<br>
> <a href="http://self.ws" target="_blank">self.ws</a> = WebSocket(self.sock, None, None)<br>
><br>
> def tearDown(self):<br>
> self.sock.close()<br>
> self.sock = None<br>
><br>
> class TestFraming(TestWebSocket):<br>
> def test_case_1_1_1(self):<br>
> # Pretend next is a valid frame<br>
> bytes = "..."<br>
><br>
> # Need to replace recv so that it reads from bytes above<br>
> self.sock.recv = ...<br>
> # Run is a blocking method that blocks on recv()<br>
> self.sock.run()<br>
><br>
<br>
<br>
<br>
</div></div>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.<br>
<br>
In your last line do you mean "self.ws.run()"? It doesn't look like socket objects have a run method.<br>
<br>
<br>
Using mock you could do:<br>
<br>
from mock import MagicMock<br>
<br>
self.sock = MagicMock(name='socket', spec=socket.socket)<br>
<br>
<br>
Then later:<br>
<br>
self.sock.recv.return_value = bytes<br>
<br>
<br>
Hope that helps,<br><br></blockquote><div><br></div><div><br></div><div>Thanks Michael. definitely does give me something to munch on. I'll report back once I have found the right balance. </div></div><div><br></div>
-- <br>- Sylvain<br><a href="http://www.defuze.org">http://www.defuze.org</a><br><a href="http://twitter.com/lawouach">http://twitter.com/lawouach</a><br>