Skip to content

Commit 3af7d7b

Browse files
[PATCH] Fix for dropping previously undefined, non-utf8 input (- WIP $188 -)
Changes in file multicast/hear.py: - Implemented changes to ensure defined (ignore) behavior when dealing with non-utf8. Changes in file tests/test_hear_data_processing.py: - implemented new test for related changes.
1 parent 39b1dd7 commit 3af7d7b

File tree

2 files changed

+32
-1
lines changed

2 files changed

+32
-1
lines changed

multicast/hear.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -426,7 +426,10 @@ def handle(self):
426426
if data is None or not sock:
427427
return # nothing to do -- fail fast.
428428
else:
429-
data = data.decode('utf8') if isinstance(data, bytes) else str(data)
429+
try:
430+
data = data.decode('utf8') if isinstance(data, bytes) else str(data)
431+
except UnicodeDecodeError: # pragma: no cover
432+
return # nothing to do -- fail quickly.
430433
if (_sys.stdout.isatty()): # pragma: no cover
431434
print(f"{self.client_address[0]} SAYS: {data.strip()} to ALL")
432435
if data is not None:

tests/test_hear_data_processing.py

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -180,6 +180,34 @@ def test_handle_none_data(self):
180180
"Socket should not be used when data is None"
181181
)
182182

183+
def test_handle_with_invalid_utf8_data(self):
184+
"""Test that HearUDPHandler silently ignores invalid UTF-8 data.
185+
186+
This test verifies that:
187+
1. The handler continues processing when receiving invalid UTF-8 data
188+
2. No exception is raised
189+
3. The handler silently ignores the decoding error
190+
"""
191+
_fixture_port_num = self._always_generate_random_port_WHEN_called()
192+
self.assertIsNotNone(_fixture_port_num)
193+
self.assertIsInstance(_fixture_port_num, int)
194+
data = b'\xff\xfe\xfd\xfc' # Invalid UTF-8 bytes
195+
sock = multicast.genSocket()
196+
handler = multicast.hear.HearUDPHandler(
197+
request=(data, sock),
198+
client_address=("224.0.0.1", _fixture_port_num),
199+
server=None
200+
)
201+
try:
202+
# Should silently ignore invalid UTF-8 data
203+
handler.handle()
204+
# If no exception is raised, the test passes
205+
except Exception as e:
206+
self.fail(f"Handler raised an unexpected exception: {e}")
207+
finally:
208+
# Clean up socket
209+
multicast.endSocket(sock)
210+
183211

184212
if __name__ == '__main__':
185213
unittest.main()

0 commit comments

Comments
 (0)