diff --git a/can/util.py b/can/util.py index f3b1040fd..ceba5a303 100644 --- a/can/util.py +++ b/can/util.py @@ -185,7 +185,7 @@ def load_config( # Slightly complex here to only search for the file config if required for _cfg in config_sources: - cfg = _cfg(context) if callable(_cfg) else _cfg + cfg = dict(_cfg(context) if callable(_cfg) else _cfg) # remove legacy operator (and copy to interface if not already present) if "bustype" in cfg: if "interface" not in cfg or not cfg["interface"]: diff --git a/doc/changelog.d/2142.fixed.rst b/doc/changelog.d/2142.fixed.rst new file mode 100644 index 000000000..d09c6d660 --- /dev/null +++ b/doc/changelog.d/2142.fixed.rst @@ -0,0 +1,2 @@ +Prevent configuration loading from modifying caller-owned dictionaries, +including ``can.rc``, when normalizing the legacy ``bustype`` key. diff --git a/test/test_load_config.py b/test/test_load_config.py index 3c850a730..3075f7b40 100644 --- a/test/test_load_config.py +++ b/test/test_load_config.py @@ -44,6 +44,31 @@ def _gen_configration_file(self, sections): def _dict_to_env(self, d): return {f"CAN_{k.upper()}": str(v) for k, v in d.items()} + def _load_config_isolated(self, config=None, rc=None): + missing_file = f"{self.test_dir}/missing.conf" + with ( + unittest.mock.patch.object(can, "rc", rc if rc is not None else {}), + unittest.mock.patch.dict("os.environ", {}, clear=True), + ): + return can.util.load_config(path=missing_file, config=config) + + def test_legacy_bustype_does_not_modify_config_argument(self): + for extra in ({}, {"interface": ""}, {"interface": "virtual"}): + with self.subTest(interface=extra.get("interface", "")): + original = {"bustype": "virtual", "channel": "0", **extra} + supplied = original.copy() + result = self._load_config_isolated(config=supplied) + self.assertEqual(result, {"interface": "virtual", "channel": 0}) + self.assertEqual(supplied, original) + + def test_legacy_bustype_does_not_modify_can_rc(self): + original = {"bustype": "virtual", "channel": "0"} + rc = original.copy() + for _ in range(2): + result = self._load_config_isolated(rc=rc) + self.assertEqual(result, {"interface": "virtual", "channel": 0}) + self.assertEqual(rc, original) + def test_config_default(self): tmp_config = self._gen_configration_file(["default"]) config = can.util.load_config(path=tmp_config)