test_device_config.py 20 KB

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