How to mock a socket object via the mock library
<p>How to mock a <code>TCPSocket</code> wrapper for the <code>socket</code> from the Python's standard libary via the <a href="https://github.com/testing-cabal/mock" rel="nofollow">mock</a> library (<code>unittest.mock</code> in case of Python 3)?</p>

<p>This is my wrapper:</p>

<pre><code>import socket

import utils


class TCPSocket:
    def __init__(self):
        self.buf = ''

    def __enter__(self):
        pass

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.close()

    def connect(self, host, port):
        self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.sock.connect((host, port))

    def close(self):
        self.sock.close()

    def send(self, data):
        self.sock.send(data)

    def sendall(self, data):
        self.sock.sendall(data)

    # For best match with hardware and network realities,
    # the value of limit should be a relatively small power of 2, for example, 4096
    def recv_some(self, limit=4096):
        return self.sock.recv(limit)

    def recv_bytes(self, count):
        while len(self.buf) &lt; count:
            self.buf += self.recv_some()
        parts = utils.split_first_n(self.buf, count)
        self.buf = parts[1]
        return parts[0]

    def recv_until(self, delim):
        while delim not in self.buf:
            self.buf += self.recv_some()
        parts = self.buf.split(delim, maxsplit=1)
        self.buf = parts[1]
        return parts[0]
</code></pre>

<p>I want to test whether functions like recv_until and recv_bytes do what they really need.</p>