test_device_config.py 17 KB

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