test_device_config.py 30 KB

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