test_device_config.py 33 KB

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