Skip to content Skip to sidebar Skip to footer

How To Mock A Socket Object Via The Mock Library

How to mock a TCPSocket wrapper for the socket from the Python's standard libary via the mock library (unittest.mock in case of Python 3)? This is my wrapper: import socket import

Solution 1:

It can be as simple as

import mock   # or from unittest import mock


mock_socket = mock.Mock()
mock_socket.recv.return_value = data

then use mock_socket where you would use the real socket. You can also mock whatever creates the socket to return a mock value like the one configured here, depending on your needs.


For your case, you can mock socket.socket so that it returns something whose method you can configure. Note that mock_socket in this example is a function that returns a Socket object, not a Socket object itself.

with mock.patch('socket.socket') as mock_socket:
    mock_socket.return_value.recv.return_value = some_data
    t = TCPSocket()
    t.connect('example.com', 12345)  # t.sock is a mock object, not a Socket
self.assertEqual(t.recv_bytes(), whatever_you_expect)
t.sock.connect.assert_called_with(('example.com', 12345))

Post a Comment for "How To Mock A Socket Object Via The Mock Library"