diff --git a/greenswitch/esl.py b/greenswitch/esl.py index 6c25f29..9f9bdaf 100644 --- a/greenswitch/esl.py +++ b/greenswitch/esl.py @@ -359,7 +359,12 @@ def connect(self): if self._outbound_connected: return self.session_data - resp = self.send('connect') + try: + resp = self.send('connect') + except OutboundSessionHasGoneAway as e: + # cleanup before raising exception + self.stop() + raise e self.session_data = resp.headers self._outbound_connected = True diff --git a/tests/test_outbound_session.py b/tests/test_outbound_session.py index 69205b3..dc5a863 100644 --- a/tests/test_outbound_session.py +++ b/tests/test_outbound_session.py @@ -25,6 +25,23 @@ def test_outbound_connected_is_updated_during_on_hangup_event(self): with self.assertRaises(esl.OutboundSessionHasGoneAway): self.outbound_session.raise_if_disconnected() + def test_raising_OutboundSessionHasGoneAway_in_session_connect_will_call_sock_close(self): + # Here we are socket connected, but not freeswitch connected + # So any exception raised in session.connect should call sock.close + self.outbound_session.connected = False + + # make outbound_session.send raise OutboundSessionHasGoneAway + self.outbound_session.send = mock.MagicMock(side_effect=esl.OutboundSessionHasGoneAway) + + # mock sock.close + self.outbound_session.sock.close = mock.MagicMock() + + # attempt to connect and assert sock.close is called + with self.assertRaises(esl.OutboundSessionHasGoneAway): + self.outbound_session.connect() + + assert self.outbound_session.sock.close.called + @pytest.mark.usefixtures("outbound_session") @pytest.mark.usefixtures("disconnect_event")