test_device_config.py 27 KB

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