Add several tests for the Connection class.

This commit is contained in:
joo committed 2018-05-27 07:40:13 +01:00
1 parent ab9ca6dfee
commit 92f2eff681
3 files changed
+94 -17

No files matched your search

+29 -16
View File
@@ -57,6 +57,7 @@ class Connection(object):
initial_version=None, initial_version=None,
allowed_versions=None, allowed_versions=None,
handle_exception=None, handle_exception=None,
handle_exit=None,
): ):
"""Sets up an instance of this object to be able to connect to a """Sets up an instance of this object to be able to connect to a
minecraft server. minecraft server.
@@ -90,6 +91,11 @@ class Connection(object):
will terminate, the exception will be will terminate, the exception will be
available via the 'exception' and 'exc_info' available via the 'exception' and 'exc_info'
attributes of the 'Connection' instance. 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 """ # NOQA
# This lock is re-entrant because it may be acquired in a re-entrant # 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.options.port = port
self.auth_token = auth_token self.auth_token = auth_token
self.username = username self.username = username
self.connected = False
self.handle_exception = handle_exception self.handle_exception = handle_exception
self.exception, self.exc_info = None, None self.exception, self.exc_info = None, None
self.handle_exit = handle_exit
# The reactor handles all the default responses to packets, # The reactor handles all the default responses to packets,
# it should be changed per networking state # 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 = socket.socket(ai_faml, ai_type, ai_prot)
self.socket.connect(ai_addr) self.socket.connect(ai_addr)
self.file_object = self.socket.makefile("rb", 0) self.file_object = self.socket.makefile("rb", 0)
self.connected = True
def disconnect(self): def disconnect(self):
""" Terminate the existing server connection, if there is one. """ """ Terminate the existing server connection, if there is one. """
self.connected = False
with self._write_lock: # pylint: disable=not-context-manager with self._write_lock: # pylint: disable=not-context-manager
if self.socket is not None: if self.socket is not None:
# Flush any packets remaining in the queue. # Flush any packets remaining in the queue.
@@ -336,18 +347,12 @@ class Connection(object):
self.networking_thread.interrupt = True self.networking_thread.interrupt = True
if self.socket is not None: 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: try:
actual_socket.shutdown(socket.SHUT_RDWR) self.socket.shutdown(socket.SHUT_RDWR)
except socket.error: except socket.error:
pass pass
finally: finally:
actual_socket.close() self.socket.close()
self.socket = None self.socket = None
def _handshake(self, next_state=STATE_PLAYING): def _handshake(self, next_state=STATE_PLAYING):
@@ -360,21 +365,28 @@ class Connection(object):
self.write_packet(handshake) self.write_packet(handshake)
def _handle_exception(self, exc, exc_info): 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: try:
exc.exc_info = exc_info # For backward compatibility. exc.exc_info = exc_info # For backward compatibility.
except (TypeError, AttributeError): except (TypeError, AttributeError):
pass pass
if self.reactor.handle_exception(exc, exc_info):
return
self.disconnect()
self.exception, self.exc_info = exc, exc_info self.exception, self.exc_info = exc, exc_info
if self.handle_exception is None: self.disconnect()
if handle_exception is None:
raise_(*exc_info) 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): def _react(self, packet):
try: try:
@@ -405,6 +417,7 @@ class NetworkingThread(threading.Thread):
self.previous_thread = None self.previous_thread = None
self.connection.networking_thread = self self.connection.networking_thread = self
self._run() self._run()
self.connection._handle_exit()
except BaseException as e: except BaseException as e:
self.connection._handle_exception(e, sys.exc_info()) self.connection._handle_exception(e, sys.exc_info())
finally: finally:
+10 -1
View File
@@ -395,6 +395,10 @@ class _FakeServerTest(unittest.TestCase):
public_key_bytes = None public_key_bytes = None
# The serialised RSA public key used by the server: see 'FakeServer'. # 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): def _start_client(self, client):
game_joined = [False] game_joined = [False]
@@ -479,6 +483,8 @@ class _FakeServerTest(unittest.TestCase):
if thread is not None and thread.is_alive(): if thread is not None and thread.is_alive():
errors.append({ errors.append({
'msg': 'Thread "%s" timed out.' % thread.name}) 'msg': 'Thread "%s" timed out.' % thread.name})
if client_exc_info[0] is None:
client_exc_info[0] = client.exc_info
except Exception: except Exception:
errors.insert(0, { errors.insert(0, {
'msg': 'Exception in main thread', 'msg': 'Exception in main thread',
@@ -492,11 +498,14 @@ class _FakeServerTest(unittest.TestCase):
with lock: with lock:
if exc_info is None: if exc_info is None:
continue continue
timeout = False
if not issubclass(exc_info[0], FakeServerTestSuccess): if not issubclass(exc_info[0], FakeServerTestSuccess):
errors.insert(0, { errors.insert(0, {
'msg': 'Exception in %s:' % thread_name, 'msg': 'Exception in %s:' % thread_name,
'exc_info': exc_info}) 'exc_info': exc_info})
timeout = False elif self.ignore_extra_exceptions:
del errors[:]
break
if timeout: if timeout:
errors.insert(0, {'msg': 'Test timed out.'}) errors.insert(0, {'msg': 'Test timed out.'})
+55
View File
@@ -1,9 +1,14 @@
from minecraft import SUPPORTED_MINECRAFT_VERSIONS from minecraft import SUPPORTED_MINECRAFT_VERSIONS
from minecraft.networking.packets import clientbound, serverbound from minecraft.networking.packets import clientbound, serverbound
from minecraft.networking.connection import IgnorePacket from minecraft.networking.connection import IgnorePacket
from minecraft.compat import unicode
from . import fake_server from . import fake_server
import sys
import re
import io
class ConnectTest(fake_server._FakeServerTest): class ConnectTest(fake_server._FakeServerTest):
def test_connect(self): def test_connect(self):
@@ -31,6 +36,37 @@ class PingTest(ConnectTest):
client.status(handle_status=False, handle_ping=handle_ping) 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): class ConnectCompressionLowTest(ConnectTest):
compression_threshold = 0 compression_threshold = 0
@@ -189,3 +225,22 @@ class IgnorePacketTest(ConnectTest):
'Returned keep-alive IDs %r != %r' % \ 'Returned keep-alive IDs %r != %r' % \
(self._keep_alive_ids_returned, [3]) (self._keep_alive_ids_returned, [3])
raise fake_server.FakeServerTestSuccess 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()