test_device_config.py 26 KB

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