test_device_config.py 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235
  1. """Test the config parser"""
  2. from unittest import IsolatedAsyncioTestCase
  3. from unittest.mock import MagicMock
  4. from custom_components.tuya_local.helpers.device_config import (
  5. available_configs,
  6. get_config,
  7. _bytes_to_fmt,
  8. _typematch,
  9. TuyaDeviceConfig,
  10. TuyaDpsConfig,
  11. TuyaEntityConfig,
  12. )
  13. from .const import (
  14. GPPH_HEATER_PAYLOAD,
  15. KOGAN_HEATER_PAYLOAD,
  16. )
  17. class TestDeviceConfig(IsolatedAsyncioTestCase):
  18. """Test the device config parser"""
  19. def test_can_find_config_files(self):
  20. """Test that the config files can be found by the parser."""
  21. found = False
  22. for cfg in available_configs():
  23. found = True
  24. break
  25. self.assertTrue(found)
  26. def check_entity(self, entity, cfg):
  27. """
  28. Check that the entity has a dps list and each dps has an id,
  29. type and name.
  30. """
  31. self.assertIsNotNone(
  32. entity._config.get("entity"), f"entity type missing in {cfg}"
  33. )
  34. e = entity.config_id
  35. self.assertIsNotNone(
  36. entity._config.get("dps"), f"dps missing from {e} in {cfg}"
  37. )
  38. for dp in entity.dps():
  39. self.assertIsNotNone(
  40. dp._config.get("id"), f"dp id missing from {e} in {cfg}"
  41. )
  42. self.assertIsNotNone(
  43. dp._config.get("type"), f"dp type missing from {e} in {cfg}"
  44. )
  45. self.assertIsNotNone(
  46. dp._config.get("name"), f"dp name missing from {e} in {cfg}"
  47. )
  48. def test_config_files_parse(self):
  49. """
  50. All configs should be parsable and meet certain criteria
  51. """
  52. for cfg in available_configs():
  53. parsed = TuyaDeviceConfig(cfg)
  54. # Check for error messages or unparsed config
  55. if isinstance(parsed, str) or isinstance(parsed._config, str):
  56. self.fail(f"unparsable yaml in {cfg}")
  57. self.assertIsNotNone(
  58. parsed._config.get("name"),
  59. f"name missing from {cfg}",
  60. )
  61. self.assertIsNotNone(
  62. parsed._config.get("primary_entity"),
  63. f"primary_entity missing from {cfg}",
  64. )
  65. self.check_entity(parsed.primary_entity, cfg)
  66. for entity in parsed.secondary_entities():
  67. self.check_entity(entity, cfg)
  68. # Most of the device_config functionality is exercised during testing of
  69. # the various supported devices. These tests concentrate only on the gaps.
  70. def test_match_quality(self):
  71. """Test the match_quality function."""
  72. cfg = get_config("deta_fan")
  73. q = cfg.match_quality({**KOGAN_HEATER_PAYLOAD, "updated_at": 0})
  74. self.assertEqual(q, 0)
  75. q = cfg.match_quality({**GPPH_HEATER_PAYLOAD})
  76. self.assertEqual(q, 0)
  77. def test_entity_find_unknown_dps_fails(self):
  78. """Test that finding a dps that doesn't exist fails."""
  79. cfg = get_config("kogan_switch")
  80. non_existing = cfg.primary_entity.find_dps("missing")
  81. self.assertIsNone(non_existing)
  82. async def test_dps_async_set_readonly_value_fails(self):
  83. """Test that setting a readonly dps fails."""
  84. mock_device = MagicMock()
  85. cfg = get_config("kogan_switch")
  86. voltage = cfg.primary_entity.find_dps("voltage_v")
  87. with self.assertRaises(TypeError):
  88. await voltage.async_set_value(mock_device, 230)
  89. def test_dps_values_returns_none_with_no_mapping(self):
  90. """
  91. Test that a dps with no mapping returns None as its possible values
  92. """
  93. mock_device = MagicMock()
  94. cfg = get_config("kogan_switch")
  95. voltage = cfg.primary_entity.find_dps("voltage_v")
  96. self.assertIsNone(voltage.values(mock_device))
  97. def test_config_returned(self):
  98. """Test that config file is returned by config"""
  99. cfg = get_config("kogan_switch")
  100. self.assertEqual(cfg.config, "smartplugv1.yaml")
  101. def test_float_matches_ints(self):
  102. """Test that the _typematch function matches int values to float dps"""
  103. self.assertTrue(_typematch(float, 1))
  104. def test_bytes_to_fmt_returns_string_for_unknown(self):
  105. """
  106. Test that the _bytes_to_fmt function parses unknown number of bytes
  107. as a string format.
  108. """
  109. self.assertEqual(_bytes_to_fmt(5), "5s")
  110. def test_deprecation(self):
  111. """Test that deprecation messages are picked from the config."""
  112. mock_device = MagicMock()
  113. mock_device.name = "Testing"
  114. mock_config = {"entity": "Test", "deprecated": "Passed"}
  115. cfg = TuyaEntityConfig(mock_device, mock_config)
  116. self.assertTrue(cfg.deprecated)
  117. self.assertEqual(
  118. cfg.deprecation_message,
  119. "The use of Test for Testing is deprecated and should be "
  120. "replaced by Passed.",
  121. )
  122. def test_format_with_none_defined(self):
  123. """Test that format returns None when there is none configured."""
  124. mock_entity = MagicMock()
  125. mock_config = {"id": "1", "name": "test", "type": "string"}
  126. cfg = TuyaDpsConfig(mock_entity, mock_config)
  127. self.assertIsNone(cfg.format)
  128. def test_decoding_base64(self):
  129. """Test that decoded_value works with base64 encoding."""
  130. mock_entity = MagicMock()
  131. mock_config = {"id": "1", "name": "test", "type": "base64"}
  132. mock_device = MagicMock()
  133. mock_device.get_property.return_value = "VGVzdA=="
  134. cfg = TuyaDpsConfig(mock_entity, mock_config)
  135. self.assertEqual(
  136. cfg.decoded_value(mock_device),
  137. bytes("Test", "utf-8"),
  138. )
  139. def test_decoding_unencoded(self):
  140. """Test that decoded_value returns the raw value when not encoded."""
  141. mock_entity = MagicMock()
  142. mock_config = {"id": "1", "name": "test", "type": "string"}
  143. mock_device = MagicMock()
  144. mock_device.get_property.return_value = "VGVzdA=="
  145. cfg = TuyaDpsConfig(mock_entity, mock_config)
  146. self.assertEqual(
  147. cfg.decoded_value(mock_device),
  148. "VGVzdA==",
  149. )
  150. def test_encoding_base64(self):
  151. """Test that encode_value works with base64."""
  152. mock_entity = MagicMock()
  153. mock_config = {"id": "1", "name": "test", "type": "base64"}
  154. cfg = TuyaDpsConfig(mock_entity, mock_config)
  155. self.assertEqual(cfg.encode_value(bytes("Test", "utf-8")), "VGVzdA==")
  156. def test_encoding_unencoded(self):
  157. """Test that encode_value works with base64."""
  158. mock_entity = MagicMock()
  159. mock_config = {"id": "1", "name": "test", "type": "string"}
  160. cfg = TuyaDpsConfig(mock_entity, mock_config)
  161. self.assertEqual(cfg.encode_value("Test"), "Test")
  162. def test_match_returns_false_on_errors_with_bitfield(self):
  163. """Test that TypeError and ValueError cause match to return False."""
  164. mock_entity = MagicMock()
  165. mock_config = {"id": "1", "name": "test", "type": "bitfield"}
  166. cfg = TuyaDpsConfig(mock_entity, mock_config)
  167. self.assertFalse(cfg._match(15, "not an integer"))
  168. def test_values_with_mirror(self):
  169. """Test that value_mirror redirects."""
  170. mock_entity = MagicMock()
  171. mock_config = {
  172. "id": "1",
  173. "type": "string",
  174. "name": "test",
  175. "mapping": [
  176. {"dps_val": "mirror", "value_mirror": "map_mirror"},
  177. {"dps_val": "plain", "value": "unmirrored"},
  178. ],
  179. }
  180. mock_map_config = {
  181. "id": "2",
  182. "type": "string",
  183. "name": "map_mirror",
  184. "mapping": [
  185. {"dps_val": "1", "value": "map_one"},
  186. {"dps_val": "2", "value": "map_two"},
  187. ],
  188. }
  189. mock_device = MagicMock()
  190. mock_device.get_property.return_value = "1"
  191. cfg = TuyaDpsConfig(mock_entity, mock_config)
  192. map = TuyaDpsConfig(mock_entity, mock_map_config)
  193. mock_entity.find_dps.return_value = map
  194. self.assertCountEqual(
  195. cfg.values(mock_device),
  196. ["unmirrored", "map_one", "map_two"],
  197. )
  198. # values gets very complex, with things like mappings within conditions
  199. # within mappings. I'd expect something like this was added with purpose,
  200. # but it isn't exercised by any of the existing unit tests.
  201. # value-mirror above is explained by the fact that the device it was
  202. # added for never worked properly, so was removed.
  203. def test_default_without_mapping(self):
  204. """Test that default returns None when there is no mapping"""
  205. mock_entity = MagicMock()
  206. mock_config = {"id": "1", "name": "test", "type": "string"}
  207. cfg = TuyaDpsConfig(mock_entity, mock_config)
  208. self.assertIsNone(cfg.default())