Skip to content

Commit 32f07c3

Browse files
Gregox273Greg Brooks
andauthored
Convert BusState to enum when read with configparser (#1957)
* Convert BusState to enum when read with configparser (#1956) * Move BusState conversion to util.py (#1956) * Check state argument type before attempting conversion (#1956) * Add tests (#1956) * Fix formatting (#1956) * Compare enums by identity (#1956) --------- Co-authored-by: Greg Brooks <[email protected]>
1 parent 85b1cb2 commit 32f07c3

File tree

3 files changed

+30
-1
lines changed

3 files changed

+30
-1
lines changed

can/util.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -249,6 +249,12 @@ def _create_bus_config(config: dict[str, Any]) -> typechecking.BusConfig:
249249
if "fd" in config:
250250
config["fd"] = config["fd"] not in (0, False)
251251

252+
if "state" in config and not isinstance(config["state"], can.BusState):
253+
try:
254+
config["state"] = can.BusState[config["state"]]
255+
except KeyError as e:
256+
raise ValueError("State config not valid!") from e
257+
252258
return cast("typechecking.BusConfig", config)
253259

254260

doc/interfaces/pcan.rst

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ Here is an example configuration file for using `PCAN-USB <https://www.peak-syst
1515
[default]
1616
interface = pcan
1717
channel = PCAN_USBBUS1
18-
state = can.bus.BusState.PASSIVE
18+
state = PASSIVE
1919
bitrate = 500000
2020

2121
``channel`` (default ``"PCAN_USBBUS1"``)

test/test_util.py

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -209,6 +209,29 @@ def test_bit_timing_fd_cfg(self):
209209
assert timing.data_tseg2 == 10
210210
assert timing.data_sjw == 10
211211

212+
def test_state_with_str(self):
213+
can_cfg = _create_bus_config(
214+
{
215+
**self.base_config,
216+
"state": "PASSIVE",
217+
}
218+
)
219+
state = can_cfg["state"]
220+
assert isinstance(state, can.BusState)
221+
assert state is can.BusState.PASSIVE
222+
223+
def test_state_with_enum(self):
224+
expected_state = can.BusState.PASSIVE
225+
can_cfg = _create_bus_config(
226+
{
227+
**self.base_config,
228+
"state": expected_state,
229+
}
230+
)
231+
state = can_cfg["state"]
232+
assert isinstance(state, can.BusState)
233+
assert state is expected_state
234+
212235

213236
class TestChannel2Int(unittest.TestCase):
214237
def test_channel2int(self) -> None:

0 commit comments

Comments
 (0)