Skip to content

Commit

Permalink
Raise better error if server doesn't return a full answer
Browse files Browse the repository at this point in the history
  • Loading branch information
PerchunPak authored and kevinkjt2000 committed Apr 17, 2023
1 parent 22788ad commit b1da0db
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 2 deletions.
5 changes: 4 additions & 1 deletion mcstatus/protocol/connection.py
Original file line number Diff line number Diff line change
Expand Up @@ -460,7 +460,10 @@ def __init__(self) -> None:
self.received = bytearray()

def read(self, length: int) -> bytearray:
"""Return self.received up to length bytes, then cut received up to that point."""
"""Return :attr:`.received` up to length bytes, then cut received up to that point."""
if len(self.received) < length:
raise IOError(f"Not enough data to read! {len(self.received)} < {length}")

result = self.received[:length]
self.received = self.received[length:]
return result
Expand Down
26 changes: 25 additions & 1 deletion tests/protocol/test_connection.py
Original file line number Diff line number Diff line change
Expand Up @@ -204,6 +204,18 @@ def test_write_buffer(self):

assert self.connection.flush() == bytearray.fromhex("027FAA")

def test_read_empty(self):
self.connection.received = bytearray()

with pytest.raises(IOError):
self.connection.read(1)

def test_read_not_enough(self):
self.connection.received = bytearray(b"a")

with pytest.raises(IOError):
self.connection.read(2)


class TestTCPSocketConnection:
@pytest.fixture(scope="class")
Expand Down Expand Up @@ -236,7 +248,13 @@ def test_read(self, connection):
assert connection.read(2) == bytearray.fromhex("7FAA")

def test_read_empty(self, connection):
connection.socket.recv.return_value = bytearray.fromhex("")
connection.socket.recv.return_value = bytearray()

with pytest.raises(IOError):
connection.read(1)

def test_read_not_enough(self, connection):
connection.socket.recv.side_effect = [bytearray(b"a"), bytearray()]

with pytest.raises(IOError):
connection.read(2)
Expand Down Expand Up @@ -276,6 +294,12 @@ def test_read(self, connection):

assert connection.read(2) == bytearray.fromhex("7FAA")

def test_read_empty(self, connection):
connection.socket.recvfrom.return_value = []

with pytest.raises(IndexError):
connection.read(1)

def test_write(self, connection):
connection.write(bytearray.fromhex("7FAA"))

Expand Down

0 comments on commit b1da0db

Please sign in to comment.