'Test TCP socket exceptions in pytest

I have a method that created a TCP_socket and then connects it to a port. In my method I have used try/exception blocks to be able to log the thrown exception and then I have raised the exception intentionally. Now I want to test the exceptions are caught and raised correctly. In my test I try to mock the socket and raise the exceptions and then assert the socket.close() is called once but my test fails. I have googled a lot but could not find any scenario that is similar to my case. Can someone please help me how I can do this test?

Here is my code:

def create_connect_tcp_socket(self):
    try:
        tcp_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        tcp_socket.connect(('', self._socket_port)) 
        return tcp_socket
    except TimeoutError:
            tcp_socket.close()
            rlog.critical('Socket timeout! Raise {} exception!'.format(TimeoutError))
            raise TimeoutError
     except ConnectionRefusedError as conn_err:
            tcp_socket.close()
            rlog.critical('Connection Refused!!!! {}.'.format(conn_err))
            rlog.critical('Raise {} exception!'.format(ConnectionRefusedError))
            raise ConnectionRefusedError

My test:

@unittest.mock.patch('socket.socket', autospec=True)
def test_create_connect_tcp_socket(self, mock_socket):
    mock_socket.side_effect = TimeoutError
    with pytest.raises(TimeoutError):
        mock_socket.close().assert_called_once()

Thanks



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source