test_device_config.py 17 KB

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