Skip to content

Commit f6d8fe0

Browse files
Thepowa753Federico Bregantzariiii9003
authored
fix: conversion for port number (#1309)
* fix: conversion for port number * fix: correct order for valid port range * refactor: tabs and spaces Sorry * fix: calling port within if in dict * fix: forcing int to bypass wrong error * feat: add util port tests * fix: tests assertRaises with correct syntax * refactor: using black * make mypy happy Co-authored-by: Federico Bregant <[email protected]> Co-authored-by: zariiii9003 <[email protected]>
1 parent ed124c9 commit f6d8fe0

File tree

2 files changed

+28
-0
lines changed

2 files changed

+28
-0
lines changed

can/util.py

+14
Original file line numberDiff line numberDiff line change
@@ -211,6 +211,20 @@ def _create_bus_config(config: Dict[str, Any]) -> typechecking.BusConfig:
211211
raise CanInterfaceNotImplementedError(
212212
f'Unknown interface type "{config["interface"]}"'
213213
)
214+
if "port" in config:
215+
# convert port to integer if necessary
216+
if isinstance(config["port"], int):
217+
port = config["port"]
218+
elif isinstance(config["port"], str):
219+
if config["port"].isnumeric():
220+
config["port"] = port = int(config["port"])
221+
else:
222+
raise ValueError("Port config must be a number!")
223+
else:
224+
raise TypeError("Port config must be string or integer!")
225+
226+
if not 0 < port < 65535:
227+
raise ValueError("Port config must be inside 0-65535 range!")
214228

215229
if "bitrate" in config:
216230
config["bitrate"] = int(config["bitrate"])

test/test_util.py

+14
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,9 @@ def test_with_new_and_alias_present(self):
5353

5454
class TestBusConfig(unittest.TestCase):
5555
base_config = dict(interface="socketcan", bitrate=500_000)
56+
port_alpha_config = dict(interface="socketcan", bitrate=500_000, port="fail123")
57+
port_to_high_config = dict(interface="socketcan", bitrate=500_000, port="999999")
58+
port_wrong_type_config = dict(interface="socketcan", bitrate=500_000, port=(1234,))
5659

5760
def test_timing_can_use_int(self):
5861
"""
@@ -64,6 +67,17 @@ def test_timing_can_use_int(self):
6467
_create_bus_config({**self.base_config, **timing_conf})
6568
except TypeError as e:
6669
self.fail(e)
70+
self.assertRaises(
71+
ValueError, _create_bus_config, {**self.port_alpha_config, **timing_conf}
72+
)
73+
self.assertRaises(
74+
ValueError, _create_bus_config, {**self.port_to_high_config, **timing_conf}
75+
)
76+
self.assertRaises(
77+
TypeError,
78+
_create_bus_config,
79+
{**self.port_wrong_type_config, **timing_conf},
80+
)
6781

6882

6983
class TestChannel2Int(unittest.TestCase):

0 commit comments

Comments
 (0)