test_device_config.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774
  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("mask"): str,
  43. vol.Optional("endianness"): str,
  44. vol.Optional("invert"): True,
  45. vol.Optional("unit"): str,
  46. vol.Optional("icon"): vol.Match(r"^mdi:"),
  47. vol.Optional("icon_priority"): int,
  48. vol.Optional("hidden"): True,
  49. vol.Optional("invalid"): True,
  50. vol.Optional("default"): True,
  51. }
  52. )
  53. COND_SCHEMA = CONDMAP_SCHEMA.extend(
  54. {
  55. vol.Required("dps_val"): vol.Maybe(vol.Any(str, int, bool, list)),
  56. vol.Optional("mapping"): [CONDMAP_SCHEMA],
  57. }
  58. )
  59. MAPPING_SCHEMA = CONDMAP_SCHEMA.extend(
  60. {
  61. vol.Optional("constraint"): str,
  62. vol.Optional("conditions"): [COND_SCHEMA],
  63. }
  64. )
  65. FORMAT_SCHEMA = vol.Schema(
  66. {
  67. vol.Required("name"): str,
  68. vol.Required("bytes"): int,
  69. vol.Optional("range"): {
  70. vol.Required("min"): int,
  71. vol.Required("max"): int,
  72. },
  73. }
  74. )
  75. DP_SCHEMA = vol.Schema(
  76. {
  77. vol.Required("id"): int,
  78. vol.Required("type"): vol.In(
  79. [
  80. "string",
  81. "integer",
  82. "boolean",
  83. "hex",
  84. "base64",
  85. "bitfield",
  86. "unixtime",
  87. "json",
  88. "utf16b64",
  89. ]
  90. ),
  91. vol.Required("name"): str,
  92. vol.Optional("range"): {
  93. vol.Required("min"): int,
  94. vol.Required("max"): int,
  95. },
  96. vol.Optional("unit"): str,
  97. vol.Optional("precision"): vol.Any(int, float),
  98. vol.Optional("class"): vol.In(
  99. [
  100. "measurement",
  101. "total",
  102. "total_increasing",
  103. ]
  104. ),
  105. vol.Optional("optional"): True,
  106. vol.Optional("persist"): False,
  107. vol.Optional("hidden"): True,
  108. vol.Optional("readonly"): True,
  109. vol.Optional("sensitive"): True,
  110. vol.Optional("force"): True,
  111. vol.Optional("icon_priority"): int,
  112. vol.Optional("mapping"): [MAPPING_SCHEMA],
  113. vol.Optional("format"): [FORMAT_SCHEMA],
  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. self.check_entity(parsed.primary_entity, cfg)
  482. entities.append(parsed.primary_entity.config_id)
  483. secondary = False
  484. for entity in parsed.secondary_entities():
  485. secondary = True
  486. self.check_entity(entity, cfg)
  487. entities.append(entity.config_id)
  488. # check entities are unique
  489. self.assertCountEqual(
  490. entities,
  491. set(entities),
  492. f"Duplicate entities in {cfg}",
  493. )
  494. # If there are no secondary entities, check that it is intended
  495. if not secondary:
  496. for key in parsed._config.keys():
  497. self.assertFalse(
  498. key.startswith("sec"),
  499. f"misspelled secondary_entities in {cfg}",
  500. )
  501. def test_configs_can_be_matched(self):
  502. """Test that the config files can be matched to a device."""
  503. for cfg in available_configs():
  504. optional = set()
  505. required = set()
  506. parsed = TuyaDeviceConfig(cfg)
  507. for entity in parsed.all_entities():
  508. for dp in entity.dps():
  509. if dp.optional:
  510. optional.add(dp.id)
  511. else:
  512. required.add(dp.id)
  513. self.assertGreater(
  514. len(required),
  515. 0,
  516. msg=f"No required dps found in {cfg}",
  517. )
  518. for dp in required:
  519. self.assertNotIn(
  520. dp,
  521. optional,
  522. msg=f"Optional dp {dp} is required in {cfg}",
  523. )
  524. # Most of the device_config functionality is exercised during testing of
  525. # the various supported devices. These tests concentrate only on the gaps.
  526. def test_match_quality(self):
  527. """Test the match_quality function."""
  528. cfg = get_config("deta_fan")
  529. q = cfg.match_quality({**KOGAN_HEATER_PAYLOAD, "updated_at": 0})
  530. self.assertEqual(q, 0)
  531. q = cfg.match_quality({**GPPH_HEATER_PAYLOAD})
  532. self.assertEqual(q, 0)
  533. def test_entity_find_unknown_dps_fails(self):
  534. """Test that finding a dps that doesn't exist fails."""
  535. cfg = get_config("kogan_switch")
  536. non_existing = cfg.primary_entity.find_dps("missing")
  537. self.assertIsNone(non_existing)
  538. async def test_dps_async_set_readonly_value_fails(self):
  539. """Test that setting a readonly dps fails."""
  540. mock_device = MagicMock()
  541. cfg = get_config("aquatech_x6_water_heater")
  542. temp = cfg.primary_entity.find_dps("temperature")
  543. with self.assertRaises(TypeError):
  544. await temp.async_set_value(mock_device, 20)
  545. def test_dps_values_is_empty_with_no_mapping(self):
  546. """
  547. Test that a dps with no mapping returns None as its possible values
  548. """
  549. mock_device = MagicMock()
  550. cfg = get_config("goldair_gpph_heater")
  551. temp = cfg.primary_entity.find_dps("current_temperature")
  552. self.assertEqual(temp.values(mock_device), [])
  553. def test_config_returned(self):
  554. """Test that config file is returned by config"""
  555. cfg = get_config("kogan_switch")
  556. self.assertEqual(cfg.config, "smartplugv1.yaml")
  557. def test_float_matches_ints(self):
  558. """Test that the _typematch function matches int values to float dps"""
  559. self.assertTrue(_typematch(float, 1))
  560. def test_bytes_to_fmt_returns_string_for_unknown(self):
  561. """
  562. Test that the _bytes_to_fmt function parses unknown number of bytes
  563. as a string format.
  564. """
  565. self.assertEqual(_bytes_to_fmt(5), "5s")
  566. def test_deprecation(self):
  567. """Test that deprecation messages are picked from the config."""
  568. mock_device = MagicMock()
  569. mock_device.name = "Testing"
  570. mock_config = {"entity": "Test", "deprecated": "Passed"}
  571. cfg = TuyaEntityConfig(mock_device, mock_config)
  572. self.assertTrue(cfg.deprecated)
  573. self.assertEqual(
  574. cfg.deprecation_message,
  575. "The use of Test for Testing is deprecated and should be "
  576. "replaced by Passed.",
  577. )
  578. def test_format_with_none_defined(self):
  579. """Test that format returns None when there is none configured."""
  580. mock_entity = MagicMock()
  581. mock_config = {"id": "1", "name": "test", "type": "string"}
  582. cfg = TuyaDpsConfig(mock_entity, mock_config)
  583. self.assertIsNone(cfg.format)
  584. def test_decoding_base64(self):
  585. """Test that decoded_value works with base64 encoding."""
  586. mock_entity = MagicMock()
  587. mock_config = {"id": "1", "name": "test", "type": "base64"}
  588. mock_device = MagicMock()
  589. mock_device.get_property.return_value = "VGVzdA=="
  590. cfg = TuyaDpsConfig(mock_entity, mock_config)
  591. self.assertEqual(
  592. cfg.decoded_value(mock_device),
  593. bytes("Test", "utf-8"),
  594. )
  595. def test_decoding_hex(self):
  596. """Test that decoded_value works with hex encoding."""
  597. mock_entity = MagicMock()
  598. mock_config = {"id": "1", "name": "test", "type": "hex"}
  599. mock_device = MagicMock()
  600. mock_device.get_property.return_value = "babe"
  601. cfg = TuyaDpsConfig(mock_entity, mock_config)
  602. self.assertEqual(
  603. cfg.decoded_value(mock_device),
  604. b"\xba\xbe",
  605. )
  606. def test_decoding_unencoded(self):
  607. """Test that decoded_value returns the raw value when not encoded."""
  608. mock_entity = MagicMock()
  609. mock_config = {"id": "1", "name": "test", "type": "string"}
  610. mock_device = MagicMock()
  611. mock_device.get_property.return_value = "VGVzdA=="
  612. cfg = TuyaDpsConfig(mock_entity, mock_config)
  613. self.assertEqual(
  614. cfg.decoded_value(mock_device),
  615. "VGVzdA==",
  616. )
  617. def test_encoding_base64(self):
  618. """Test that encode_value works with base64."""
  619. mock_entity = MagicMock()
  620. mock_config = {"id": "1", "name": "test", "type": "base64"}
  621. cfg = TuyaDpsConfig(mock_entity, mock_config)
  622. self.assertEqual(cfg.encode_value(bytes("Test", "utf-8")), "VGVzdA==")
  623. def test_encoding_hex(self):
  624. """Test that encode_value works with base64."""
  625. mock_entity = MagicMock()
  626. mock_config = {"id": "1", "name": "test", "type": "hex"}
  627. cfg = TuyaDpsConfig(mock_entity, mock_config)
  628. self.assertEqual(cfg.encode_value(b"\xca\xfe"), "cafe")
  629. def test_encoding_unencoded(self):
  630. """Test that encode_value works with base64."""
  631. mock_entity = MagicMock()
  632. mock_config = {"id": "1", "name": "test", "type": "string"}
  633. cfg = TuyaDpsConfig(mock_entity, mock_config)
  634. self.assertEqual(cfg.encode_value("Test"), "Test")
  635. def test_match_returns_false_on_errors_with_bitfield(self):
  636. """Test that TypeError and ValueError cause match to return False."""
  637. mock_entity = MagicMock()
  638. mock_config = {"id": "1", "name": "test", "type": "bitfield"}
  639. cfg = TuyaDpsConfig(mock_entity, mock_config)
  640. self.assertFalse(cfg._match(15, "not an integer"))
  641. def test_values_with_mirror(self):
  642. """Test that value_mirror redirects."""
  643. mock_entity = MagicMock()
  644. mock_config = {
  645. "id": "1",
  646. "type": "string",
  647. "name": "test",
  648. "mapping": [
  649. {"dps_val": "mirror", "value_mirror": "map_mirror"},
  650. {"dps_val": "plain", "value": "unmirrored"},
  651. ],
  652. }
  653. mock_map_config = {
  654. "id": "2",
  655. "type": "string",
  656. "name": "map_mirror",
  657. "mapping": [
  658. {"dps_val": "1", "value": "map_one"},
  659. {"dps_val": "2", "value": "map_two"},
  660. ],
  661. }
  662. mock_device = MagicMock()
  663. mock_device.get_property.return_value = "1"
  664. cfg = TuyaDpsConfig(mock_entity, mock_config)
  665. map = TuyaDpsConfig(mock_entity, mock_map_config)
  666. mock_entity.find_dps.return_value = map
  667. self.assertCountEqual(
  668. cfg.values(mock_device),
  669. ["unmirrored", "map_one", "map_two"],
  670. )
  671. def test_get_device_id(self):
  672. """Test that check if device id is correct"""
  673. self.assertEqual("my-device-id", get_device_id({"device_id": "my-device-id"}))
  674. self.assertEqual("sub-id", get_device_id({"device_cid": "sub-id"}))
  675. self.assertEqual("s", get_device_id({"device_id": "d", "device_cid": "s"}))
  676. def test_getting_masked_hex(self):
  677. """Test that get_value works with masked hex encoding."""
  678. mock_entity = MagicMock()
  679. mock_config = {
  680. "id": "1",
  681. "name": "test",
  682. "type": "hex",
  683. "mapping": [
  684. {"mask": "ff00"},
  685. ],
  686. }
  687. mock_device = MagicMock()
  688. mock_device.get_property.return_value = "babe"
  689. cfg = TuyaDpsConfig(mock_entity, mock_config)
  690. self.assertEqual(
  691. cfg.get_value(mock_device),
  692. 0xBA,
  693. )
  694. def test_setting_masked_hex(self):
  695. """Test that get_values_to_set works with masked hex encoding."""
  696. mock_entity = MagicMock()
  697. mock_config = {
  698. "id": "1",
  699. "name": "test",
  700. "type": "hex",
  701. "mapping": [
  702. {"mask": "ff00"},
  703. ],
  704. }
  705. mock_device = MagicMock()
  706. mock_device.get_property.return_value = "babe"
  707. cfg = TuyaDpsConfig(mock_entity, mock_config)
  708. self.assertEqual(
  709. cfg.get_values_to_set(mock_device, 0xCA),
  710. {"1": "cabe"},
  711. )
  712. def test_default_without_mapping(self):
  713. """Test that default returns None when there is no mapping"""
  714. mock_entity = MagicMock()
  715. mock_config = {"id": "1", "name": "test", "type": "string"}
  716. cfg = TuyaDpsConfig(mock_entity, mock_config)
  717. self.assertIsNone(cfg.default)