diff --git a/can/interfaces/socketcan/socketcan.py b/can/interfaces/socketcan/socketcan.py index 5970d8a20..df86ce53b 100644 --- a/can/interfaces/socketcan/socketcan.py +++ b/can/interfaces/socketcan/socketcan.py @@ -603,7 +603,12 @@ def bind_socket(sock: socket.socket, channel: str = "can0") -> None: If the specified interface isn't found. """ log.debug("Binding socket to channel=%s", channel) - sock.bind((channel,)) + try: + sock.bind((channel,)) + except OSError as exc: + exc.add_note(f"Failed to bind SocketCAN socket to channel {channel!r}.") + log.exception("Error binding SocketCAN socket to channel %r", channel) + raise log.debug("Bound socket.") diff --git a/doc/changelog.d/2104.added.rst b/doc/changelog.d/2104.added.rst new file mode 100644 index 000000000..7a87eac45 --- /dev/null +++ b/doc/changelog.d/2104.added.rst @@ -0,0 +1 @@ +SocketCAN sockets now add the channel name to the `OSError` raised when binding fails, so it can be identified when several buses are in use. diff --git a/test/test_socketcan_helpers.py b/test/test_socketcan_helpers.py index 710922290..4086a34e8 100644 --- a/test/test_socketcan_helpers.py +++ b/test/test_socketcan_helpers.py @@ -8,6 +8,7 @@ from pathlib import Path from unittest import mock +from can.interfaces.socketcan.socketcan import bind_socket from can.interfaces.socketcan.utils import error_code_to_str, find_available_interfaces from .config import IS_LINUX, TEST_INTERFACE_SOCKETCAN @@ -64,3 +65,31 @@ def test_find_available_interfaces_exception(self): if __name__ == "__main__": unittest.main() + + +class TestBindSocket(unittest.TestCase): + def test_bind_socket_adds_context_to_oserror(self): + """An OSError from bind() should name the channel that failed.""" + sock = mock.Mock() + sock.bind.side_effect = OSError(19, "No such device") + + with self.assertRaises(OSError) as context: + bind_socket(sock, "vcan42") + + sock.bind.assert_called_once_with(("vcan42",)) + notes = getattr(context.exception, "__notes__", []) + self.assertTrue( + any("vcan42" in note for note in notes), + f"expected the channel in {notes!r}", + ) + + def test_bind_socket_keeps_original_error(self): + """The raised exception should stay an OSError with its original args.""" + sock = mock.Mock() + sock.bind.side_effect = OSError(19, "No such device") + + with self.assertRaises(OSError) as context: + bind_socket(sock, "can0") + + self.assertEqual(context.exception.errno, 19) + self.assertEqual(context.exception.strerror, "No such device")