[TIP] Mocking a socket object

Sylvain Hellegouarch sh at defuze.org
Sat Feb 18 04:50:53 PST 2012


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()


Cheers,
-- 
- Sylvain
http://www.defuze.org
http://twitter.com/lawouach

[1] https://github.com/Lawouach/WebSocket-for-Python
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.idyll.org/pipermail/testing-in-python/attachments/20120218/8e3c6b2b/attachment.html>


More information about the testing-in-python mailing list