4
0

test_device_config.py 25 KB

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