Skip to content

Commit

Permalink
improve TestBusConfig (#1804)
Browse files Browse the repository at this point in the history
  • Loading branch information
zariiii9003 authored Jun 23, 2024
1 parent 478f8b8 commit 2c90f9f
Show file tree
Hide file tree
Showing 2 changed files with 88 additions and 29 deletions.
49 changes: 29 additions & 20 deletions can/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
Utilities and configuration file parsing.
"""

import contextlib
import copy
import functools
import json
Expand Down Expand Up @@ -243,33 +244,41 @@ def _create_bus_config(config: Dict[str, Any]) -> typechecking.BusConfig:
if not 0 < port < 65535:
raise ValueError("Port config must be inside 0-65535 range!")

if config.get("timing", None) is None:
try:
if set(typechecking.BitTimingFdDict.__annotations__).issubset(config):
config["timing"] = can.BitTimingFd(
**{
key: int(config[key])
for key in typechecking.BitTimingFdDict.__annotations__
},
strict=False,
)
elif set(typechecking.BitTimingDict.__annotations__).issubset(config):
config["timing"] = can.BitTiming(
**{
key: int(config[key])
for key in typechecking.BitTimingDict.__annotations__
},
strict=False,
)
except (ValueError, TypeError):
pass
if "timing" not in config:
if timing := _dict2timing(config):
config["timing"] = timing

if "fd" in config:
config["fd"] = config["fd"] not in (0, False)

return cast(typechecking.BusConfig, config)


def _dict2timing(data: Dict[str, Any]) -> Union[BitTiming, BitTimingFd, None]:
"""Try to instantiate a :class:`~can.BitTiming` or :class:`~can.BitTimingFd` from
a dictionary. Return `None` if not possible."""

with contextlib.suppress(ValueError, TypeError):
if set(typechecking.BitTimingFdDict.__annotations__).issubset(data):
return BitTimingFd(
**{
key: int(data[key])
for key in typechecking.BitTimingFdDict.__annotations__
},
strict=False,
)
elif set(typechecking.BitTimingDict.__annotations__).issubset(data):
return BitTiming(
**{
key: int(data[key])
for key in typechecking.BitTimingDict.__annotations__
},
strict=False,
)

return None


def set_logging_level(level_name: str) -> None:
"""Set the logging level for the `"can"` logger.
Expand Down
68 changes: 59 additions & 9 deletions test/test_util.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@

import pytest

import can
from can import BitTiming, BitTimingFd
from can.exceptions import CanInitializationError
from can.util import (
Expand Down Expand Up @@ -132,10 +133,7 @@ def _test_func3(a):


class TestBusConfig(unittest.TestCase):
base_config = dict(interface="socketcan", bitrate=500_000)
port_alpha_config = dict(interface="socketcan", bitrate=500_000, port="fail123")
port_to_high_config = dict(interface="socketcan", bitrate=500_000, port="999999")
port_wrong_type_config = dict(interface="socketcan", bitrate=500_000, port=(1234,))
base_config = {"interface": "socketcan", "bitrate": 500_000}

def test_timing_can_use_int(self):
"""
Expand All @@ -147,17 +145,69 @@ def test_timing_can_use_int(self):
_create_bus_config({**self.base_config, **timing_conf})
except TypeError as e:
self.fail(e)

def test_port_datatype(self):
self.assertRaises(
ValueError, _create_bus_config, {**self.port_alpha_config, **timing_conf}
ValueError, _create_bus_config, {**self.base_config, "port": "fail123"}
)
self.assertRaises(
ValueError, _create_bus_config, {**self.port_to_high_config, **timing_conf}
ValueError, _create_bus_config, {**self.base_config, "port": "999999"}
)
self.assertRaises(
TypeError,
_create_bus_config,
{**self.port_wrong_type_config, **timing_conf},
TypeError, _create_bus_config, {**self.base_config, "port": (1234,)}
)

try:
_create_bus_config({**self.base_config, "port": "1234"})
except TypeError as e:
self.fail(e)

def test_bit_timing_cfg(self):
can_cfg = _create_bus_config(
{
**self.base_config,
"f_clock": "8000000",
"brp": "1",
"tseg1": "5",
"tseg2": "2",
"sjw": "1",
"nof_samples": "1",
}
)
timing = can_cfg["timing"]
assert isinstance(timing, can.BitTiming)
assert timing.f_clock == 8_000_000
assert timing.brp == 1
assert timing.tseg1 == 5
assert timing.tseg2 == 2
assert timing.sjw == 1

def test_bit_timing_fd_cfg(self):
canfd_cfg = _create_bus_config(
{
**self.base_config,
"f_clock": "80000000",
"nom_brp": "1",
"nom_tseg1": "119",
"nom_tseg2": "40",
"nom_sjw": "40",
"data_brp": "1",
"data_tseg1": "29",
"data_tseg2": "10",
"data_sjw": "10",
}
)
timing = canfd_cfg["timing"]
assert isinstance(timing, can.BitTimingFd)
assert timing.f_clock == 80_000_000
assert timing.nom_brp == 1
assert timing.nom_tseg1 == 119
assert timing.nom_tseg2 == 40
assert timing.nom_sjw == 40
assert timing.data_brp == 1
assert timing.data_tseg1 == 29
assert timing.data_tseg2 == 10
assert timing.data_sjw == 10


class TestChannel2Int(unittest.TestCase):
Expand Down

0 comments on commit 2c90f9f

Please sign in to comment.