test_device_config.py 20 KB

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