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
7 changes: 6 additions & 1 deletion can/interfaces/socketcan/socketcan.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.")


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.
29 changes: 29 additions & 0 deletions test/test_socketcan_helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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")