test_device_config.py 17 KB

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