Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mocking a socket connection in Python

I am trying to write unit tests for a class in python. The class opens a tcp socket on init. I am trying to mock this out so that I can assert that connecting is called with the correct values but obviously doesn't actually happen in unit tests. I have tired MagicMock, patch, etc but I have not found a solution.

My class so far looks like this

import socket

class MyClass(object):

    def __init__(self):
        self.tcp_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.tcp_socket.connect('0.0.0.0', '6767')
like image 939
CountCet Avatar asked Aug 06 '15 19:08

CountCet


People also ask

What is mocking in Python?

mock is a library for testing in Python. It allows you to replace parts of your system under test with mock objects and make assertions about how they have been used. unittest. mock provides a core Mock class removing the need to create a host of stubs throughout your test suite.

What does mock mock () do?

mock provides a powerful mechanism for mocking objects, called patch() , which looks up an object in a given module and replaces that object with a Mock . Usually, you use patch() as a decorator or a context manager to provide a scope in which you will mock the target object.


1 Answers

If you just want to assert that connect is called correctly, it's a simple as

import mock
import socket

class MyClass(object):

    def __init__(self):
        self.tcp_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.tcp_socket.connect('0.0.0.0', '6767')

with mock.patch('socket.socket'):
    c = MyClass()
    c.tcp_socket.connect.assert_called_with('0.0.0.0', '6767')

If you have to import a module first to access MyClass, you'll need to adjust the patch slightly:

from mymodule import MyClass
import mock

with mock.patch('mymodule.socket.socket'):
    c = MyClass()
    c.tcp_socket.connect.assert_called_with('0.0.0.0', '6767')
like image 119
chepner Avatar answered Oct 05 '22 02:10

chepner