test_device_config.py 27 KB

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