test_device_config.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798
  1. """Test the config parser"""
  2. from unittest import IsolatedAsyncioTestCase
  3. from unittest.mock import MagicMock
  4. import voluptuous as vol
  5. from fuzzywuzzy import fuzz
  6. from homeassistant.components.sensor import SensorDeviceClass
  7. from custom_components.tuya_local.helpers.config import get_device_id
  8. from custom_components.tuya_local.helpers.device_config import (
  9. TuyaDeviceConfig,
  10. TuyaDpsConfig,
  11. TuyaEntityConfig,
  12. _bytes_to_fmt,
  13. _typematch,
  14. available_configs,
  15. get_config,
  16. )
  17. from custom_components.tuya_local.sensor import TuyaLocalSensor
  18. from .const import GPPH_HEATER_PAYLOAD, KOGAN_HEATER_PAYLOAD
  19. PRODUCT_SCHEMA = vol.Schema(
  20. {
  21. vol.Required("id"): str,
  22. vol.Optional("name"): str,
  23. }
  24. )
  25. CONDMAP_SCHEMA = vol.Schema(
  26. {
  27. vol.Optional("dps_val"): vol.Maybe(vol.Any(str, int, bool, list)),
  28. vol.Optional("value"): vol.Maybe(vol.Any(str, int, bool, float)),
  29. vol.Optional("value_redirect"): str,
  30. vol.Optional("value_mirror"): str,
  31. vol.Optional("available"): str,
  32. vol.Optional("range"): {
  33. vol.Required("min"): int,
  34. vol.Required("max"): int,
  35. },
  36. vol.Optional("target_range"): {
  37. vol.Required("min"): int,
  38. vol.Required("max"): int,
  39. },
  40. vol.Optional("scale"): vol.Any(int, float),
  41. vol.Optional("step"): vol.Any(int, float),
  42. vol.Optional("invert"): True,
  43. vol.Optional("unit"): str,
  44. vol.Optional("icon"): vol.Match(r"^mdi:"),
  45. vol.Optional("icon_priority"): int,
  46. vol.Optional("hidden"): True,
  47. vol.Optional("invalid"): True,
  48. vol.Optional("default"): True,
  49. }
  50. )
  51. COND_SCHEMA = CONDMAP_SCHEMA.extend(
  52. {
  53. vol.Required("dps_val"): vol.Maybe(vol.Any(str, int, bool, list)),
  54. vol.Optional("mapping"): [CONDMAP_SCHEMA],
  55. }
  56. )
  57. MAPPING_SCHEMA = CONDMAP_SCHEMA.extend(
  58. {
  59. vol.Optional("constraint"): str,
  60. vol.Optional("conditions"): [COND_SCHEMA],
  61. }
  62. )
  63. FORMAT_SCHEMA = vol.Schema(
  64. {
  65. vol.Required("name"): str,
  66. vol.Required("bytes"): int,
  67. vol.Optional("range"): {
  68. vol.Required("min"): int,
  69. vol.Required("max"): int,
  70. },
  71. }
  72. )
  73. DP_SCHEMA = vol.Schema(
  74. {
  75. vol.Required("id"): int,
  76. vol.Required("type"): vol.In(
  77. [
  78. "string",
  79. "integer",
  80. "boolean",
  81. "hex",
  82. "base64",
  83. "bitfield",
  84. "unixtime",
  85. "json",
  86. "utf16b64",
  87. ]
  88. ),
  89. vol.Required("name"): str,
  90. vol.Optional("range"): {
  91. vol.Required("min"): int,
  92. vol.Required("max"): int,
  93. },
  94. vol.Optional("unit"): str,
  95. vol.Optional("precision"): vol.Any(int, float),
  96. vol.Optional("class"): vol.In(
  97. [
  98. "measurement",
  99. "total",
  100. "total_increasing",
  101. ]
  102. ),
  103. vol.Optional("optional"): True,
  104. vol.Optional("persist"): False,
  105. vol.Optional("hidden"): True,
  106. vol.Optional("readonly"): True,
  107. vol.Optional("sensitive"): True,
  108. vol.Optional("force"): True,
  109. vol.Optional("icon_priority"): int,
  110. vol.Optional("mapping"): [MAPPING_SCHEMA],
  111. vol.Optional("format"): [FORMAT_SCHEMA],
  112. vol.Optional("mask"): str,
  113. vol.Optional("endianness"): vol.In(["little"]),
  114. }
  115. )
  116. ENTITY_SCHEMA = vol.Schema(
  117. {
  118. vol.Required("entity"): vol.In(
  119. [
  120. "alarm_control_panel",
  121. "binary_sensor",
  122. "button",
  123. "camera",
  124. "climate",
  125. "cover",
  126. "event",
  127. "fan",
  128. "humidifier",
  129. "lawn_mower",
  130. "light",
  131. "lock",
  132. "number",
  133. "remote",
  134. "select",
  135. "sensor",
  136. "siren",
  137. "switch",
  138. "vacuum",
  139. "valve",
  140. "water_heater",
  141. ]
  142. ),
  143. vol.Optional("name"): str,
  144. vol.Optional("class"): str,
  145. vol.Optional(vol.Or("translation_key", "translation_only_key")): str,
  146. vol.Optional("translation_placeholders"): dict[str, str],
  147. vol.Optional("category"): vol.In(["config", "diagnostic"]),
  148. vol.Optional("icon"): vol.Match(r"^mdi:"),
  149. vol.Optional("icon_priority"): int,
  150. vol.Optional("deprecated"): str,
  151. vol.Optional("mode"): vol.In(["box", "slider"]),
  152. vol.Required("dps"): [DP_SCHEMA],
  153. }
  154. )
  155. YAML_SCHEMA = vol.Schema(
  156. {
  157. vol.Required("name"): str,
  158. vol.Optional("legacy_type"): str,
  159. vol.Optional("products"): [PRODUCT_SCHEMA],
  160. vol.Required("primary_entity"): ENTITY_SCHEMA,
  161. vol.Optional("secondary_entities"): [ENTITY_SCHEMA],
  162. }
  163. )
  164. KNOWN_DPS = {
  165. "alarm_control_panel": {
  166. "required": ["alarm_state"],
  167. "optional": ["trigger"],
  168. },
  169. "binary_sensor": {"required": ["sensor"], "optional": []},
  170. "button": {"required": ["button"], "optional": []},
  171. "camera": {
  172. "required": [],
  173. "optional": ["switch", "motion_enable", "snapshot", "record"],
  174. },
  175. "climate": {
  176. "required": [],
  177. "optional": [
  178. "current_temperature",
  179. "current_humidity",
  180. "fan_mode",
  181. "humidity",
  182. "hvac_mode",
  183. "hvac_action",
  184. "min_temperature",
  185. "max_temperature",
  186. "preset_mode",
  187. "swing_mode",
  188. {
  189. "xor": [
  190. "temperature",
  191. {"and": ["target_temp_high", "target_temp_low"]},
  192. ]
  193. },
  194. "temperature_unit",
  195. ],
  196. },
  197. "cover": {
  198. "required": [{"or": ["control", "position"]}],
  199. "optional": [
  200. "current_position",
  201. "action",
  202. "open",
  203. "reversed",
  204. ],
  205. },
  206. "event": {"required": ["event"], "optional": []},
  207. "fan": {
  208. "required": [{"or": ["preset_mode", "speed"]}],
  209. "optional": ["switch", "oscillate", "direction"],
  210. },
  211. "humidifier": {
  212. "required": ["humidity"],
  213. "optional": ["switch", "mode", "current_humidity"],
  214. },
  215. "lawn_mower": {"required": ["activity", "command"], "optional": []},
  216. "light": {
  217. "required": [{"or": ["switch", "brightness", "effect"]}],
  218. "optional": ["color_mode", "color_temp", {"xor": ["rgbhsv", "named_color"]}],
  219. },
  220. "lock": {
  221. "required": [],
  222. "optional": [
  223. "lock",
  224. {"and": ["request_unlock", "approve_unlock"]},
  225. {"and": ["request_intercom", "approve_intercom"]},
  226. "unlock_fingerprint",
  227. "unlock_password",
  228. "unlock_temp_pwd",
  229. "unlock_dynamic_pwd",
  230. "unlock_offline_pwd",
  231. "unlock_card",
  232. "unlock_app",
  233. "unlock_key",
  234. "unlock_ble",
  235. "jammed",
  236. ],
  237. },
  238. "number": {
  239. "required": ["value"],
  240. "optional": ["unit", "minimum", "maximum"],
  241. },
  242. "remote": {
  243. "required": ["send"],
  244. "optional": ["receive"],
  245. },
  246. "select": {"required": ["option"], "optional": []},
  247. "sensor": {"required": ["sensor"], "optional": ["unit"]},
  248. "siren": {
  249. "required": [],
  250. "optional": ["tone", "volume", "duration", "switch"],
  251. },
  252. "switch": {"required": ["switch"], "optional": ["current_power_w"]},
  253. "vacuum": {
  254. "required": ["status"],
  255. "optional": [
  256. "command",
  257. "locate",
  258. "power",
  259. "activate",
  260. "battery",
  261. "direction_control",
  262. "error",
  263. "fan_speed",
  264. ],
  265. },
  266. "valve": {
  267. "required": ["valve"],
  268. "optional": [],
  269. },
  270. "water_heater": {
  271. "required": [],
  272. "optional": [
  273. "current_temperature",
  274. "operation_mode",
  275. "temperature",
  276. "temperature_unit",
  277. "min_temperature",
  278. "max_temperature",
  279. "away_mode",
  280. ],
  281. },
  282. }
  283. class TestDeviceConfig(IsolatedAsyncioTestCase):
  284. """Test the device config parser"""
  285. def test_can_find_config_files(self):
  286. """Test that the config files can be found by the parser."""
  287. found = False
  288. for cfg in available_configs():
  289. found = True
  290. break
  291. self.assertTrue(found)
  292. def dp_match(self, condition, accounted, unaccounted, known, required=False):
  293. if isinstance(condition, str):
  294. known.add(condition)
  295. if condition in unaccounted:
  296. unaccounted.remove(condition)
  297. accounted.add(condition)
  298. if required:
  299. return condition in accounted
  300. else:
  301. return True
  302. elif "and" in condition:
  303. return self.and_match(
  304. condition["and"], accounted, unaccounted, known, required
  305. )
  306. elif "or" in condition:
  307. return self.or_match(condition["or"], accounted, unaccounted, known)
  308. elif "xor" in condition:
  309. return self.xor_match(
  310. condition["xor"], accounted, unaccounted, known, required
  311. )
  312. else:
  313. self.fail(f"Unrecognized condition {condition}")
  314. def and_match(self, conditions, accounted, unaccounted, known, required):
  315. single_match = False
  316. all_match = True
  317. for cond in conditions:
  318. match = self.dp_match(cond, accounted, unaccounted, known, True)
  319. all_match = all_match and match
  320. single_match = single_match or match
  321. if required:
  322. return all_match
  323. else:
  324. return all_match == single_match
  325. def or_match(self, conditions, accounted, unaccounted, known):
  326. match = False
  327. # loop through all, to ensure they are transferred to accounted list
  328. for cond in conditions:
  329. match = match or self.dp_match(cond, accounted, unaccounted, known, True)
  330. return match
  331. def xor_match(self, conditions, accounted, unaccounted, known, required):
  332. prior_match = False
  333. for cond in conditions:
  334. match = self.dp_match(cond, accounted, unaccounted, known, True)
  335. if match and prior_match:
  336. return False
  337. prior_match = prior_match or match
  338. # If any matched, all should be considered matched
  339. # this bit only handles nesting "and" within "xor"
  340. if prior_match:
  341. for c in conditions:
  342. if isinstance(c, str):
  343. accounted.add(c)
  344. elif "and" in c:
  345. for c2 in c["and"]:
  346. if isinstance(c2, str):
  347. accounted.add(c2)
  348. return prior_match or not required
  349. def rule_broken_msg(self, rule):
  350. msg = ""
  351. if isinstance(rule, str):
  352. return f"{msg} {rule}"
  353. elif "and" in rule:
  354. msg = f"{msg} all of ["
  355. for sub in rule["and"]:
  356. msg = f"{msg} {self.rule_broken_msg(sub)}"
  357. return f"{msg} ]"
  358. elif "or" in rule:
  359. msg = f"{msg} at least one of ["
  360. for sub in rule["or"]:
  361. msg = f"{msg} {self.rule_broken_msg(sub)}"
  362. return f"{msg} ]"
  363. elif "xor" in rule:
  364. msg = f"{msg} only one of ["
  365. for sub in rule["xor"]:
  366. msg = f"{msg} {self.rule_broken_msg(sub)}"
  367. return f"{msg} ]"
  368. return "for reason unknown"
  369. def check_entity(self, entity, cfg):
  370. """
  371. Check that the entity has a dps list and each dps has an id,
  372. type and name, and any other consistency checks.
  373. """
  374. self.assertIsNotNone(
  375. entity._config.get("entity"), f"entity type missing in {cfg}"
  376. )
  377. e = entity.config_id
  378. self.assertIsNotNone(
  379. entity._config.get("dps"), f"dps missing from {e} in {cfg}"
  380. )
  381. functions = set()
  382. extra = set()
  383. known = set()
  384. redirects = set()
  385. # Basic checks of dps, and initialising of redirects and extras sets
  386. # for later checking
  387. for dp in entity.dps():
  388. self.assertIsNotNone(
  389. dp._config.get("id"), f"dp id missing from {e} in {cfg}"
  390. )
  391. self.assertIsNotNone(
  392. dp._config.get("type"), f"dp type missing from {e} in {cfg}"
  393. )
  394. self.assertIsNotNone(
  395. dp._config.get("name"), f"dp name missing from {e} in {cfg}"
  396. )
  397. extra.add(dp.name)
  398. mappings = dp._config.get("mapping", [])
  399. self.assertIsInstance(
  400. mappings,
  401. list,
  402. f"mapping is not a list in {cfg}; entity {e}, dp {dp.name}",
  403. )
  404. for m in mappings:
  405. conditions = m.get("conditions", [])
  406. self.assertIsInstance(
  407. conditions,
  408. list,
  409. f"conditions is not a list in {cfg}; entity {e}, dp {dp.name}",
  410. )
  411. for c in conditions:
  412. if c.get("value_redirect"):
  413. redirects.add(c.get("value_redirect"))
  414. if c.get("value_mirror"):
  415. redirects.add(c.get("value_mirror"))
  416. if m.get("value_redirect"):
  417. redirects.add(m.get("value_redirect"))
  418. if m.get("value_mirror"):
  419. redirects.add(m.get("value_mirror"))
  420. # Check redirects all exist
  421. for redirect in redirects:
  422. self.assertIn(redirect, extra, f"dp {redirect} missing from {e} in {cfg}")
  423. # Check dps that are required for this entity type all exist
  424. expected = KNOWN_DPS.get(entity.entity)
  425. for rule in expected["required"]:
  426. self.assertTrue(
  427. self.dp_match(rule, functions, extra, known, True),
  428. f"{cfg} missing required {self.rule_broken_msg(rule)} in {e}",
  429. )
  430. for rule in expected["optional"]:
  431. self.assertTrue(
  432. self.dp_match(rule, functions, extra, known, False),
  433. f"{cfg} expecting {self.rule_broken_msg(rule)} in {e}",
  434. )
  435. # Check for potential typos in extra attributes
  436. known_extra = known - functions
  437. for attr in extra:
  438. for dp in known_extra:
  439. self.assertLess(
  440. fuzz.ratio(attr, dp),
  441. 85,
  442. f"Probable typo {attr} is too similar to {dp} in {cfg} {e}",
  443. )
  444. # Check that sensors with mapped values are of class enum and vice versa
  445. if entity.entity == "sensor":
  446. mock_device = MagicMock()
  447. sensor = TuyaLocalSensor(mock_device, entity)
  448. if sensor.options:
  449. self.assertEqual(
  450. entity.device_class,
  451. SensorDeviceClass.ENUM,
  452. f"{cfg} {e} has mapped values but does not have a device class of enum",
  453. )
  454. if entity.device_class == SensorDeviceClass.ENUM:
  455. self.assertIsNotNone(
  456. sensor.options,
  457. f"{cfg} {e} has a device class of enum, but has no mapped values",
  458. )
  459. def test_config_files_parse(self):
  460. """
  461. All configs should be parsable and meet certain criteria
  462. """
  463. for cfg in available_configs():
  464. entities = []
  465. parsed = TuyaDeviceConfig(cfg)
  466. # Check for error messages or unparsed config
  467. if isinstance(parsed, str) or isinstance(parsed._config, str):
  468. self.fail(f"unparsable yaml in {cfg}")
  469. try:
  470. YAML_SCHEMA(parsed._config)
  471. except vol.MultipleInvalid as e:
  472. self.fail(f"Validation error in {cfg}: {e}")
  473. self.assertIsNotNone(
  474. parsed._config.get("name"),
  475. f"name missing from {cfg}",
  476. )
  477. self.assertIsNotNone(
  478. parsed._config.get("primary_entity"),
  479. f"primary_entity missing from {cfg}",
  480. )
  481. count = 0
  482. for entity in parsed.all_entities():
  483. self.check_entity(entity, cfg)
  484. entities.append(entity.config_id)
  485. count += 1
  486. assert count > 0, f"No entities found in {cfg}"
  487. # check entities are unique
  488. self.assertCountEqual(
  489. entities,
  490. set(entities),
  491. f"Duplicate entities in {cfg}",
  492. )
  493. # If there are no secondary entities, check that it is intended
  494. if count == 1:
  495. for key in parsed._config.keys():
  496. self.assertFalse(
  497. key.startswith("sec"),
  498. f"misspelled secondary_entities in {cfg}",
  499. )
  500. def test_configs_can_be_matched(self):
  501. """Test that the config files can be matched to a device."""
  502. for cfg in available_configs():
  503. optional = set()
  504. required = set()
  505. parsed = TuyaDeviceConfig(cfg)
  506. products = parsed._config.get("products")
  507. # Configs with a product list can be matched by product id
  508. if products:
  509. p_match = False
  510. for p in products:
  511. if p.get("id"):
  512. p_match = True
  513. if p_match:
  514. continue
  515. for entity in parsed.all_entities():
  516. for dp in entity.dps():
  517. if dp.optional:
  518. optional.add(dp.id)
  519. else:
  520. required.add(dp.id)
  521. self.assertGreater(
  522. len(required),
  523. 0,
  524. msg=f"No required dps found in {cfg}",
  525. )
  526. for dp in required:
  527. self.assertNotIn(
  528. dp,
  529. optional,
  530. msg=f"Optional dp {dp} is required in {cfg}",
  531. )
  532. # Most of the device_config functionality is exercised during testing of
  533. # the various supported devices. These tests concentrate only on the gaps.
  534. def test_match_quality(self):
  535. """Test the match_quality function."""
  536. cfg = get_config("deta_fan")
  537. q = cfg.match_quality({**KOGAN_HEATER_PAYLOAD, "updated_at": 0})
  538. self.assertEqual(q, 0)
  539. q = cfg.match_quality({**GPPH_HEATER_PAYLOAD})
  540. self.assertEqual(q, 0)
  541. def test_entity_find_unknown_dps_fails(self):
  542. """Test that finding a dps that doesn't exist fails."""
  543. cfg = get_config("kogan_switch")
  544. for entity in cfg.all_entities():
  545. non_existing = entity.find_dps("missing")
  546. self.assertIsNone(non_existing)
  547. break
  548. async def test_dps_async_set_readonly_value_fails(self):
  549. """Test that setting a readonly dps fails."""
  550. mock_device = MagicMock()
  551. cfg = get_config("aquatech_x6_water_heater")
  552. for entity in cfg.all_entities():
  553. if entity.entity == "climate":
  554. temp = entity.find_dps("temperature")
  555. with self.assertRaises(TypeError):
  556. await temp.async_set_value(mock_device, 20)
  557. break
  558. def test_dps_values_is_empty_with_no_mapping(self):
  559. """
  560. Test that a dps with no mapping returns empty list for possible values
  561. """
  562. mock_device = MagicMock()
  563. cfg = get_config("goldair_gpph_heater")
  564. for entity in cfg.all_entities():
  565. if entity.entity == "climate":
  566. temp = entity.find_dps("temperature")
  567. self.assertEqual(temp.values(mock_device), [])
  568. break
  569. def test_config_returned(self):
  570. """Test that config file is returned by config"""
  571. cfg = get_config("kogan_switch")
  572. self.assertEqual(cfg.config, "smartplugv1.yaml")
  573. def test_float_matches_ints(self):
  574. """Test that the _typematch function matches int values to float dps"""
  575. self.assertTrue(_typematch(float, 1))
  576. def test_bytes_to_fmt_returns_string_for_unknown(self):
  577. """
  578. Test that the _bytes_to_fmt function parses unknown number of bytes
  579. as a string format.
  580. """
  581. self.assertEqual(_bytes_to_fmt(5), "5s")
  582. def test_deprecation(self):
  583. """Test that deprecation messages are picked from the config."""
  584. mock_device = MagicMock()
  585. mock_device.name = "Testing"
  586. mock_config = {"entity": "Test", "deprecated": "Passed"}
  587. cfg = TuyaEntityConfig(mock_device, mock_config)
  588. self.assertTrue(cfg.deprecated)
  589. self.assertEqual(
  590. cfg.deprecation_message,
  591. "The use of Test for Testing is deprecated and should be "
  592. "replaced by Passed.",
  593. )
  594. def test_format_with_none_defined(self):
  595. """Test that format returns None when there is none configured."""
  596. mock_entity = MagicMock()
  597. mock_config = {"id": "1", "name": "test", "type": "string"}
  598. cfg = TuyaDpsConfig(mock_entity, mock_config)
  599. self.assertIsNone(cfg.format)
  600. def test_decoding_base64(self):
  601. """Test that decoded_value works with base64 encoding."""
  602. mock_entity = MagicMock()
  603. mock_config = {"id": "1", "name": "test", "type": "base64"}
  604. mock_device = MagicMock()
  605. mock_device.get_property.return_value = "VGVzdA=="
  606. cfg = TuyaDpsConfig(mock_entity, mock_config)
  607. self.assertEqual(
  608. cfg.decoded_value(mock_device),
  609. bytes("Test", "utf-8"),
  610. )
  611. def test_decoding_hex(self):
  612. """Test that decoded_value works with hex encoding."""
  613. mock_entity = MagicMock()
  614. mock_config = {"id": "1", "name": "test", "type": "hex"}
  615. mock_device = MagicMock()
  616. mock_device.get_property.return_value = "babe"
  617. cfg = TuyaDpsConfig(mock_entity, mock_config)
  618. self.assertEqual(
  619. cfg.decoded_value(mock_device),
  620. b"\xba\xbe",
  621. )
  622. def test_decoding_unencoded(self):
  623. """Test that decoded_value returns the raw value when not encoded."""
  624. mock_entity = MagicMock()
  625. mock_config = {"id": "1", "name": "test", "type": "string"}
  626. mock_device = MagicMock()
  627. mock_device.get_property.return_value = "VGVzdA=="
  628. cfg = TuyaDpsConfig(mock_entity, mock_config)
  629. self.assertEqual(
  630. cfg.decoded_value(mock_device),
  631. "VGVzdA==",
  632. )
  633. def test_encoding_base64(self):
  634. """Test that encode_value works with base64."""
  635. mock_entity = MagicMock()
  636. mock_config = {"id": "1", "name": "test", "type": "base64"}
  637. cfg = TuyaDpsConfig(mock_entity, mock_config)
  638. self.assertEqual(cfg.encode_value(bytes("Test", "utf-8")), "VGVzdA==")
  639. def test_encoding_hex(self):
  640. """Test that encode_value works with base64."""
  641. mock_entity = MagicMock()
  642. mock_config = {"id": "1", "name": "test", "type": "hex"}
  643. cfg = TuyaDpsConfig(mock_entity, mock_config)
  644. self.assertEqual(cfg.encode_value(b"\xca\xfe"), "cafe")
  645. def test_encoding_unencoded(self):
  646. """Test that encode_value works with base64."""
  647. mock_entity = MagicMock()
  648. mock_config = {"id": "1", "name": "test", "type": "string"}
  649. cfg = TuyaDpsConfig(mock_entity, mock_config)
  650. self.assertEqual(cfg.encode_value("Test"), "Test")
  651. def test_match_returns_false_on_errors_with_bitfield(self):
  652. """Test that TypeError and ValueError cause match to return False."""
  653. mock_entity = MagicMock()
  654. mock_config = {"id": "1", "name": "test", "type": "bitfield"}
  655. cfg = TuyaDpsConfig(mock_entity, mock_config)
  656. self.assertFalse(cfg._match(15, "not an integer"))
  657. def test_values_with_mirror(self):
  658. """Test that value_mirror redirects."""
  659. mock_entity = MagicMock()
  660. mock_config = {
  661. "id": "1",
  662. "type": "string",
  663. "name": "test",
  664. "mapping": [
  665. {"dps_val": "mirror", "value_mirror": "map_mirror"},
  666. {"dps_val": "plain", "value": "unmirrored"},
  667. ],
  668. }
  669. mock_map_config = {
  670. "id": "2",
  671. "type": "string",
  672. "name": "map_mirror",
  673. "mapping": [
  674. {"dps_val": "1", "value": "map_one"},
  675. {"dps_val": "2", "value": "map_two"},
  676. ],
  677. }
  678. mock_device = MagicMock()
  679. mock_device.get_property.return_value = "1"
  680. cfg = TuyaDpsConfig(mock_entity, mock_config)
  681. map = TuyaDpsConfig(mock_entity, mock_map_config)
  682. mock_entity.find_dps.return_value = map
  683. self.assertCountEqual(
  684. cfg.values(mock_device),
  685. ["unmirrored", "map_one", "map_two"],
  686. )
  687. def test_get_device_id(self):
  688. """Test that check if device id is correct"""
  689. self.assertEqual("my-device-id", get_device_id({"device_id": "my-device-id"}))
  690. self.assertEqual("sub-id", get_device_id({"device_cid": "sub-id"}))
  691. self.assertEqual("s", get_device_id({"device_id": "d", "device_cid": "s"}))
  692. def test_getting_masked_hex(self):
  693. """Test that get_value works with masked hex encoding."""
  694. mock_entity = MagicMock()
  695. mock_config = {
  696. "id": "1",
  697. "name": "test",
  698. "type": "hex",
  699. "mask": "ff00",
  700. }
  701. mock_device = MagicMock()
  702. mock_device.get_property.return_value = "babe"
  703. cfg = TuyaDpsConfig(mock_entity, mock_config)
  704. self.assertEqual(
  705. cfg.get_value(mock_device),
  706. 0xBA,
  707. )
  708. def test_setting_masked_hex(self):
  709. """Test that get_values_to_set works with masked hex encoding."""
  710. mock_entity = MagicMock()
  711. mock_config = {
  712. "id": "1",
  713. "name": "test",
  714. "type": "hex",
  715. "mask": "ff00",
  716. }
  717. mock_device = MagicMock()
  718. mock_device.get_property.return_value = "babe"
  719. cfg = TuyaDpsConfig(mock_entity, mock_config)
  720. self.assertEqual(
  721. cfg.get_values_to_set(mock_device, 0xCA),
  722. {"1": "cabe"},
  723. )
  724. def test_default_without_mapping(self):
  725. """Test that default returns None when there is no mapping"""
  726. mock_entity = MagicMock()
  727. mock_config = {"id": "1", "name": "test", "type": "string"}
  728. cfg = TuyaDpsConfig(mock_entity, mock_config)
  729. self.assertIsNone(cfg.default)
  730. def test_matching_with_product_id(self):
  731. """Test that matching with product id works"""
  732. cfg = get_config("smartplugv1")
  733. self.assertTrue(cfg.matches({}, ["37mnhia3pojleqfh"]))
  734. def test_matched_product_id_with_conflict_rejected(self):
  735. """Test that matching with product id fails when there is a conflict"""
  736. cfg = get_config("smartplugv1")
  737. self.assertFalse(cfg.matches({"1": "wrong_type"}, ["37mnhia3pojleqfh"]))