test_device_config.py 27 KB

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