test_device_config.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804
  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": [],
  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. for err in e.errors:
  480. path = ".".join([str(p) for p in err.path])
  481. messages.append(f"{path}: {err.msg}")
  482. messages = "; ".join(messages)
  483. pytest.fail(f"\n::error file={fname},line=1::Validation error: {messages}")
  484. assert parsed._config.get("name") is not None, (
  485. f"\n::error file={fname},line=1::name missing from {cfg}",
  486. )
  487. count = 0
  488. for entity in parsed.all_entities():
  489. check_entity(entity, cfg, mocker)
  490. entities.append(entity.config_id)
  491. count += 1
  492. assert count > 0, f"\n::error file={fname},line=1::No entities found in {cfg}"
  493. # check entities are unique
  494. assert len(entities) == len(set(entities)), (
  495. f"\n::error file={fname},line=1::Duplicate entities in {cfg}",
  496. )
  497. def test_configs_can_be_matched():
  498. """Test that the config files can be matched to a device."""
  499. for cfg in available_configs():
  500. optional = set()
  501. required = set()
  502. parsed = TuyaDeviceConfig(cfg)
  503. fname = f"custom_components/tuya_local/devices/{cfg}"
  504. products = parsed._config.get("products")
  505. # Configs with a product list can be matched by product id
  506. if products:
  507. p_match = False
  508. for p in products:
  509. if p.get("id"):
  510. p_match = True
  511. if p_match:
  512. continue
  513. for entity in parsed.all_entities():
  514. for dp in entity.dps():
  515. if dp.optional:
  516. optional.add(dp.id)
  517. else:
  518. required.add(dp.id)
  519. assert len(required) > 0, (
  520. f"\n::error file={fname},line=1::No required dps found in {cfg}"
  521. )
  522. for dp in required:
  523. assert dp not in optional, (
  524. f"\n::error file={fname},line=1::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():
  529. """Test the match_quality function."""
  530. cfg = get_config("deta_fan")
  531. q = cfg.match_quality({**KOGAN_HEATER_PAYLOAD, "updated_at": 0})
  532. assert q == 0
  533. q = cfg.match_quality({**GPPH_HEATER_PAYLOAD})
  534. assert q == 0
  535. def test_entity_find_unknown_dps_fails():
  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. assert non_existing is None
  541. break
  542. @pytest.mark.asyncio
  543. async def test_dps_async_set_readonly_value_fails(mocker):
  544. """Test that setting a readonly dps fails."""
  545. mock_device = mocker.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 pytest.raises(TypeError):
  551. await temp.async_set_value(mock_device, 20)
  552. break
  553. def test_dps_values_is_empty_with_no_mapping(mocker):
  554. """
  555. Test that a dps with no mapping returns empty list for possible values
  556. """
  557. mock_device = mocker.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. assert temp.values(mock_device) == []
  563. break
  564. def test_config_returned():
  565. """Test that config file is returned by config"""
  566. cfg = get_config("kogan_switch")
  567. assert cfg.config == "smartplugv1.yaml"
  568. def test_float_matches_ints():
  569. """Test that the _typematch function matches int values to float dps"""
  570. assert _typematch(float, 1)
  571. def test_bytes_to_fmt_returns_string_for_unknown():
  572. """
  573. Test that the _bytes_to_fmt function parses unknown number of bytes
  574. as a string format.
  575. """
  576. assert _bytes_to_fmt(5) == "5s"
  577. def test_deprecation(mocker):
  578. """Test that deprecation messages are picked from the config."""
  579. mock_device = mocker.MagicMock()
  580. mock_device.name = "Testing"
  581. mock_config = {"entity": "Test", "deprecated": "Passed"}
  582. cfg = TuyaEntityConfig(mock_device, mock_config)
  583. assert cfg.deprecated
  584. assert (
  585. cfg.deprecation_message
  586. == "The use of Test for Testing is deprecated and should be replaced by Passed."
  587. )
  588. def test_format_with_none_defined(mocker):
  589. """Test that format returns None when there is none configured."""
  590. mock_entity = mocker.MagicMock()
  591. mock_config = {"id": "1", "name": "test", "type": "string"}
  592. cfg = TuyaDpsConfig(mock_entity, mock_config)
  593. assert cfg.format is None
  594. def test_decoding_base64(mocker):
  595. """Test that decoded_value works with base64 encoding."""
  596. mock_entity = mocker.MagicMock()
  597. mock_config = {"id": "1", "name": "test", "type": "base64"}
  598. mock_device = mocker.MagicMock()
  599. mock_device.get_property.return_value = "VGVzdA=="
  600. cfg = TuyaDpsConfig(mock_entity, mock_config)
  601. assert cfg.decoded_value(mock_device) == bytes("Test", "utf-8")
  602. def test_decoding_hex(mocker):
  603. """Test that decoded_value works with hex encoding."""
  604. mock_entity = mocker.MagicMock()
  605. mock_config = {"id": "1", "name": "test", "type": "hex"}
  606. mock_device = mocker.MagicMock()
  607. mock_device.get_property.return_value = "babe"
  608. cfg = TuyaDpsConfig(mock_entity, mock_config)
  609. assert cfg.decoded_value(mock_device) == b"\xba\xbe"
  610. def test_decoding_unencoded(mocker):
  611. """Test that decoded_value returns the raw value when not encoded."""
  612. mock_entity = mocker.MagicMock()
  613. mock_config = {"id": "1", "name": "test", "type": "string"}
  614. mock_device = mocker.MagicMock()
  615. mock_device.get_property.return_value = "VGVzdA=="
  616. cfg = TuyaDpsConfig(mock_entity, mock_config)
  617. assert cfg.decoded_value(mock_device) == "VGVzdA=="
  618. def test_encoding_base64(mocker):
  619. """Test that encode_value works with base64."""
  620. mock_entity = mocker.MagicMock()
  621. mock_config = {"id": "1", "name": "test", "type": "base64"}
  622. cfg = TuyaDpsConfig(mock_entity, mock_config)
  623. assert cfg.encode_value(bytes("Test", "utf-8")) == "VGVzdA=="
  624. def test_encoding_hex(mocker):
  625. """Test that encode_value works with base64."""
  626. mock_entity = mocker.MagicMock()
  627. mock_config = {"id": "1", "name": "test", "type": "hex"}
  628. cfg = TuyaDpsConfig(mock_entity, mock_config)
  629. assert cfg.encode_value(b"\xca\xfe") == "cafe"
  630. def test_encoding_unencoded(mocker):
  631. """Test that encode_value works with base64."""
  632. mock_entity = mocker.MagicMock()
  633. mock_config = {"id": "1", "name": "test", "type": "string"}
  634. cfg = TuyaDpsConfig(mock_entity, mock_config)
  635. assert cfg.encode_value("Test") == "Test"
  636. def test_match_returns_false_on_errors_with_bitfield(mocker):
  637. """Test that TypeError and ValueError cause match to return False."""
  638. mock_entity = mocker.MagicMock()
  639. mock_config = {"id": "1", "name": "test", "type": "bitfield"}
  640. cfg = TuyaDpsConfig(mock_entity, mock_config)
  641. assert not cfg._match(15, "not an integer")
  642. def test_values_with_mirror(mocker):
  643. """Test that value_mirror redirects."""
  644. mock_entity = mocker.MagicMock()
  645. mock_config = {
  646. "id": "1",
  647. "type": "string",
  648. "name": "test",
  649. "mapping": [
  650. {"dps_val": "mirror", "value_mirror": "map_mirror"},
  651. {"dps_val": "plain", "value": "unmirrored"},
  652. ],
  653. }
  654. mock_map_config = {
  655. "id": "2",
  656. "type": "string",
  657. "name": "map_mirror",
  658. "mapping": [
  659. {"dps_val": "1", "value": "map_one"},
  660. {"dps_val": "2", "value": "map_two"},
  661. ],
  662. }
  663. mock_device = mocker.MagicMock()
  664. mock_device.get_property.return_value = "1"
  665. cfg = TuyaDpsConfig(mock_entity, mock_config)
  666. map = TuyaDpsConfig(mock_entity, mock_map_config)
  667. mock_entity.find_dps.return_value = map
  668. assert set(cfg.values(mock_device)) == {"unmirrored", "map_one", "map_two"}
  669. assert len(cfg.values(mock_device)) == 3
  670. def test_get_device_id():
  671. """Test that check if device id is correct"""
  672. assert "my-device-id" == get_device_id({"device_id": "my-device-id"})
  673. assert "sub-id" == get_device_id({"device_cid": "sub-id"})
  674. assert "s" == get_device_id({"device_id": "d", "device_cid": "s"})
  675. def test_getting_masked_hex(mocker):
  676. """Test that get_value works with masked hex encoding."""
  677. mock_entity = mocker.MagicMock()
  678. mock_config = {
  679. "id": "1",
  680. "name": "test",
  681. "type": "hex",
  682. "mask": "ff00",
  683. }
  684. mock_device = mocker.MagicMock()
  685. mock_device.get_property.return_value = "babe"
  686. cfg = TuyaDpsConfig(mock_entity, mock_config)
  687. assert cfg.get_value(mock_device) == 0xBA
  688. def test_setting_masked_hex(mocker):
  689. """Test that get_values_to_set works with masked hex encoding."""
  690. mock_entity = mocker.MagicMock()
  691. mock_config = {
  692. "id": "1",
  693. "name": "test",
  694. "type": "hex",
  695. "mask": "ff00",
  696. }
  697. mock_device = mocker.MagicMock()
  698. mock_device.get_property.return_value = "babe"
  699. cfg = TuyaDpsConfig(mock_entity, mock_config)
  700. assert cfg.get_values_to_set(mock_device, 0xCA) == {"1": "cabe"}
  701. def test_default_without_mapping(mocker):
  702. """Test that default returns None when there is no mapping"""
  703. mock_entity = mocker.MagicMock()
  704. mock_config = {"id": "1", "name": "test", "type": "string"}
  705. cfg = TuyaDpsConfig(mock_entity, mock_config)
  706. assert cfg.default is None
  707. def test_matching_with_product_id():
  708. """Test that matching with product id works"""
  709. cfg = get_config("smartplugv1")
  710. assert cfg.matches({}, ["37mnhia3pojleqfh"])
  711. def test_matched_product_id_with_conflict_rejected():
  712. """Test that matching with product id fails when there is a conflict"""
  713. cfg = get_config("smartplugv1")
  714. assert not cfg.matches({"1": "wrong_type"}, ["37mnhia3pojleqfh"])