diff --git a/minecraft/networking/connection.py b/minecraft/networking/connection.py index d35af8c..a5b7482 100644 --- a/minecraft/networking/connection.py +++ b/minecraft/networking/connection.py @@ -57,6 +57,7 @@ class Connection(object): initial_version=None, allowed_versions=None, handle_exception=None, + handle_exit=None, ): """Sets up an instance of this object to be able to connect to a minecraft server. @@ -90,6 +91,11 @@ class Connection(object): will terminate, the exception will be available via the 'exception' and 'exc_info' attributes of the 'Connection' instance. + :param handle_exit: A function to be called when a connection to a + server terminates, not caused by an exception, + and not with the intention to automatically + reconnect. Exceptions raised in this handler + will be handled by handle_exception. """ # NOQA # This lock is re-entrant because it may be acquired in a re-entrant @@ -132,9 +138,11 @@ class Connection(object): self.options.port = port self.auth_token = auth_token self.username = username + self.connected = False self.handle_exception = handle_exception self.exception, self.exc_info = None, None + self.handle_exit = handle_exit # The reactor handles all the default responses to packets, # it should be changed per networking state @@ -323,9 +331,12 @@ class Connection(object): self.socket = socket.socket(ai_faml, ai_type, ai_prot) self.socket.connect(ai_addr) self.file_object = self.socket.makefile("rb", 0) + self.connected = True def disconnect(self): """ Terminate the existing server connection, if there is one. """ + self.connected = False + with self._write_lock: # pylint: disable=not-context-manager if self.socket is not None: # Flush any packets remaining in the queue. @@ -336,18 +347,12 @@ class Connection(object): self.networking_thread.interrupt = True if self.socket is not None: - if hasattr(self.socket, 'actual_socket'): - # pylint: disable=no-member - actual_socket = self.socket.actual_socket - else: - actual_socket = self.socket - try: - actual_socket.shutdown(socket.SHUT_RDWR) + self.socket.shutdown(socket.SHUT_RDWR) except socket.error: pass finally: - actual_socket.close() + self.socket.close() self.socket = None def _handshake(self, next_state=STATE_PLAYING): @@ -360,21 +365,28 @@ class Connection(object): self.write_packet(handshake) def _handle_exception(self, exc, exc_info): + handle_exception = self.handle_exception + try: + if self.reactor.handle_exception(exc, exc_info): + return + if handle_exception not in (None, False): + self.handle_exception(exc, exc_info) + except BaseException as new_exc: + exc, exc_info = new_exc, sys.exc_info() + try: exc.exc_info = exc_info # For backward compatibility. except (TypeError, AttributeError): pass - if self.reactor.handle_exception(exc, exc_info): - return - - self.disconnect() - self.exception, self.exc_info = exc, exc_info - if self.handle_exception is None: + self.disconnect() + if handle_exception is None: raise_(*exc_info) - elif self.handle_exception is not False: - self.handle_exception(exc, exc_info) + + def _handle_exit(self): + if not self.connected and self.handle_exit is not None: + self.handle_exit() def _react(self, packet): try: @@ -405,6 +417,7 @@ class NetworkingThread(threading.Thread): self.previous_thread = None self.connection.networking_thread = self self._run() + self.connection._handle_exit() except BaseException as e: self.connection._handle_exception(e, sys.exc_info()) finally: diff --git a/tests/fake_server.py b/tests/fake_server.py index 0fe3720..f9338cc 100644 --- a/tests/fake_server.py +++ b/tests/fake_server.py @@ -395,6 +395,10 @@ class _FakeServerTest(unittest.TestCase): public_key_bytes = None # The serialised RSA public key used by the server: see 'FakeServer'. + ignore_extra_exceptions = False + # If True, any occurrence of the 'FakeServerTestSuccess' exception is + # considered a success, even if other exceptions are raised. + def _start_client(self, client): game_joined = [False] @@ -479,6 +483,8 @@ class _FakeServerTest(unittest.TestCase): if thread is not None and thread.is_alive(): errors.append({ 'msg': 'Thread "%s" timed out.' % thread.name}) + if client_exc_info[0] is None: + client_exc_info[0] = client.exc_info except Exception: errors.insert(0, { 'msg': 'Exception in main thread', @@ -492,11 +498,14 @@ class _FakeServerTest(unittest.TestCase): with lock: if exc_info is None: continue + timeout = False if not issubclass(exc_info[0], FakeServerTestSuccess): errors.insert(0, { 'msg': 'Exception in %s:' % thread_name, 'exc_info': exc_info}) - timeout = False + elif self.ignore_extra_exceptions: + del errors[:] + break if timeout: errors.insert(0, {'msg': 'Test timed out.'}) diff --git a/tests/test_connection.py b/tests/test_connection.py index 17f0a23..fb23b48 100644 --- a/tests/test_connection.py +++ b/tests/test_connection.py @@ -1,9 +1,14 @@ from minecraft import SUPPORTED_MINECRAFT_VERSIONS from minecraft.networking.packets import clientbound, serverbound from minecraft.networking.connection import IgnorePacket +from minecraft.compat import unicode from . import fake_server +import sys +import re +import io + class ConnectTest(fake_server._FakeServerTest): def test_connect(self): @@ -31,6 +36,37 @@ class PingTest(ConnectTest): client.status(handle_status=False, handle_ping=handle_ping) +class StatusTest(ConnectTest): + def _start_client(self, client): + def handle_status(status_dict): + assert status_dict['description'] == {'text': 'FakeServer'} + raise fake_server.FakeServerTestSuccess + client.status(handle_status=handle_status, handle_ping=False) + + +class DefaultStatusTest(ConnectTest): + def setUp(self): + class FakeStdOut(io.BytesIO): + def write(self, data): + if isinstance(data, unicode): + data = data.encode('utf8') + super(FakeStdOut, self).write(data) + sys.stdout, self.old_stdout = FakeStdOut(), sys.stdout + + def tearDown(self): + sys.stdout, self.old_stdout = self.old_stdout, None + + def _start_client(self, client): + def handle_exit(): + output = sys.stdout.getvalue() + assert re.match(b'{.*}\\nPing: \\d+ ms\\n$', output), \ + 'Invalid stdout contents: %r.' % output + raise fake_server.FakeServerTestSuccess + client.handle_exit = handle_exit + + client.status(handle_status=None, handle_ping=None) + + class ConnectCompressionLowTest(ConnectTest): compression_threshold = 0 @@ -189,3 +225,22 @@ class IgnorePacketTest(ConnectTest): 'Returned keep-alive IDs %r != %r' % \ (self._keep_alive_ids_returned, [3]) raise fake_server.FakeServerTestSuccess + + +class HandleExceptionTest(ConnectTest): + ignore_extra_exceptions = True + + def _start_client(self, client): + message = 'Min skoldpadda ar inte snabb, men den ar en skoldpadda.' + + def handle_login_success(_packet): + raise Exception(message) + client.register_packet_listener( + handle_login_success, clientbound.login.LoginSuccessPacket) + + def handle_exception(exc, exc_info): + assert isinstance(exc, Exception) and exc.args == (message,) + raise fake_server.FakeServerTestSuccess + client.handle_exception = handle_exception + + client.connect()