Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion can/interfaces/socketcan/socketcan.py
Original file line number Diff line number Diff line change
Expand Up @@ -603,7 +603,11 @@ 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}.")
raise
log.debug("Bound socket.")


Expand Down
1 change: 1 addition & 0 deletions doc/changelog.d/2104.added.rst
Original file line number Diff line number Diff line change
@@ -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.
18 changes: 18 additions & 0 deletions test/test_socketcan.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
BcmMsgHead,
SocketcanBus,
bcm_header_factory,
bind_socket,
build_bcm_header,
build_bcm_transmit_header,
build_bcm_tx_delete_header,
Expand Down Expand Up @@ -593,6 +594,23 @@ def test_capture_message_without_ancillary_data(self):
self.assertIsNotNone(received)
self.assertTrue(received.equals(expected), f"{received!r} != {expected!r}")

def test_bind_socket_adds_channel_to_oserror(self):
"""bind_socket() keeps the original OSError and notes the channel"""
sock = Mock()
sock.bind.side_effect = OSError(errno.ENODEV, "No such device")

with self.assertRaises(OSError) as ctx:
bind_socket(sock, "vcan42")

sock.bind.assert_called_once_with(("vcan42",))
# the error stays a plain OSError, so callers can still inspect it
self.assertEqual(ctx.exception.errno, errno.ENODEV)
self.assertEqual(ctx.exception.strerror, "No such device")
self.assertTrue(
any("vcan42" in note for note in ctx.exception.__notes__),
f"channel missing from {ctx.exception.__notes__!r}",
)


if __name__ == "__main__":
unittest.main()
Loading