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')
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.
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.
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')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With