test_device_config.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547
  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.
  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. for dp in entity.dps():
  227. self.assertIsNotNone(
  228. dp._config.get("id"), f"dp id missing from {e} in {cfg}"
  229. )
  230. self.assertIsNotNone(
  231. dp._config.get("type"), f"dp type missing from {e} in {cfg}"
  232. )
  233. self.assertIsNotNone(
  234. dp._config.get("name"), f"dp name missing from {e} in {cfg}"
  235. )
  236. extra.add(dp.name)
  237. expected = KNOWN_DPS.get(entity.entity)
  238. for rule in expected["required"]:
  239. self.assertTrue(
  240. self.dp_match(rule, functions, extra, known, True),
  241. f"{cfg} missing required {self.rule_broken_msg(rule)} in {e}",
  242. )
  243. for rule in expected["optional"]:
  244. self.assertTrue(
  245. self.dp_match(rule, functions, extra, known, False),
  246. f"{cfg} expecting {self.rule_broken_msg(rule)} in {e}",
  247. )
  248. # Check for potential typos in extra attributes
  249. known_extra = known - functions
  250. for attr in extra:
  251. for dp in known_extra:
  252. self.assertLess(
  253. fuzz.ratio(attr, dp),
  254. 85,
  255. f"Probable typo {attr} is too similar to {dp} in {cfg} {e}",
  256. )
  257. # Check that sensors with mapped values are of class enum and vice versa
  258. if entity.entity == "sensor":
  259. mock_device = MagicMock()
  260. sensor = TuyaLocalSensor(mock_device, entity)
  261. if sensor.options:
  262. self.assertEqual(
  263. entity.device_class,
  264. SensorDeviceClass.ENUM,
  265. f"{cfg} {e} has mapped values but does not have a device class of enum",
  266. )
  267. if entity.device_class == SensorDeviceClass.ENUM:
  268. self.assertIsNotNone(
  269. sensor.options,
  270. f"{cfg} {e} has a device class of enum, but has no mapped values",
  271. )
  272. def test_config_files_parse(self):
  273. """
  274. All configs should be parsable and meet certain criteria
  275. """
  276. for cfg in available_configs():
  277. entities = []
  278. parsed = TuyaDeviceConfig(cfg)
  279. # Check for error messages or unparsed config
  280. if isinstance(parsed, str) or isinstance(parsed._config, str):
  281. self.fail(f"unparsable yaml in {cfg}")
  282. self.assertIsNotNone(
  283. parsed._config.get("name"),
  284. f"name missing from {cfg}",
  285. )
  286. self.assertIsNotNone(
  287. parsed._config.get("primary_entity"),
  288. f"primary_entity missing from {cfg}",
  289. )
  290. self.check_entity(parsed.primary_entity, cfg)
  291. entities.append(parsed.primary_entity.config_id)
  292. secondary = False
  293. for entity in parsed.secondary_entities():
  294. secondary = True
  295. self.check_entity(entity, cfg)
  296. entities.append(entity.config_id)
  297. # check entities are unique
  298. self.assertCountEqual(entities, set(entities))
  299. # If there are no secondary entities, check that it is intended
  300. if not secondary:
  301. for key in parsed._config.keys():
  302. self.assertFalse(
  303. key.startswith("sec"),
  304. f"misspelled secondary_entities in {cfg}",
  305. )
  306. # Most of the device_config functionality is exercised during testing of
  307. # the various supported devices. These tests concentrate only on the gaps.
  308. def test_match_quality(self):
  309. """Test the match_quality function."""
  310. cfg = get_config("deta_fan")
  311. q = cfg.match_quality({**KOGAN_HEATER_PAYLOAD, "updated_at": 0})
  312. self.assertEqual(q, 0)
  313. q = cfg.match_quality({**GPPH_HEATER_PAYLOAD})
  314. self.assertEqual(q, 0)
  315. def test_entity_find_unknown_dps_fails(self):
  316. """Test that finding a dps that doesn't exist fails."""
  317. cfg = get_config("kogan_switch")
  318. non_existing = cfg.primary_entity.find_dps("missing")
  319. self.assertIsNone(non_existing)
  320. async def test_dps_async_set_readonly_value_fails(self):
  321. """Test that setting a readonly dps fails."""
  322. mock_device = MagicMock()
  323. cfg = get_config("goldair_gpph_heater")
  324. error_code = cfg.primary_entity.find_dps("error")
  325. with self.assertRaises(TypeError):
  326. await error_code.async_set_value(mock_device, 1)
  327. def test_dps_values_is_empty_with_no_mapping(self):
  328. """
  329. Test that a dps with no mapping returns None as its possible values
  330. """
  331. mock_device = MagicMock()
  332. cfg = get_config("goldair_gpph_heater")
  333. temp = cfg.primary_entity.find_dps("current_temperature")
  334. self.assertEqual(temp.values(mock_device), [])
  335. def test_config_returned(self):
  336. """Test that config file is returned by config"""
  337. cfg = get_config("kogan_switch")
  338. self.assertEqual(cfg.config, "smartplugv1.yaml")
  339. def test_float_matches_ints(self):
  340. """Test that the _typematch function matches int values to float dps"""
  341. self.assertTrue(_typematch(float, 1))
  342. def test_bytes_to_fmt_returns_string_for_unknown(self):
  343. """
  344. Test that the _bytes_to_fmt function parses unknown number of bytes
  345. as a string format.
  346. """
  347. self.assertEqual(_bytes_to_fmt(5), "5s")
  348. def test_deprecation(self):
  349. """Test that deprecation messages are picked from the config."""
  350. mock_device = MagicMock()
  351. mock_device.name = "Testing"
  352. mock_config = {"entity": "Test", "deprecated": "Passed"}
  353. cfg = TuyaEntityConfig(mock_device, mock_config)
  354. self.assertTrue(cfg.deprecated)
  355. self.assertEqual(
  356. cfg.deprecation_message,
  357. "The use of Test for Testing is deprecated and should be "
  358. "replaced by Passed.",
  359. )
  360. def test_format_with_none_defined(self):
  361. """Test that format returns None when there is none configured."""
  362. mock_entity = MagicMock()
  363. mock_config = {"id": "1", "name": "test", "type": "string"}
  364. cfg = TuyaDpsConfig(mock_entity, mock_config)
  365. self.assertIsNone(cfg.format)
  366. def test_decoding_base64(self):
  367. """Test that decoded_value works with base64 encoding."""
  368. mock_entity = MagicMock()
  369. mock_config = {"id": "1", "name": "test", "type": "base64"}
  370. mock_device = MagicMock()
  371. mock_device.get_property.return_value = "VGVzdA=="
  372. cfg = TuyaDpsConfig(mock_entity, mock_config)
  373. self.assertEqual(
  374. cfg.decoded_value(mock_device),
  375. bytes("Test", "utf-8"),
  376. )
  377. def test_decoding_hex(self):
  378. """Test that decoded_value works with hex encoding."""
  379. mock_entity = MagicMock()
  380. mock_config = {"id": "1", "name": "test", "type": "hex"}
  381. mock_device = MagicMock()
  382. mock_device.get_property.return_value = "babe"
  383. cfg = TuyaDpsConfig(mock_entity, mock_config)
  384. self.assertEqual(
  385. cfg.decoded_value(mock_device),
  386. b"\xba\xbe",
  387. )
  388. def test_decoding_unencoded(self):
  389. """Test that decoded_value returns the raw value when not encoded."""
  390. mock_entity = MagicMock()
  391. mock_config = {"id": "1", "name": "test", "type": "string"}
  392. mock_device = MagicMock()
  393. mock_device.get_property.return_value = "VGVzdA=="
  394. cfg = TuyaDpsConfig(mock_entity, mock_config)
  395. self.assertEqual(
  396. cfg.decoded_value(mock_device),
  397. "VGVzdA==",
  398. )
  399. def test_encoding_base64(self):
  400. """Test that encode_value works with base64."""
  401. mock_entity = MagicMock()
  402. mock_config = {"id": "1", "name": "test", "type": "base64"}
  403. cfg = TuyaDpsConfig(mock_entity, mock_config)
  404. self.assertEqual(cfg.encode_value(bytes("Test", "utf-8")), "VGVzdA==")
  405. def test_encoding_hex(self):
  406. """Test that encode_value works with base64."""
  407. mock_entity = MagicMock()
  408. mock_config = {"id": "1", "name": "test", "type": "hex"}
  409. cfg = TuyaDpsConfig(mock_entity, mock_config)
  410. self.assertEqual(cfg.encode_value(b"\xca\xfe"), "cafe")
  411. def test_encoding_unencoded(self):
  412. """Test that encode_value works with base64."""
  413. mock_entity = MagicMock()
  414. mock_config = {"id": "1", "name": "test", "type": "string"}
  415. cfg = TuyaDpsConfig(mock_entity, mock_config)
  416. self.assertEqual(cfg.encode_value("Test"), "Test")
  417. def test_match_returns_false_on_errors_with_bitfield(self):
  418. """Test that TypeError and ValueError cause match to return False."""
  419. mock_entity = MagicMock()
  420. mock_config = {"id": "1", "name": "test", "type": "bitfield"}
  421. cfg = TuyaDpsConfig(mock_entity, mock_config)
  422. self.assertFalse(cfg._match(15, "not an integer"))
  423. def test_values_with_mirror(self):
  424. """Test that value_mirror redirects."""
  425. mock_entity = MagicMock()
  426. mock_config = {
  427. "id": "1",
  428. "type": "string",
  429. "name": "test",
  430. "mapping": [
  431. {"dps_val": "mirror", "value_mirror": "map_mirror"},
  432. {"dps_val": "plain", "value": "unmirrored"},
  433. ],
  434. }
  435. mock_map_config = {
  436. "id": "2",
  437. "type": "string",
  438. "name": "map_mirror",
  439. "mapping": [
  440. {"dps_val": "1", "value": "map_one"},
  441. {"dps_val": "2", "value": "map_two"},
  442. ],
  443. }
  444. mock_device = MagicMock()
  445. mock_device.get_property.return_value = "1"
  446. cfg = TuyaDpsConfig(mock_entity, mock_config)
  447. map = TuyaDpsConfig(mock_entity, mock_map_config)
  448. mock_entity.find_dps.return_value = map
  449. self.assertCountEqual(
  450. cfg.values(mock_device),
  451. ["unmirrored", "map_one", "map_two"],
  452. )
  453. def test_get_device_id(self):
  454. """Test that check if device id is correct"""
  455. self.assertEqual("my-device-id", get_device_id({"device_id": "my-device-id"}))
  456. self.assertEqual("sub-id", get_device_id({"device_cid": "sub-id"}))
  457. self.assertEqual("s", get_device_id({"device_id": "d", "device_cid": "s"}))
  458. def test_getting_masked_hex(self):
  459. """Test that get_value works with masked hex encoding."""
  460. mock_entity = MagicMock()
  461. mock_config = {
  462. "id": "1",
  463. "name": "test",
  464. "type": "hex",
  465. "mapping": [
  466. {"mask": "ff00"},
  467. ],
  468. }
  469. mock_device = MagicMock()
  470. mock_device.get_property.return_value = "babe"
  471. cfg = TuyaDpsConfig(mock_entity, mock_config)
  472. self.assertEqual(
  473. cfg.get_value(mock_device),
  474. 0xBA,
  475. )
  476. def test_setting_masked_hex(self):
  477. """Test that get_values_to_set works with masked hex encoding."""
  478. mock_entity = MagicMock()
  479. mock_config = {
  480. "id": "1",
  481. "name": "test",
  482. "type": "hex",
  483. "mapping": [
  484. {"mask": "ff00"},
  485. ],
  486. }
  487. mock_device = MagicMock()
  488. mock_device.get_property.return_value = "babe"
  489. cfg = TuyaDpsConfig(mock_entity, mock_config)
  490. self.assertEqual(
  491. cfg.get_values_to_set(mock_device, 0xCA),
  492. {"1": "cabe"},
  493. )
  494. def test_default_without_mapping(self):
  495. """Test that default returns None when there is no mapping"""
  496. mock_entity = MagicMock()
  497. mock_config = {"id": "1", "name": "test", "type": "string"}
  498. cfg = TuyaDpsConfig(mock_entity, mock_config)
  499. self.assertIsNone(cfg.default)