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
11 changes: 10 additions & 1 deletion can/interfaces/socketcan/socketcan.py
Original file line number Diff line number Diff line change
Expand Up @@ -598,7 +598,16 @@ 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 error:
context = f"SocketCAN channel {channel!r}"
if error.strerror is None:
error.args = (f"{error} ({context})",)
else:
error.strerror = f"{error.strerror} ({context})"
error.args = (error.errno, error.strerror)
raise
log.debug("Bound socket.")


Expand Down
1 change: 1 addition & 0 deletions doc/changelog.d/2104.fixed.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Include the SocketCAN channel in socket binding errors.
30 changes: 29 additions & 1 deletion test/test_socketcan.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,12 @@
"""

import ctypes
import errno
import struct
import sys
import unittest
import warnings
from unittest.mock import patch
from unittest.mock import Mock, patch

import can
from can.interfaces.socketcan.constants import (
Expand All @@ -22,6 +23,7 @@
from can.interfaces.socketcan.socketcan import (
BcmMsgHead,
bcm_header_factory,
bind_socket,
build_bcm_header,
build_bcm_transmit_header,
build_bcm_tx_delete_header,
Expand All @@ -32,6 +34,32 @@


class SocketCANTest(unittest.TestCase):
def test_bind_socket_failure_identifies_channel(self):
for channel, error in (
("can0", OSError(errno.ENODEV, "No such device")),
("vcan42", PermissionError(errno.EPERM, "Operation not permitted")),
("can-special", OSError("bind failed")),
):
with self.subTest(channel=channel):
sock = Mock()
sock.bind.side_effect = error

with self.assertRaises(OSError) as caught:
bind_socket(sock, channel)

self.assertIn(channel, str(caught.exception))
self.assertIn(channel, repr(caught.exception))
self.assertIs(caught.exception, error)
self.assertEqual(caught.exception.errno, error.errno)
sock.bind.assert_called_once_with((channel,))

def test_bind_socket_success(self):
sock = Mock()

bind_socket(sock, "can0")

sock.bind.assert_called_once_with(("can0",))

def setUp(self):
self._ctypes_sizeof = ctypes.sizeof
self._ctypes_alignment = ctypes.alignment
Expand Down