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')
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…