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/test/test_load_config.py b/test/test_load_config.py index 3c850a730..97398ce55 100644 --- a/test/test_load_config.py +++ b/test/test_load_config.py @@ -44,6 +44,54 @@ 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 test_config_sources_are_not_modified(self): + for interface in (None, "", "virtual"): + with self.subTest(interface=interface): + original = {"bustype": "virtual", "channel": "0"} + if interface is not None: + original["interface"] = interface + for source in ("argument", "rc", "environment", "file"): + with self.subTest(source=source): + supplied = original.copy() + with ( + unittest.mock.patch.object( + can, "rc", supplied if source == "rc" else {} + ), + unittest.mock.patch( + "can.util.load_environment_config", + return_value=( + supplied if source == "environment" else {} + ), + ), + unittest.mock.patch( + "can.util.load_file_config", + return_value=supplied if source == "file" else {}, + ), + ): + for _ in range(2): + result = can.util.load_config( + config=supplied if source == "argument" else {} + ) + self.assertEqual( + result, {"interface": "virtual", "channel": 0} + ) + self.assertEqual(supplied, original) + + def test_config_precedence_with_legacy_interface(self): + supplied = {"interface": "virtual", "bustype": "socketcan", "channel": "0"} + rc = {"bustype": "serial", "channel": "1", "bitrate": "125000"} + with ( + unittest.mock.patch.object(can, "rc", rc), + unittest.mock.patch("can.util.load_environment_config", return_value={}), + unittest.mock.patch("can.util.load_file_config", return_value={}), + ): + self.assertEqual( + can.util.load_config(config=supplied), + {"interface": "virtual", "channel": 0, "bitrate": 125000}, + ) + self.assertEqual(supplied["bustype"], "socketcan") + self.assertEqual(rc, {"bustype": "serial", "channel": "1", "bitrate": "125000"}) + def test_config_default(self): tmp_config = self._gen_configration_file(["default"]) config = can.util.load_config(path=tmp_config)