Преглед изворни кода

fix(test_device_config): split checking between raw type and resolved Python type

- when checking type matches dps_val, we need to use the resolved type
  other existing checks are against the raw type.

- parameterize config tests rather than looping, so other configs
  get checked when there are errors in an earlier config.
Jason Rumney пре 20 часа
родитељ
комит
ea70392621
1 измењених фајлова са 85 додато и 78 уклоњено
  1. 85 78
      tests/test_device_config.py

+ 85 - 78
tests/test_device_config.py

@@ -464,16 +464,23 @@ def check_entity(entity, cfg, mocker):
     # for later checking
     for dp in entity.dps():
         line = dp._config.__line__
-        dp_type = dp._config.get("type")
+        dp_rawtype = dp.rawtype
+        dp_type = dp.type
         assert dp._config.get("id") is not None, (
             f"\n::error file={fname},line={line}::dp id missing from {e} in {cfg}"
         )
-        assert dp_type is not None, (
+        assert dp_rawtype is not None, (
             f"\n::error file={fname},line={line}::dp type missing from {e} in {cfg}"
         )
+        assert isinstance(dp_type, type(int)), (
+            f"\n::error file={fname},line={line}::dp unrecognized {dp_rawtype} type from {e} in {cfg}"
+        )
         assert dp._config.get("name") is not None, (
             f"\n::error file={fname},line={line}::dp name missing from {e} in {cfg}"
         )
+        # Allow hex and base64 to be matched to either str or int, since they can be masked
+        if dp_rawtype == "hex" or dp_rawtype == "base64":
+            dp_type = (str, int)
         extra.add(dp.name)
         mappings = dp._config.get("mapping", [])
         assert isinstance(mappings, list), (
@@ -485,22 +492,22 @@ def check_entity(entity, cfg, mocker):
             assert isinstance(conditions, list), (
                 f"\n::error file={fname},line={line}::conditions is not a list in {cfg}; entity {e}, dp {dp.name}"
             )
-            if m.get("invert") and dp_type not in ["integer", "hex", "base64"]:
+            if m.get("invert") and dp_rawtype not in ["integer", "hex", "base64"]:
                 pytest.fail(
                     f"\n::error file={fname},line={line}::invert is only valid for numeric values in {cfg}; entity {e}, dp {dp.name}"
                 )
             dpv = m.get("dps_val")
             if dpv is not None:
-                assert _typematch(dpv, dp_type), (
+                assert _typematch(dp_type, dpv), (
                     f"\n::error file={fname},line={line}::dps_val {dpv} is not compatible with "
-                    f"type {dp_type} in {cfg}; entity {e}, dp {dp.name}"
+                    f"type {dp_rawtype} in {cfg}; entity {e}, dp {dp.name}"
                 )
             for c in conditions:
                 if c.get("value_redirect"):
                     redirects.add(c.get("value_redirect"))
                 if c.get("value_mirror"):
                     redirects.add(c.get("value_mirror"))
-                if c.get("invert") and dp_type not in ["integer", "hex", "base64"]:
+                if c.get("invert") and dp_rawtype not in ["integer", "hex", "base64"]:
                     pytest.fail(
                         f"\n::error file={fname},line={line}::invert is only valid for numeric values in {cfg}; entity {e}, dp {dp.name}"
                     )
@@ -550,88 +557,88 @@ def check_entity(entity, cfg, mocker):
             )
 
 
-def test_config_files_parse(mocker):
+@pytest.mark.parametrize("cfg", available_configs())
+def test_config_file_parses(cfg, mocker):
     """
     All configs should be parsable and meet certain criteria
     """
-    for cfg in available_configs():
-        entities = []
-        parsed = TuyaDeviceConfig(cfg)
-        # Check for error messages or unparsed config
-        if isinstance(parsed, str) or isinstance(parsed._config, str):
-            pytest.fail(f"unparsable yaml in {cfg}")
-
-        fname = f"custom_components/tuya_local/devices/{cfg}"
-        try:
-            YAML_SCHEMA(parsed._config)
-        except vol.MultipleInvalid as e:
-            messages = []
-            first_line = None
-            for err in e.errors:
-                path = ".".join([str(p) for p in err.path])
-                messages.append(f"{path}: {err.msg}")
-                if first_line is None:
-                    # voluptuous doesn't always seem to return line numbers
-                    if err.path and hasattr(err.path[-1], "__line__"):
-                        first_line = err.path[-1].__line__
-
-            messages = "; ".join(messages)
-            if not first_line:
-                first_line = 1
-            pytest.fail(
-                f"\n::error file={fname},line={first_line}::Validation error: {messages}"
-            )
+    entities = []
+    parsed = TuyaDeviceConfig(cfg)
+    # Check for error messages or unparsed config
+    if isinstance(parsed, str) or isinstance(parsed._config, str):
+        pytest.fail(f"unparsable yaml in {cfg}")
 
-        assert parsed._config.get("name") is not None, (
-            f"\n::error file={fname},line=1::name missing from {cfg}"
+    fname = f"custom_components/tuya_local/devices/{cfg}"
+    try:
+        YAML_SCHEMA(parsed._config)
+    except vol.MultipleInvalid as e:
+        messages = []
+        first_line = None
+        for err in e.errors:
+            path = ".".join([str(p) for p in err.path])
+            messages.append(f"{path}: {err.msg}")
+            if first_line is None:
+                # voluptuous doesn't always seem to return line numbers
+                if err.path and hasattr(err.path[-1], "__line__"):
+                    first_line = err.path[-1].__line__
+
+        messages = "; ".join(messages)
+        if not first_line:
+            first_line = 1
+        pytest.fail(
+            f"\n::error file={fname},line={first_line}::Validation error: {messages}"
         )
-        count = 0
-        for entity in parsed.all_entities():
-            check_entity(entity, cfg, mocker)
-            # check entities are unique
-            if entity.config_id in entities:
-                pytest.fail(
-                    f"\n::error file={fname},line={entity._config.__line__}::"
-                    f"Duplicate entity {entity.config_id} in {cfg}"
-                )
-            entities.append(entity.config_id)
 
-            count += 1
-        assert count > 0, f"\n::error file={fname},line=1::No entities found in {cfg}"
+    assert parsed._config.get("name") is not None, (
+        f"\n::error file={fname},line=1::name missing from {cfg}"
+    )
+    count = 0
+    for entity in parsed.all_entities():
+        check_entity(entity, cfg, mocker)
+        # check entities are unique
+        if entity.config_id in entities:
+            pytest.fail(
+                f"\n::error file={fname},line={entity._config.__line__}::"
+                f"Duplicate entity {entity.config_id} in {cfg}"
+            )
+        entities.append(entity.config_id)
+
+        count += 1
+    assert count > 0, f"\n::error file={fname},line=1::No entities found in {cfg}"
 
 
-def test_configs_can_be_matched():
+@pytest.mark.parametrize("cfg", available_configs())
+def test_config_can_be_matched(cfg):
     """Test that the config files can be matched to a device."""
-    for cfg in available_configs():
-        optional = set()
-        required = set()
-        parsed = TuyaDeviceConfig(cfg)
-        fname = f"custom_components/tuya_local/devices/{cfg}"
-        products = parsed._config.get("products")
-        # Configs with a product list can be matched by product id
-        if products:
-            p_match = False
-            for p in products:
-                if p.get("id"):
-                    p_match = True
-            if p_match:
-                continue
-
-        for entity in parsed.all_entities():
-            for dp in entity.dps():
-                if dp.optional:
-                    optional.add(dp.id)
-                else:
-                    required.add(dp.id)
-
-        assert len(required) > 0, (
-            f"\n::error file={fname},line=1::No required dps found in {cfg}"
-        )
+    optional = set()
+    required = set()
+    parsed = TuyaDeviceConfig(cfg)
+    fname = f"custom_components/tuya_local/devices/{cfg}"
+    products = parsed._config.get("products")
+    # Configs with a product list can be matched by product id
+    if products:
+        p_match = False
+        for p in products:
+            if p.get("id"):
+                p_match = True
+        if p_match:
+            return
+
+    for entity in parsed.all_entities():
+        for dp in entity.dps():
+            if dp.optional:
+                optional.add(dp.id)
+            else:
+                required.add(dp.id)
+
+    assert len(required) > 0, (
+        f"\n::error file={fname},line=1::No required dps found in {cfg}"
+    )
 
-        for dp in required:
-            assert dp not in optional, (
-                f"\n::error file={fname},line=1::Optional dp {dp} is required in {cfg}"
-            )
+    for dp in required:
+        assert dp not in optional, (
+            f"\n::error file={fname},line=1::Optional dp {dp} is required in {cfg}"
+        )
 
 
 # Most of the device_config functionality is exercised during testing of