File tree Expand file tree Collapse file tree 2 files changed +32
-1
lines changed Expand file tree Collapse file tree 2 files changed +32
-1
lines changed Original file line number Diff line number Diff 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 :
Original file line number Diff line number Diff 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
184212if __name__ == '__main__' :
185213 unittest .main ()
You can’t perform that action at this time.
0 commit comments