test_device_config.py 27 KB

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