from pathlib import Path import pytest from gateway.config import ConfigError, load_config ROOT = Path(__file__).resolve().parents[1] def test_load_shipped_config(): cfg = load_config(ROOT / "config" / "config.yaml") assert len(cfg.compressors) == 9 assert len(cfg.slaves) == 2 assert cfg.slaves[0].port != cfg.slaves[1].port assert sorted(c.register_index for c in cfg.compressors) == list(range(9)) assert cfg.register_float_order == "ABCD" assert {c.s331 for c in cfg.compressors} == {"s331_1", "s331_2"} def test_device_address_offset_is_applied(tmp_path): # 先加载原配置拿原始值 cfg_orig = load_config(ROOT / "config" / "config.yaml") first_orig = next(c for c in cfg_orig.compressors if c.id == 3) orig_power_addr = first_orig.power_instant.address orig_flow_addr = first_orig.flow_instant.address orig_device_count = len(cfg_orig.devices) source = (ROOT / "config" / "config.yaml").read_text(encoding="utf-8") # 给蘑菇云电表加 10 个寄存器整体偏移(devices 首个配置块即 mogo_meter) source = source.replace(" address_offset: 0", " address_offset: 10", 1) config_file = tmp_path / "config.yaml" config_file.write_text(source, encoding="utf-8") cfg = load_config(config_file) assert len(cfg.devices) == orig_device_count meter = cfg.devices["mogo_meter"] assert meter.address_offset == 10 # 电表点位整体后移 10 个寄存器 first = next(c for c in cfg.compressors if c.id == 3) assert first.power_instant.address == orig_power_addr + 10 # S331 点位不受 meter 偏移影响 assert first.flow_instant.address == orig_flow_addr def test_duplicate_register_index_rejected(tmp_path): source = (ROOT / "config" / "config.yaml").read_text(encoding="utf-8") source = source.replace("register_index: 1\n", "register_index: 0\n", 1) config_file = tmp_path / "config.yaml" config_file.write_text(source, encoding="utf-8") with pytest.raises(ConfigError): load_config(config_file) def test_duplicate_slave_port_rejected(tmp_path): source = (ROOT / "config" / "config.yaml").read_text(encoding="utf-8") source = source.replace("/dev/ttyS7", "/dev/ttyS1") config_file = tmp_path / "config.yaml" config_file.write_text(source, encoding="utf-8") with pytest.raises(ConfigError): load_config(config_file)