mocking a socket connection in Python

后端 未结 1 927
有刺的猬
有刺的猬 2020-12-20 15:23

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 connecti

相关标签:
1条回答
  • 2020-12-20 15:56

    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')
    
    0 讨论(0)
提交回复
热议问题