test_device_config.py 27 KB

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