test_device_config.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734
  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. "valve",
  131. "water_heater",
  132. ]
  133. ),
  134. vol.Optional("name"): str,
  135. vol.Optional("class"): str,
  136. vol.Optional(vol.Or("translation_key", "translation_only_key")): str,
  137. vol.Optional("category"): vol.In(["config", "diagnostic"]),
  138. vol.Optional("icon"): vol.Match(r"^mdi:"),
  139. vol.Optional("icon_priority"): int,
  140. vol.Optional("deprecated"): str,
  141. vol.Optional("mode"): vol.In(["box", "slider"]),
  142. vol.Required("dps"): [DP_SCHEMA],
  143. }
  144. )
  145. YAML_SCHEMA = vol.Schema(
  146. {
  147. vol.Required("name"): str,
  148. vol.Optional("legacy_type"): str,
  149. vol.Optional("products"): [PRODUCT_SCHEMA],
  150. vol.Required("primary_entity"): ENTITY_SCHEMA,
  151. vol.Optional("secondary_entities"): [ENTITY_SCHEMA],
  152. }
  153. )
  154. KNOWN_DPS = {
  155. "alarm_control_panel": {
  156. "required": ["alarm_state"],
  157. "optional": ["trigger"],
  158. },
  159. "binary_sensor": {"required": ["sensor"], "optional": []},
  160. "button": {"required": ["button"], "optional": []},
  161. "camera": {
  162. "required": [],
  163. "optional": ["switch", "motion_enable", "snapshot", "record"],
  164. },
  165. "climate": {
  166. "required": [],
  167. "optional": [
  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. "valve": {
  257. "required": ["valve"],
  258. "optional": [],
  259. },
  260. "water_heater": {
  261. "required": [],
  262. "optional": [
  263. "current_temperature",
  264. "operation_mode",
  265. "temperature",
  266. "temperature_unit",
  267. "min_temperature",
  268. "max_temperature",
  269. "away_mode",
  270. ],
  271. },
  272. }
  273. class TestDeviceConfig(IsolatedAsyncioTestCase):
  274. """Test the device config parser"""
  275. def test_can_find_config_files(self):
  276. """Test that the config files can be found by the parser."""
  277. found = False
  278. for cfg in available_configs():
  279. found = True
  280. break
  281. self.assertTrue(found)
  282. def dp_match(self, condition, accounted, unaccounted, known, required=False):
  283. if isinstance(condition, str):
  284. known.add(condition)
  285. if condition in unaccounted:
  286. unaccounted.remove(condition)
  287. accounted.add(condition)
  288. if required:
  289. return condition in accounted
  290. else:
  291. return True
  292. elif "and" in condition:
  293. return self.and_match(
  294. condition["and"], accounted, unaccounted, known, required
  295. )
  296. elif "or" in condition:
  297. return self.or_match(condition["or"], accounted, unaccounted, known)
  298. elif "xor" in condition:
  299. return self.xor_match(
  300. condition["xor"], accounted, unaccounted, known, required
  301. )
  302. else:
  303. self.fail(f"Unrecognized condition {condition}")
  304. def and_match(self, conditions, accounted, unaccounted, known, required):
  305. single_match = False
  306. all_match = True
  307. for cond in conditions:
  308. match = self.dp_match(cond, accounted, unaccounted, known, True)
  309. all_match = all_match and match
  310. single_match = single_match or match
  311. if required:
  312. return all_match
  313. else:
  314. return all_match == single_match
  315. def or_match(self, conditions, accounted, unaccounted, known):
  316. match = False
  317. # loop through all, to ensure they are transferred to accounted list
  318. for cond in conditions:
  319. match = match or self.dp_match(cond, accounted, unaccounted, known, True)
  320. return match
  321. def xor_match(self, conditions, accounted, unaccounted, known, required):
  322. prior_match = False
  323. for cond in conditions:
  324. match = self.dp_match(cond, accounted, unaccounted, known, True)
  325. if match and prior_match:
  326. return False
  327. prior_match = prior_match or match
  328. # If any matched, all should be considered matched
  329. # this bit only handles nesting "and" within "xor"
  330. if prior_match:
  331. for c in conditions:
  332. if isinstance(c, str):
  333. accounted.add(c)
  334. elif "and" in c:
  335. for c2 in c["and"]:
  336. if isinstance(c2, str):
  337. accounted.add(c2)
  338. return prior_match or not required
  339. def rule_broken_msg(self, rule):
  340. msg = ""
  341. if isinstance(rule, str):
  342. return f"{msg} {rule}"
  343. elif "and" in rule:
  344. msg = f"{msg} all of ["
  345. for sub in rule["and"]:
  346. msg = f"{msg} {self.rule_broken_msg(sub)}"
  347. return f"{msg} ]"
  348. elif "or" in rule:
  349. msg = f"{msg} at least one of ["
  350. for sub in rule["or"]:
  351. msg = f"{msg} {self.rule_broken_msg(sub)}"
  352. return f"{msg} ]"
  353. elif "xor" in rule:
  354. msg = f"{msg} only one of ["
  355. for sub in rule["xor"]:
  356. msg = f"{msg} {self.rule_broken_msg(sub)}"
  357. return f"{msg} ]"
  358. return "for reason unknown"
  359. def check_entity(self, entity, cfg):
  360. """
  361. Check that the entity has a dps list and each dps has an id,
  362. type and name, and any other consistency checks.
  363. """
  364. self.assertIsNotNone(
  365. entity._config.get("entity"), f"entity type missing in {cfg}"
  366. )
  367. e = entity.config_id
  368. self.assertIsNotNone(
  369. entity._config.get("dps"), f"dps missing from {e} in {cfg}"
  370. )
  371. functions = set()
  372. extra = set()
  373. known = set()
  374. redirects = set()
  375. # Basic checks of dps, and initialising of redirects and extras sets
  376. # for later checking
  377. for dp in entity.dps():
  378. self.assertIsNotNone(
  379. dp._config.get("id"), f"dp id missing from {e} in {cfg}"
  380. )
  381. self.assertIsNotNone(
  382. dp._config.get("type"), f"dp type missing from {e} in {cfg}"
  383. )
  384. self.assertIsNotNone(
  385. dp._config.get("name"), f"dp name missing from {e} in {cfg}"
  386. )
  387. extra.add(dp.name)
  388. mappings = dp._config.get("mapping", [])
  389. self.assertIsInstance(
  390. mappings,
  391. list,
  392. f"mapping is not a list in {cfg}; entity {e}, dp {dp.name}",
  393. )
  394. for m in mappings:
  395. conditions = m.get("conditions", [])
  396. self.assertIsInstance(
  397. conditions,
  398. list,
  399. f"conditions is not a list in {cfg}; entity {e}, dp {dp.name}",
  400. )
  401. for c in conditions:
  402. if c.get("value_redirect"):
  403. redirects.add(c.get("value_redirect"))
  404. if c.get("value_mirror"):
  405. redirects.add(c.get("value_mirror"))
  406. if m.get("value_redirect"):
  407. redirects.add(m.get("value_redirect"))
  408. if m.get("value_mirror"):
  409. redirects.add(m.get("value_mirror"))
  410. # Check redirects all exist
  411. for redirect in redirects:
  412. self.assertIn(redirect, extra, f"dp {redirect} missing from {e} in {cfg}")
  413. # Check dps that are required for this entity type all exist
  414. expected = KNOWN_DPS.get(entity.entity)
  415. for rule in expected["required"]:
  416. self.assertTrue(
  417. self.dp_match(rule, functions, extra, known, True),
  418. f"{cfg} missing required {self.rule_broken_msg(rule)} in {e}",
  419. )
  420. for rule in expected["optional"]:
  421. self.assertTrue(
  422. self.dp_match(rule, functions, extra, known, False),
  423. f"{cfg} expecting {self.rule_broken_msg(rule)} in {e}",
  424. )
  425. # Check for potential typos in extra attributes
  426. known_extra = known - functions
  427. for attr in extra:
  428. for dp in known_extra:
  429. self.assertLess(
  430. fuzz.ratio(attr, dp),
  431. 85,
  432. f"Probable typo {attr} is too similar to {dp} in {cfg} {e}",
  433. )
  434. # Check that sensors with mapped values are of class enum and vice versa
  435. if entity.entity == "sensor":
  436. mock_device = MagicMock()
  437. sensor = TuyaLocalSensor(mock_device, entity)
  438. if sensor.options:
  439. self.assertEqual(
  440. entity.device_class,
  441. SensorDeviceClass.ENUM,
  442. f"{cfg} {e} has mapped values but does not have a device class of enum",
  443. )
  444. if entity.device_class == SensorDeviceClass.ENUM:
  445. self.assertIsNotNone(
  446. sensor.options,
  447. f"{cfg} {e} has a device class of enum, but has no mapped values",
  448. )
  449. def test_config_files_parse(self):
  450. """
  451. All configs should be parsable and meet certain criteria
  452. """
  453. for cfg in available_configs():
  454. entities = []
  455. parsed = TuyaDeviceConfig(cfg)
  456. # Check for error messages or unparsed config
  457. if isinstance(parsed, str) or isinstance(parsed._config, str):
  458. self.fail(f"unparsable yaml in {cfg}")
  459. try:
  460. YAML_SCHEMA(parsed._config)
  461. except vol.MultipleInvalid as e:
  462. self.fail(f"Validation error in {cfg}: {e}")
  463. self.assertIsNotNone(
  464. parsed._config.get("name"),
  465. f"name missing from {cfg}",
  466. )
  467. self.assertIsNotNone(
  468. parsed._config.get("primary_entity"),
  469. f"primary_entity missing from {cfg}",
  470. )
  471. self.check_entity(parsed.primary_entity, cfg)
  472. entities.append(parsed.primary_entity.config_id)
  473. secondary = False
  474. for entity in parsed.secondary_entities():
  475. secondary = True
  476. self.check_entity(entity, cfg)
  477. entities.append(entity.config_id)
  478. # check entities are unique
  479. self.assertCountEqual(entities, set(entities))
  480. # If there are no secondary entities, check that it is intended
  481. if not secondary:
  482. for key in parsed._config.keys():
  483. self.assertFalse(
  484. key.startswith("sec"),
  485. f"misspelled secondary_entities in {cfg}",
  486. )
  487. # Most of the device_config functionality is exercised during testing of
  488. # the various supported devices. These tests concentrate only on the gaps.
  489. def test_match_quality(self):
  490. """Test the match_quality function."""
  491. cfg = get_config("deta_fan")
  492. q = cfg.match_quality({**KOGAN_HEATER_PAYLOAD, "updated_at": 0})
  493. self.assertEqual(q, 0)
  494. q = cfg.match_quality({**GPPH_HEATER_PAYLOAD})
  495. self.assertEqual(q, 0)
  496. def test_entity_find_unknown_dps_fails(self):
  497. """Test that finding a dps that doesn't exist fails."""
  498. cfg = get_config("kogan_switch")
  499. non_existing = cfg.primary_entity.find_dps("missing")
  500. self.assertIsNone(non_existing)
  501. async def test_dps_async_set_readonly_value_fails(self):
  502. """Test that setting a readonly dps fails."""
  503. mock_device = MagicMock()
  504. cfg = get_config("goldair_gpph_heater")
  505. error_code = cfg.primary_entity.find_dps("error")
  506. with self.assertRaises(TypeError):
  507. await error_code.async_set_value(mock_device, 1)
  508. def test_dps_values_is_empty_with_no_mapping(self):
  509. """
  510. Test that a dps with no mapping returns None as its possible values
  511. """
  512. mock_device = MagicMock()
  513. cfg = get_config("goldair_gpph_heater")
  514. temp = cfg.primary_entity.find_dps("current_temperature")
  515. self.assertEqual(temp.values(mock_device), [])
  516. def test_config_returned(self):
  517. """Test that config file is returned by config"""
  518. cfg = get_config("kogan_switch")
  519. self.assertEqual(cfg.config, "smartplugv1.yaml")
  520. def test_float_matches_ints(self):
  521. """Test that the _typematch function matches int values to float dps"""
  522. self.assertTrue(_typematch(float, 1))
  523. def test_bytes_to_fmt_returns_string_for_unknown(self):
  524. """
  525. Test that the _bytes_to_fmt function parses unknown number of bytes
  526. as a string format.
  527. """
  528. self.assertEqual(_bytes_to_fmt(5), "5s")
  529. def test_deprecation(self):
  530. """Test that deprecation messages are picked from the config."""
  531. mock_device = MagicMock()
  532. mock_device.name = "Testing"
  533. mock_config = {"entity": "Test", "deprecated": "Passed"}
  534. cfg = TuyaEntityConfig(mock_device, mock_config)
  535. self.assertTrue(cfg.deprecated)
  536. self.assertEqual(
  537. cfg.deprecation_message,
  538. "The use of Test for Testing is deprecated and should be "
  539. "replaced by Passed.",
  540. )
  541. def test_format_with_none_defined(self):
  542. """Test that format returns None when there is none configured."""
  543. mock_entity = MagicMock()
  544. mock_config = {"id": "1", "name": "test", "type": "string"}
  545. cfg = TuyaDpsConfig(mock_entity, mock_config)
  546. self.assertIsNone(cfg.format)
  547. def test_decoding_base64(self):
  548. """Test that decoded_value works with base64 encoding."""
  549. mock_entity = MagicMock()
  550. mock_config = {"id": "1", "name": "test", "type": "base64"}
  551. mock_device = MagicMock()
  552. mock_device.get_property.return_value = "VGVzdA=="
  553. cfg = TuyaDpsConfig(mock_entity, mock_config)
  554. self.assertEqual(
  555. cfg.decoded_value(mock_device),
  556. bytes("Test", "utf-8"),
  557. )
  558. def test_decoding_hex(self):
  559. """Test that decoded_value works with hex encoding."""
  560. mock_entity = MagicMock()
  561. mock_config = {"id": "1", "name": "test", "type": "hex"}
  562. mock_device = MagicMock()
  563. mock_device.get_property.return_value = "babe"
  564. cfg = TuyaDpsConfig(mock_entity, mock_config)
  565. self.assertEqual(
  566. cfg.decoded_value(mock_device),
  567. b"\xba\xbe",
  568. )
  569. def test_decoding_unencoded(self):
  570. """Test that decoded_value returns the raw value when not encoded."""
  571. mock_entity = MagicMock()
  572. mock_config = {"id": "1", "name": "test", "type": "string"}
  573. mock_device = MagicMock()
  574. mock_device.get_property.return_value = "VGVzdA=="
  575. cfg = TuyaDpsConfig(mock_entity, mock_config)
  576. self.assertEqual(
  577. cfg.decoded_value(mock_device),
  578. "VGVzdA==",
  579. )
  580. def test_encoding_base64(self):
  581. """Test that encode_value works with base64."""
  582. mock_entity = MagicMock()
  583. mock_config = {"id": "1", "name": "test", "type": "base64"}
  584. cfg = TuyaDpsConfig(mock_entity, mock_config)
  585. self.assertEqual(cfg.encode_value(bytes("Test", "utf-8")), "VGVzdA==")
  586. def test_encoding_hex(self):
  587. """Test that encode_value works with base64."""
  588. mock_entity = MagicMock()
  589. mock_config = {"id": "1", "name": "test", "type": "hex"}
  590. cfg = TuyaDpsConfig(mock_entity, mock_config)
  591. self.assertEqual(cfg.encode_value(b"\xca\xfe"), "cafe")
  592. def test_encoding_unencoded(self):
  593. """Test that encode_value works with base64."""
  594. mock_entity = MagicMock()
  595. mock_config = {"id": "1", "name": "test", "type": "string"}
  596. cfg = TuyaDpsConfig(mock_entity, mock_config)
  597. self.assertEqual(cfg.encode_value("Test"), "Test")
  598. def test_match_returns_false_on_errors_with_bitfield(self):
  599. """Test that TypeError and ValueError cause match to return False."""
  600. mock_entity = MagicMock()
  601. mock_config = {"id": "1", "name": "test", "type": "bitfield"}
  602. cfg = TuyaDpsConfig(mock_entity, mock_config)
  603. self.assertFalse(cfg._match(15, "not an integer"))
  604. def test_values_with_mirror(self):
  605. """Test that value_mirror redirects."""
  606. mock_entity = MagicMock()
  607. mock_config = {
  608. "id": "1",
  609. "type": "string",
  610. "name": "test",
  611. "mapping": [
  612. {"dps_val": "mirror", "value_mirror": "map_mirror"},
  613. {"dps_val": "plain", "value": "unmirrored"},
  614. ],
  615. }
  616. mock_map_config = {
  617. "id": "2",
  618. "type": "string",
  619. "name": "map_mirror",
  620. "mapping": [
  621. {"dps_val": "1", "value": "map_one"},
  622. {"dps_val": "2", "value": "map_two"},
  623. ],
  624. }
  625. mock_device = MagicMock()
  626. mock_device.get_property.return_value = "1"
  627. cfg = TuyaDpsConfig(mock_entity, mock_config)
  628. map = TuyaDpsConfig(mock_entity, mock_map_config)
  629. mock_entity.find_dps.return_value = map
  630. self.assertCountEqual(
  631. cfg.values(mock_device),
  632. ["unmirrored", "map_one", "map_two"],
  633. )
  634. def test_get_device_id(self):
  635. """Test that check if device id is correct"""
  636. self.assertEqual("my-device-id", get_device_id({"device_id": "my-device-id"}))
  637. self.assertEqual("sub-id", get_device_id({"device_cid": "sub-id"}))
  638. self.assertEqual("s", get_device_id({"device_id": "d", "device_cid": "s"}))
  639. def test_getting_masked_hex(self):
  640. """Test that get_value works with masked hex encoding."""
  641. mock_entity = MagicMock()
  642. mock_config = {
  643. "id": "1",
  644. "name": "test",
  645. "type": "hex",
  646. "mapping": [
  647. {"mask": "ff00"},
  648. ],
  649. }
  650. mock_device = MagicMock()
  651. mock_device.get_property.return_value = "babe"
  652. cfg = TuyaDpsConfig(mock_entity, mock_config)
  653. self.assertEqual(
  654. cfg.get_value(mock_device),
  655. 0xBA,
  656. )
  657. def test_setting_masked_hex(self):
  658. """Test that get_values_to_set works with masked hex encoding."""
  659. mock_entity = MagicMock()
  660. mock_config = {
  661. "id": "1",
  662. "name": "test",
  663. "type": "hex",
  664. "mapping": [
  665. {"mask": "ff00"},
  666. ],
  667. }
  668. mock_device = MagicMock()
  669. mock_device.get_property.return_value = "babe"
  670. cfg = TuyaDpsConfig(mock_entity, mock_config)
  671. self.assertEqual(
  672. cfg.get_values_to_set(mock_device, 0xCA),
  673. {"1": "cabe"},
  674. )
  675. def test_default_without_mapping(self):
  676. """Test that default returns None when there is no mapping"""
  677. mock_entity = MagicMock()
  678. mock_config = {"id": "1", "name": "test", "type": "string"}
  679. cfg = TuyaDpsConfig(mock_entity, mock_config)
  680. self.assertIsNone(cfg.default)