test_device_config.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478
  1. """Test the config parser"""
  2. from fuzzywuzzy import fuzz
  3. from unittest import IsolatedAsyncioTestCase
  4. from unittest.mock import MagicMock
  5. from homeassistant.components.sensor import SensorDeviceClass
  6. from custom_components.tuya_local.helpers.config import get_device_id
  7. from custom_components.tuya_local.helpers.device_config import (
  8. available_configs,
  9. get_config,
  10. _bytes_to_fmt,
  11. _typematch,
  12. TuyaDeviceConfig,
  13. TuyaDpsConfig,
  14. TuyaEntityConfig,
  15. )
  16. from custom_components.tuya_local.sensor import TuyaLocalSensor
  17. from .const import (
  18. GPPH_HEATER_PAYLOAD,
  19. KOGAN_HEATER_PAYLOAD,
  20. )
  21. KNOWN_DPS = {
  22. "binary_sensor": {"required": ["sensor"], "optional": []},
  23. "button": {"required": ["button"], "optional": []},
  24. "camera": {
  25. "required": [],
  26. "optional": ["switch", "motion_enable", "snapshot", "record"],
  27. },
  28. "climate": {
  29. "required": [],
  30. "optional": [
  31. "aux_heat",
  32. "current_temperature",
  33. "current_humidity",
  34. "fan_mode",
  35. "humidity",
  36. "hvac_mode",
  37. "hvac_action",
  38. "min_temperature",
  39. "max_temperature",
  40. "preset_mode",
  41. "swing_mode",
  42. {
  43. "xor": [
  44. "temperature",
  45. {"and": ["target_temp_high", "target_temp_low"]},
  46. ]
  47. },
  48. "temperature_unit",
  49. ],
  50. },
  51. "cover": {
  52. "required": [{"or": ["control", "position"]}],
  53. "optional": [
  54. "current_position",
  55. "action",
  56. "open",
  57. "reversed",
  58. ],
  59. },
  60. "fan": {
  61. "required": [{"or": ["preset_mode", "speed"]}],
  62. "optional": ["switch", "oscillate", "direction"],
  63. },
  64. "humidifier": {"required": ["switch", "humidity"], "optional": ["mode"]},
  65. "light": {
  66. "required": [{"or": ["switch", "brightness", "effect"]}],
  67. "optional": ["color_mode", "color_temp", "rgbhsv"],
  68. },
  69. "lock": {
  70. "optional": [
  71. "lock",
  72. {"and": ["request_unlock", "approve_unlock"]},
  73. "unlock_fingerprint",
  74. "unlock_password",
  75. "unlock_temp_pwd",
  76. "unlock_dynamic_pwd",
  77. "unlock_card",
  78. "unlock_app",
  79. "unlock_key",
  80. {"and": ["request_intercom", "approve_intercom"]},
  81. "jammed",
  82. ],
  83. },
  84. "number": {
  85. "required": ["value"],
  86. "optional": ["unit", "minimum", "maximum"],
  87. },
  88. "select": {"required": ["option"], "optional": []},
  89. "sensor": {"required": ["sensor"], "optional": ["unit"]},
  90. "siren": {"required": [], "optional": ["tone", "volume", "duration"]},
  91. "switch": {"required": ["switch"], "optional": ["current_power_w"]},
  92. "vacuum": {
  93. "required": ["status"],
  94. "optional": [
  95. "command",
  96. "locate",
  97. "power",
  98. "activate",
  99. "battery",
  100. "direction_control",
  101. "error",
  102. "fan_speed",
  103. ],
  104. },
  105. "water_heater": {
  106. "required": [],
  107. "optional": [
  108. "current_temperature",
  109. "operation_mode",
  110. "temperature",
  111. "temperature_unit",
  112. "min_temperature",
  113. "max_temperature",
  114. ],
  115. },
  116. }
  117. class TestDeviceConfig(IsolatedAsyncioTestCase):
  118. """Test the device config parser"""
  119. def test_can_find_config_files(self):
  120. """Test that the config files can be found by the parser."""
  121. found = False
  122. for cfg in available_configs():
  123. found = True
  124. break
  125. self.assertTrue(found)
  126. def dp_match(self, condition, accounted, unaccounted, known, required=False):
  127. if type(condition) is str:
  128. known.add(condition)
  129. if condition in unaccounted:
  130. unaccounted.remove(condition)
  131. accounted.add(condition)
  132. if required:
  133. return condition in accounted
  134. else:
  135. return True
  136. elif "and" in condition:
  137. return self.and_match(
  138. condition["and"], accounted, unaccounted, known, required
  139. )
  140. elif "or" in condition:
  141. return self.or_match(condition["or"], accounted, unaccounted, known)
  142. elif "xor" in condition:
  143. return self.xor_match(
  144. condition["xor"], accounted, unaccounted, known, required
  145. )
  146. else:
  147. self.fail(f"Unrecognized condition {condition}")
  148. def and_match(self, conditions, accounted, unaccounted, known, required):
  149. single_match = False
  150. all_match = True
  151. for cond in conditions:
  152. match = self.dp_match(cond, accounted, unaccounted, known, True)
  153. all_match = all_match and match
  154. single_match = single_match or match
  155. if required:
  156. return all_match
  157. else:
  158. return all_match == single_match
  159. def or_match(self, conditions, accounted, unaccounted, known):
  160. match = False
  161. # loop through all, to ensure they are transferred to accounted list
  162. for cond in conditions:
  163. match = match or self.dp_match(cond, accounted, unaccounted, known, True)
  164. return match
  165. def xor_match(self, conditions, accounted, unaccounted, known, required):
  166. prior_match = False
  167. for cond in conditions:
  168. match = self.dp_match(cond, accounted, unaccounted, known, True)
  169. if match and prior_match:
  170. return False
  171. prior_match = prior_match or match
  172. # If any matched, all should be considered matched
  173. # this bit only handles nesting "and" within "xor"
  174. if prior_match:
  175. for c in conditions:
  176. if type(c) is str:
  177. accounted.add(c)
  178. elif "and" in c:
  179. for c2 in c["and"]:
  180. if type(c2) is str:
  181. accounted.add(c2)
  182. return prior_match or not required
  183. def rule_broken_msg(self, rule):
  184. msg = ""
  185. if type(rule) is str:
  186. return f"{msg} {rule}"
  187. elif "and" in rule:
  188. msg = f"{msg} all of ["
  189. for sub in rule["and"]:
  190. msg = f"{msg} {self.rule_broken_msg(sub)}"
  191. return f"{msg} ]"
  192. elif "or" in rule:
  193. msg = f"{msg} at least one of ["
  194. for sub in rule["or"]:
  195. msg = f"{msg} {self.rule_broken_msg(sub)}"
  196. return f"{msg} ]"
  197. elif "xor" in rule:
  198. msg = f"{msg} only one of ["
  199. for sub in rule["xor"]:
  200. msg = f"{msg} {self.rule_broken_msg(sub)}"
  201. return f"{msg} ]"
  202. return "for reason unknown"
  203. def check_entity(self, entity, cfg):
  204. """
  205. Check that the entity has a dps list and each dps has an id,
  206. type and name.
  207. """
  208. self.assertIsNotNone(
  209. entity._config.get("entity"), f"entity type missing in {cfg}"
  210. )
  211. e = entity.config_id
  212. self.assertIsNotNone(
  213. entity._config.get("dps"), f"dps missing from {e} in {cfg}"
  214. )
  215. functions = set()
  216. extra = set()
  217. known = set()
  218. for dp in entity.dps():
  219. self.assertIsNotNone(
  220. dp._config.get("id"), f"dp id missing from {e} in {cfg}"
  221. )
  222. self.assertIsNotNone(
  223. dp._config.get("type"), f"dp type missing from {e} in {cfg}"
  224. )
  225. self.assertIsNotNone(
  226. dp._config.get("name"), f"dp name missing from {e} in {cfg}"
  227. )
  228. extra.add(dp.name)
  229. expected = KNOWN_DPS.get(entity.entity)
  230. for rule in expected["required"]:
  231. self.assertTrue(
  232. self.dp_match(rule, functions, extra, known, True),
  233. f"{cfg} missing required {self.rule_broken_msg(rule)} in {e}",
  234. )
  235. for rule in expected["optional"]:
  236. self.assertTrue(
  237. self.dp_match(rule, functions, extra, known, False),
  238. f"{cfg} expecting {self.rule_broken_msg(rule)} in {e}",
  239. )
  240. # Check for potential typos in extra attributes
  241. known_extra = known - functions
  242. for attr in extra:
  243. for dp in known_extra:
  244. self.assertLess(
  245. fuzz.ratio(attr, dp),
  246. 85,
  247. f"Probable typo {attr} is too similar to {dp} in {cfg} {e}",
  248. )
  249. # Check that sensors with mapped values are of class enum and vice versa
  250. if entity.entity == "sensor":
  251. mock_device = MagicMock()
  252. sensor = TuyaLocalSensor(mock_device, entity)
  253. if sensor.options:
  254. self.assertEqual(
  255. entity.device_class,
  256. SensorDeviceClass.ENUM,
  257. f"{cfg} {e} has mapped values but does not have a device class of enum",
  258. )
  259. if entity.device_class == SensorDeviceClass.ENUM:
  260. self.assertIsNotNone(
  261. sensor.options,
  262. f"{cfg} {e} has a device class of enum, but has no mapped values",
  263. )
  264. def test_config_files_parse(self):
  265. """
  266. All configs should be parsable and meet certain criteria
  267. """
  268. for cfg in available_configs():
  269. entities = []
  270. parsed = TuyaDeviceConfig(cfg)
  271. # Check for error messages or unparsed config
  272. if isinstance(parsed, str) or isinstance(parsed._config, str):
  273. self.fail(f"unparsable yaml in {cfg}")
  274. self.assertIsNotNone(
  275. parsed._config.get("name"),
  276. f"name missing from {cfg}",
  277. )
  278. self.assertIsNotNone(
  279. parsed._config.get("primary_entity"),
  280. f"primary_entity missing from {cfg}",
  281. )
  282. self.check_entity(parsed.primary_entity, cfg)
  283. entities.append(parsed.primary_entity.config_id)
  284. for entity in parsed.secondary_entities():
  285. self.check_entity(entity, cfg)
  286. entities.append(entity.config_id)
  287. self.assertCountEqual(entities, set(entities))
  288. # Most of the device_config functionality is exercised during testing of
  289. # the various supported devices. These tests concentrate only on the gaps.
  290. def test_match_quality(self):
  291. """Test the match_quality function."""
  292. cfg = get_config("deta_fan")
  293. q = cfg.match_quality({**KOGAN_HEATER_PAYLOAD, "updated_at": 0})
  294. self.assertEqual(q, 0)
  295. q = cfg.match_quality({**GPPH_HEATER_PAYLOAD})
  296. self.assertEqual(q, 0)
  297. def test_entity_find_unknown_dps_fails(self):
  298. """Test that finding a dps that doesn't exist fails."""
  299. cfg = get_config("kogan_switch")
  300. non_existing = cfg.primary_entity.find_dps("missing")
  301. self.assertIsNone(non_existing)
  302. async def test_dps_async_set_readonly_value_fails(self):
  303. """Test that setting a readonly dps fails."""
  304. mock_device = MagicMock()
  305. cfg = get_config("goldair_gpph_heater")
  306. error_code = cfg.primary_entity.find_dps("error")
  307. with self.assertRaises(TypeError):
  308. await error_code.async_set_value(mock_device, 1)
  309. def test_dps_values_returns_none_with_no_mapping(self):
  310. """
  311. Test that a dps with no mapping returns None as its possible values
  312. """
  313. mock_device = MagicMock()
  314. cfg = get_config("goldair_gpph_heater")
  315. temp = cfg.primary_entity.find_dps("current_temperature")
  316. self.assertIsNone(temp.values(mock_device))
  317. def test_config_returned(self):
  318. """Test that config file is returned by config"""
  319. cfg = get_config("kogan_switch")
  320. self.assertEqual(cfg.config, "smartplugv1.yaml")
  321. def test_float_matches_ints(self):
  322. """Test that the _typematch function matches int values to float dps"""
  323. self.assertTrue(_typematch(float, 1))
  324. def test_bytes_to_fmt_returns_string_for_unknown(self):
  325. """
  326. Test that the _bytes_to_fmt function parses unknown number of bytes
  327. as a string format.
  328. """
  329. self.assertEqual(_bytes_to_fmt(5), "5s")
  330. def test_deprecation(self):
  331. """Test that deprecation messages are picked from the config."""
  332. mock_device = MagicMock()
  333. mock_device.name = "Testing"
  334. mock_config = {"entity": "Test", "deprecated": "Passed"}
  335. cfg = TuyaEntityConfig(mock_device, mock_config)
  336. self.assertTrue(cfg.deprecated)
  337. self.assertEqual(
  338. cfg.deprecation_message,
  339. "The use of Test for Testing is deprecated and should be "
  340. "replaced by Passed.",
  341. )
  342. def test_format_with_none_defined(self):
  343. """Test that format returns None when there is none configured."""
  344. mock_entity = MagicMock()
  345. mock_config = {"id": "1", "name": "test", "type": "string"}
  346. cfg = TuyaDpsConfig(mock_entity, mock_config)
  347. self.assertIsNone(cfg.format)
  348. def test_decoding_base64(self):
  349. """Test that decoded_value works with base64 encoding."""
  350. mock_entity = MagicMock()
  351. mock_config = {"id": "1", "name": "test", "type": "base64"}
  352. mock_device = MagicMock()
  353. mock_device.get_property.return_value = "VGVzdA=="
  354. cfg = TuyaDpsConfig(mock_entity, mock_config)
  355. self.assertEqual(
  356. cfg.decoded_value(mock_device),
  357. bytes("Test", "utf-8"),
  358. )
  359. def test_decoding_unencoded(self):
  360. """Test that decoded_value returns the raw value when not encoded."""
  361. mock_entity = MagicMock()
  362. mock_config = {"id": "1", "name": "test", "type": "string"}
  363. mock_device = MagicMock()
  364. mock_device.get_property.return_value = "VGVzdA=="
  365. cfg = TuyaDpsConfig(mock_entity, mock_config)
  366. self.assertEqual(
  367. cfg.decoded_value(mock_device),
  368. "VGVzdA==",
  369. )
  370. def test_encoding_base64(self):
  371. """Test that encode_value works with base64."""
  372. mock_entity = MagicMock()
  373. mock_config = {"id": "1", "name": "test", "type": "base64"}
  374. cfg = TuyaDpsConfig(mock_entity, mock_config)
  375. self.assertEqual(cfg.encode_value(bytes("Test", "utf-8")), "VGVzdA==")
  376. def test_encoding_unencoded(self):
  377. """Test that encode_value works with base64."""
  378. mock_entity = MagicMock()
  379. mock_config = {"id": "1", "name": "test", "type": "string"}
  380. cfg = TuyaDpsConfig(mock_entity, mock_config)
  381. self.assertEqual(cfg.encode_value("Test"), "Test")
  382. def test_match_returns_false_on_errors_with_bitfield(self):
  383. """Test that TypeError and ValueError cause match to return False."""
  384. mock_entity = MagicMock()
  385. mock_config = {"id": "1", "name": "test", "type": "bitfield"}
  386. cfg = TuyaDpsConfig(mock_entity, mock_config)
  387. self.assertFalse(cfg._match(15, "not an integer"))
  388. def test_values_with_mirror(self):
  389. """Test that value_mirror redirects."""
  390. mock_entity = MagicMock()
  391. mock_config = {
  392. "id": "1",
  393. "type": "string",
  394. "name": "test",
  395. "mapping": [
  396. {"dps_val": "mirror", "value_mirror": "map_mirror"},
  397. {"dps_val": "plain", "value": "unmirrored"},
  398. ],
  399. }
  400. mock_map_config = {
  401. "id": "2",
  402. "type": "string",
  403. "name": "map_mirror",
  404. "mapping": [
  405. {"dps_val": "1", "value": "map_one"},
  406. {"dps_val": "2", "value": "map_two"},
  407. ],
  408. }
  409. mock_device = MagicMock()
  410. mock_device.get_property.return_value = "1"
  411. cfg = TuyaDpsConfig(mock_entity, mock_config)
  412. map = TuyaDpsConfig(mock_entity, mock_map_config)
  413. mock_entity.find_dps.return_value = map
  414. self.assertCountEqual(
  415. cfg.values(mock_device),
  416. ["unmirrored", "map_one", "map_two"],
  417. )
  418. def test_get_device_id(self):
  419. """Test that check if device id is correct"""
  420. self.assertEqual("my-device-id", get_device_id({"device_id": "my-device-id"}))
  421. self.assertEqual("sub-id", get_device_id({"device_cid": "sub-id"}))
  422. self.assertEqual("s", get_device_id({"device_id": "d", "device_cid": "s"}))
  423. # values gets very complex, with things like mappings within conditions
  424. # within mappings. I'd expect something like this was added with purpose,
  425. # but it isn't exercised by any of the existing unit tests.
  426. # value-mirror above is explained by the fact that the device it was
  427. # added for never worked properly, so was removed.
  428. def test_default_without_mapping(self):
  429. """Test that default returns None when there is no mapping"""
  430. mock_entity = MagicMock()
  431. mock_config = {"id": "1", "name": "test", "type": "string"}
  432. cfg = TuyaDpsConfig(mock_entity, mock_config)
  433. self.assertIsNone(cfg.default())