test_device_config.py 25 KB

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