test_device_config.py 27 KB

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