test_device_config.py 33 KB

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