[TIP] Mocking a socket object

Michael Foord michael at voidspace.org.uk
Sat Feb 18 14:23:42 PST 2012

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,


> Cheers,
> -- 
> - Sylvain
> http://www.defuze.org
> http://twitter.com/lawouach
> [1] https://github.com/Lawouach/WebSocket-for-Python
> _______________________________________________
> testing-in-python mailing list
> testing-in-python at lists.idyll.org
> http://lists.idyll.org/listinfo/testing-in-python


May you do good and not evil
May you find forgiveness for yourself and forgive others
May you share freely, never taking more than you give.
-- the sqlite blessing 

More information about the testing-in-python mailing list