test_device_config.py 26 KB

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