diff --git a/.devcontainer/devcontainer.json b/.devcontainer/devcontainer.json index 0761dae..e0f805a 100644 --- a/.devcontainer/devcontainer.json +++ b/.devcontainer/devcontainer.json @@ -1,6 +1,6 @@ // See https://aka.ms/vscode-remote/devcontainer.json for format details. { - "image": "ghcr.io/ludeeus/devcontainer/integration:stable", + "image": "ghcr.io/ludeeus/devcontainer/integration:latest", "name": "Blueprint integration development", "context": "..", "appPort": [ diff --git a/.pylintrc b/.pylintrc new file mode 100644 index 0000000..634ce49 --- /dev/null +++ b/.pylintrc @@ -0,0 +1,590 @@ +[MASTER] + +# A comma-separated list of package or module names from where C extensions may +# be loaded. Extensions are loading into the active Python interpreter and may +# run arbitrary code. +extension-pkg-allow-list= + +# A comma-separated list of package or module names from where C extensions may +# be loaded. Extensions are loading into the active Python interpreter and may +# run arbitrary code. (This is an alternative name to extension-pkg-allow-list +# for backward compatibility.) +extension-pkg-whitelist= + +# Return non-zero exit code if any of these messages/categories are detected, +# even if score is above --fail-under value. Syntax same as enable. Messages +# specified are enabled, while categories only check already-enabled messages. +fail-on= + +# Specify a score threshold to be exceeded before program exits with error. +fail-under=10.0 + +# Files or directories to be skipped. They should be base names, not paths. +ignore=CVS + +# Add files or directories matching the regex patterns to the ignore-list. The +# regex matches against paths and can be in Posix or Windows format. +ignore-paths= + +# Files or directories matching the regex patterns are skipped. The regex +# matches against base names, not paths. The default value ignores emacs file +# locks +ignore-patterns=^\.# + +# Python code to execute, usually for sys.path manipulation such as +# pygtk.require(). +#init-hook= + +# Use multiple processes to speed up Pylint. Specifying 0 will auto-detect the +# number of processors available to use. +jobs=1 + +# Control the amount of potential inferred values when inferring a single +# object. This can help the performance when dealing with large functions or +# complex, nested conditions. +limit-inference-results=100 + +# List of plugins (as comma separated values of python module names) to load, +# usually to register additional checkers. +load-plugins= + +# Pickle collected data for later comparisons. +persistent=yes + +# Minimum Python version to use for version dependent checks. Will default to +# the version used to run pylint. +py-version=3.10 + +# Discover python modules and packages in the file system subtree. +recursive=no + +# When enabled, pylint would attempt to guess common misconfiguration and emit +# user-friendly hints instead of false-positive error messages. +suggestion-mode=yes + +# Allow loading of arbitrary C extensions. Extensions are imported into the +# active Python interpreter and may run arbitrary code. +unsafe-load-any-extension=no + + +[MESSAGES CONTROL] + +# Only show warnings with the listed confidence levels. Leave empty to show +# all. Valid levels: HIGH, CONTROL_FLOW, INFERENCE, INFERENCE_FAILURE, +# UNDEFINED. +confidence= + +# Disable the message, report, category or checker with the given id(s). You +# can either give multiple identifiers separated by comma (,) or put this +# option multiple times (only on the command line, not in the configuration +# file where it should appear only once). You can also use "--disable=all" to +# disable everything first and then re-enable specific checks. For example, if +# you want to run only the similarities checker, you can use "--disable=all +# --enable=similarities". If you want to run only the classes checker, but have +# no Warning level messages displayed, use "--disable=all --enable=classes +# --disable=W". +disable=raw-checker-failed, + bad-inline-option, + locally-disabled, + file-ignored, + suppressed-message, + useless-suppression, + deprecated-pragma, + use-symbolic-message-instead, + missing-module-docstring, + missing-function-docstring, + missing-class-docstring, + wildcard-import, + unused-wildcard-import + +# Enable the message, report, category or checker with the given id(s). You can +# either give multiple identifier separated by comma (,) or put this option +# multiple time (only on the command line, not in the configuration file where +# it should appear only once). See also the "--disable" option for examples. +enable=c-extension-no-member + + +[REPORTS] + +# Python expression which should return a score less than or equal to 10. You +# have access to the variables 'fatal', 'error', 'warning', 'refactor', +# 'convention', and 'info' which contain the number of messages in each +# category, as well as 'statement' which is the total number of statements +# analyzed. This score is used by the global evaluation report (RP0004). +evaluation=max(0, 0 if fatal else 10.0 - ((float(5 * error + warning + refactor + convention) / statement) * 10)) + +# Template used to display messages. This is a python new-style format string +# used to format the message information. See doc for all details. +#msg-template= + +# Set the output format. Available formats are text, parseable, colorized, json +# and msvs (visual studio). You can also give a reporter class, e.g. +# mypackage.mymodule.MyReporterClass. +output-format=text + +# Tells whether to display a full report or only the messages. +reports=no + +# Activate the evaluation score. +score=yes + + +[REFACTORING] + +# Maximum number of nested blocks for function / method body +max-nested-blocks=5 + +# Complete name of functions that never returns. When checking for +# inconsistent-return-statements if a never returning function is called then +# it will be considered as an explicit return statement and no message will be +# printed. +never-returning-functions=sys.exit,argparse.parse_error + + +[MISCELLANEOUS] + +# List of note tags to take in consideration, separated by a comma. +notes=FIXME, + XXX, + TODO + +# Regular expression of note tags to take in consideration. +#notes-rgx= + + +[TYPECHECK] + +# List of decorators that produce context managers, such as +# contextlib.contextmanager. Add to this list to register other decorators that +# produce valid context managers. +contextmanager-decorators=contextlib.contextmanager + +# List of members which are set dynamically and missed by pylint inference +# system, and so shouldn't trigger E1101 when accessed. Python regular +# expressions are accepted. +generated-members= + +# Tells whether missing members accessed in mixin class should be ignored. A +# class is considered mixin if its name matches the mixin-class-rgx option. +ignore-mixin-members=yes + +# Tells whether to warn about missing members when the owner of the attribute +# is inferred to be None. +ignore-none=yes + +# This flag controls whether pylint should warn about no-member and similar +# checks whenever an opaque object is returned when inferring. The inference +# can return multiple potential results while evaluating a Python object, but +# some branches might not be evaluated, which results in partial inference. In +# that case, it might be useful to still emit no-member and other checks for +# the rest of the inferred objects. +ignore-on-opaque-inference=yes + +# List of class names for which member attributes should not be checked (useful +# for classes with dynamically set attributes). This supports the use of +# qualified names. +ignored-classes=optparse.Values,thread._local,_thread._local + +# List of module names for which member attributes should not be checked +# (useful for modules/projects where namespaces are manipulated during runtime +# and thus existing member attributes cannot be deduced by static analysis). It +# supports qualified module names, as well as Unix pattern matching. +ignored-modules= + +# Show a hint with possible names when a member name was not found. The aspect +# of finding the hint is based on edit distance. +missing-member-hint=yes + +# The minimum edit distance a name should have in order to be considered a +# similar match for a missing member name. +missing-member-hint-distance=1 + +# The total number of similar names that should be taken in consideration when +# showing a hint for a missing member. +missing-member-max-choices=1 + +# Regex pattern to define which classes are considered mixins ignore-mixin- +# members is set to 'yes' +mixin-class-rgx=.*[Mm]ixin + +# List of decorators that change the signature of a decorated function. +signature-mutators= + + +[FORMAT] + +# Expected format of line ending, e.g. empty (any line ending), LF or CRLF. +expected-line-ending-format= + +# Regexp for a line that is allowed to be longer than the limit. +ignore-long-lines=^\s*(# )??$ + +# Number of spaces of indent required inside a hanging or continued line. +indent-after-paren=4 + +# String used as indentation unit. This is usually " " (4 spaces) or "\t" (1 +# tab). +indent-string=' ' + +# Maximum number of characters on a single line. +max-line-length=120 + +# Maximum number of lines in a module. +max-module-lines=1000 + +# Allow the body of a class to be on the same line as the declaration if body +# contains single statement. +single-line-class-stmt=no + +# Allow the body of an if to be on the same line as the test if there is no +# else. +single-line-if-stmt=no + + +[SIMILARITIES] + +# Comments are removed from the similarity computation +ignore-comments=yes + +# Docstrings are removed from the similarity computation +ignore-docstrings=yes + +# Imports are removed from the similarity computation +ignore-imports=no + +# Signatures are removed from the similarity computation +ignore-signatures=no + +# Minimum lines number of a similarity. +min-similarity-lines=4 + + +[BASIC] + +# Naming style matching correct argument names. +argument-naming-style=snake_case + +# Regular expression matching correct argument names. Overrides argument- +# naming-style. If left empty, argument names will be checked with the set +# naming style. +#argument-rgx= + +# Naming style matching correct attribute names. +attr-naming-style=snake_case + +# Regular expression matching correct attribute names. Overrides attr-naming- +# style. If left empty, attribute names will be checked with the set naming +# style. +#attr-rgx= + +# Bad variable names which should always be refused, separated by a comma. +bad-names=foo, + bar, + baz, + toto, + tutu, + tata + +# Bad variable names regexes, separated by a comma. If names match any regex, +# they will always be refused +bad-names-rgxs= + +# Naming style matching correct class attribute names. +class-attribute-naming-style=any + +# Regular expression matching correct class attribute names. Overrides class- +# attribute-naming-style. If left empty, class attribute names will be checked +# with the set naming style. +#class-attribute-rgx= + +# Naming style matching correct class constant names. +class-const-naming-style=UPPER_CASE + +# Regular expression matching correct class constant names. Overrides class- +# const-naming-style. If left empty, class constant names will be checked with +# the set naming style. +#class-const-rgx= + +# Naming style matching correct class names. +class-naming-style=PascalCase + +# Regular expression matching correct class names. Overrides class-naming- +# style. If left empty, class names will be checked with the set naming style. +#class-rgx= + +# Naming style matching correct constant names. +const-naming-style=UPPER_CASE + +# Regular expression matching correct constant names. Overrides const-naming- +# style. If left empty, constant names will be checked with the set naming +# style. +#const-rgx= + +# Minimum line length for functions/classes that require docstrings, shorter +# ones are exempt. +docstring-min-length=-1 + +# Naming style matching correct function names. +function-naming-style=snake_case + +# Regular expression matching correct function names. Overrides function- +# naming-style. If left empty, function names will be checked with the set +# naming style. +#function-rgx= + +# Good variable names which should always be accepted, separated by a comma. +good-names=i, + j, + k, + ex, + Run, + _ + +# Good variable names regexes, separated by a comma. If names match any regex, +# they will always be accepted +good-names-rgxs= + +# Include a hint for the correct naming format with invalid-name. +include-naming-hint=no + +# Naming style matching correct inline iteration names. +inlinevar-naming-style=any + +# Regular expression matching correct inline iteration names. Overrides +# inlinevar-naming-style. If left empty, inline iteration names will be checked +# with the set naming style. +#inlinevar-rgx= + +# Naming style matching correct method names. +method-naming-style=snake_case + +# Regular expression matching correct method names. Overrides method-naming- +# style. If left empty, method names will be checked with the set naming style. +#method-rgx= + +# Naming style matching correct module names. +module-naming-style=snake_case + +# Regular expression matching correct module names. Overrides module-naming- +# style. If left empty, module names will be checked with the set naming style. +#module-rgx= + +# Colon-delimited sets of names that determine each other's naming style when +# the name regexes allow several styles. +name-group= + +# Regular expression which should only match function or class names that do +# not require a docstring. +no-docstring-rgx=^_ + +# List of decorators that produce properties, such as abc.abstractproperty. Add +# to this list to register other decorators that produce valid properties. +# These decorators are taken in consideration only for invalid-name. +property-classes=abc.abstractproperty + +# Regular expression matching correct type variable names. If left empty, type +# variable names will be checked with the set naming style. +#typevar-rgx= + +# Naming style matching correct variable names. +variable-naming-style=snake_case + +# Regular expression matching correct variable names. Overrides variable- +# naming-style. If left empty, variable names will be checked with the set +# naming style. +#variable-rgx= + + +[VARIABLES] + +# List of additional names supposed to be defined in builtins. Remember that +# you should avoid defining new builtins when possible. +additional-builtins= + +# Tells whether unused global variables should be treated as a violation. +allow-global-unused-variables=yes + +# List of names allowed to shadow builtins +allowed-redefined-builtins= + +# List of strings which can identify a callback function by name. A callback +# name must start or end with one of those strings. +callbacks=cb_, + _cb + +# A regular expression matching the name of dummy variables (i.e. expected to +# not be used). +dummy-variables-rgx=_+$|(_[a-zA-Z0-9_]*[a-zA-Z0-9]+?$)|dummy|^ignored_|^unused_ + +# Argument names that match this expression will be ignored. Default to name +# with leading underscore. +ignored-argument-names=_.*|^ignored_|^unused_ + +# Tells whether we should check for unused import in __init__ files. +init-import=no + +# List of qualified module names which can have objects that can redefine +# builtins. +redefining-builtins-modules=six.moves,past.builtins,future.builtins,builtins,io + + +[LOGGING] + +# The type of string formatting that logging methods do. `old` means using % +# formatting, `new` is for `{}` formatting. +logging-format-style=old + +# Logging modules to check that the string format arguments are in logging +# function parameter format. +logging-modules=logging + + +[STRING] + +# This flag controls whether inconsistent-quotes generates a warning when the +# character used as a quote delimiter is used inconsistently within a module. +check-quote-consistency=no + +# This flag controls whether the implicit-str-concat should generate a warning +# on implicit string concatenation in sequences defined over several lines. +check-str-concat-over-line-jumps=no + + +[SPELLING] + +# Limits count of emitted suggestions for spelling mistakes. +max-spelling-suggestions=4 + +# Spelling dictionary name. Available dictionaries: none. To make it work, +# install the 'python-enchant' package. +spelling-dict= + +# List of comma separated words that should be considered directives if they +# appear and the beginning of a comment and should not be checked. +spelling-ignore-comment-directives=fmt: on,fmt: off,noqa:,noqa,nosec,isort:skip,mypy: + +# List of comma separated words that should not be checked. +spelling-ignore-words= + +# A path to a file that contains the private dictionary; one word per line. +spelling-private-dict-file= + +# Tells whether to store unknown words to the private dictionary (see the +# --spelling-private-dict-file option) instead of raising a message. +spelling-store-unknown-words=no + + +[IMPORTS] + +# List of modules that can be imported at any level, not just the top level +# one. +allow-any-import-level= + +# Allow wildcard imports from modules that define __all__. +allow-wildcard-with-all=no + +# Analyse import fallback blocks. This can be used to support both Python 2 and +# 3 compatible code, which means that the block might have code that exists +# only in one or another interpreter, leading to false positives when analysed. +analyse-fallback-blocks=no + +# Deprecated modules which should not be used, separated by a comma. +deprecated-modules= + +# Output a graph (.gv or any supported image format) of external dependencies +# to the given file (report RP0402 must not be disabled). +ext-import-graph= + +# Output a graph (.gv or any supported image format) of all (i.e. internal and +# external) dependencies to the given file (report RP0402 must not be +# disabled). +import-graph= + +# Output a graph (.gv or any supported image format) of internal dependencies +# to the given file (report RP0402 must not be disabled). +int-import-graph= + +# Force import order to recognize a module as part of the standard +# compatibility libraries. +known-standard-library= + +# Force import order to recognize a module as part of a third party library. +known-third-party=enchant + +# Couples of modules and preferred modules, separated by a comma. +preferred-modules= + + +[DESIGN] + +# List of regular expressions of class ancestor names to ignore when counting +# public methods (see R0903) +exclude-too-few-public-methods= + +# List of qualified class names to ignore when counting class parents (see +# R0901) +ignored-parents= + +# Maximum number of arguments for function / method. +max-args=5 + +# Maximum number of attributes for a class (see R0902). +max-attributes=7 + +# Maximum number of boolean expressions in an if statement (see R0916). +max-bool-expr=5 + +# Maximum number of branch for function / method body. +max-branches=12 + +# Maximum number of locals for function / method body. +max-locals=15 + +# Maximum number of parents for a class (see R0901). +max-parents=7 + +# Maximum number of public methods for a class (see R0904). +max-public-methods=20 + +# Maximum number of return / yield for function / method body. +max-returns=6 + +# Maximum number of statements in function / method body. +max-statements=50 + +# Minimum number of public methods for a class (see R0903). +min-public-methods=2 + + +[CLASSES] + +# Warn about protected attribute access inside special methods +check-protected-access-in-special-methods=no + +# List of method names used to declare (i.e. assign) instance attributes. +defining-attr-methods=__init__, + __new__, + setUp, + __post_init__ + +# List of member names, which should be excluded from the protected access +# warning. +exclude-protected=_asdict, + _fields, + _replace, + _source, + _make + +# List of valid names for the first argument in a class method. +valid-classmethod-first-arg=cls + +# List of valid names for the first argument in a metaclass class method. +valid-metaclass-classmethod-first-arg=cls + + +[EXCEPTIONS] + +# Exceptions that will emit a warning when being caught. Defaults to +# "BaseException, Exception". +overgeneral-exceptions=BaseException, + Exception diff --git a/.vscode/settings.json b/.vscode/settings.json index a3d535d..aea87d4 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -4,5 +4,10 @@ "python.pythonPath": "/usr/local/bin/python", "files.associations": { "*.yaml": "home-assistant" - } + }, + "python.testing.pytestArgs": [ + "tests" + ], + "python.testing.unittestEnabled": false, + "python.testing.pytestEnabled": true } \ No newline at end of file diff --git a/custom_components/candy/__init__.py b/custom_components/candy/__init__.py index 9f44f0a..45e74c3 100644 --- a/custom_components/candy/__init__.py +++ b/custom_components/candy/__init__.py @@ -35,7 +35,7 @@ async def update_status(): _LOGGER.debug("Fetched status: %s", status) return status except Exception as err: - raise UpdateFailed(f"Error communicating with API: {repr(err)}") + raise UpdateFailed(f"Error communicating with API: {repr(err)}") from err coordinator = DataUpdateCoordinator( hass, diff --git a/custom_components/candy/client/__init__.py b/custom_components/candy/client/__init__.py index 65d28e2..8d89197 100644 --- a/custom_components/candy/client/__init__.py +++ b/custom_components/candy/client/__init__.py @@ -1,7 +1,7 @@ import json import logging from json import JSONDecodeError -from typing import Union, Optional +from typing import Optional, Tuple, Union import aiohttp import backoff @@ -10,7 +10,8 @@ from aiolimiter import AsyncLimiter from .decryption import decrypt, Encryption, find_key -from .model import WashingMachineStatus, TumbleDryerStatus, DishwasherStatus, OvenStatus +from .model import (DishwasherStatus, OvenStatus, TumbleDryerStatus, + WashingMachineStatus) _LOGGER = logging.getLogger(__name__) @@ -63,7 +64,7 @@ async def status(self) -> Union[WashingMachineStatus, TumbleDryerStatus, Dishwas return status -async def detect_encryption(session: aiohttp.ClientSession, device_ip: str) -> (Encryption, Optional[str]): +async def detect_encryption(session: aiohttp.ClientSession, device_ip: str) -> Tuple[Encryption, Optional[str]]: # noinspection PyBroadException try: _LOGGER.info("Trying to get a response without encryption (encrypted=0)...") @@ -73,8 +74,8 @@ async def detect_encryption(session: aiohttp.ClientSession, device_ip: str) -> ( assert resp_json.get("response") != "BAD REQUEST" _LOGGER.info("Received unencrypted JSON response, no need to use key for decryption") return Encryption.NO_ENCRYPTION, None - except Exception as e: - _LOGGER.debug(e) + except Exception as err: # pylint: disable=broad-except + _LOGGER.debug(err) _LOGGER.info("Failed to get a valid response without encryption, let's try with encrypted=1...") url = _status_url(device_ip, use_encryption=True) async with _LIMITER, session.get(url) as resp: @@ -84,12 +85,12 @@ async def detect_encryption(session: aiohttp.ClientSession, device_ip: str) -> ( _LOGGER.info("Response is not encrypted (despite encryption=1 in request), no need to brute force " "the key") return Encryption.ENCRYPTION_WITHOUT_KEY, None - except JSONDecodeError: + except JSONDecodeError as json_err: _LOGGER.info("Brute force decryption key from the encrypted response...") - _LOGGER.debug(f"Response: {resp_hex}") + _LOGGER.debug("Response: %s", resp_hex) key = find_key(bytes.fromhex(resp_hex)) if key is None: - raise ValueError("Couldn't brute force key") + raise ValueError("Couldn't brute force key") from json_err _LOGGER.info("Using key with encrypted=1 for future requests") return Encryption.ENCRYPTION, key diff --git a/custom_components/candy/client/decryption.py b/custom_components/candy/client/decryption.py index f627dea..343be80 100644 --- a/custom_components/candy/client/decryption.py +++ b/custom_components/candy/client/decryption.py @@ -19,7 +19,10 @@ class Encryption(Enum): NO_ENCRYPTION = 1 # Use `encrypted=0` in request, response is plaintext JSON ENCRYPTION = 2 # Use `encrypted=1` in request, response is encrypted bytes in hex encoding - ENCRYPTION_WITHOUT_KEY = 3 # Use `encrypted=1` in request, response is unencrypted hex bytes (https://github.com/ofalvai/home-assistant-candy/issues/35#issuecomment-965557116) + + # Use `encrypted=1` in request, response is unencrypted hex bytes + # https://github.com/ofalvai/home-assistant-candy/issues/35#issuecomment-965557116) + ENCRYPTION_WITHOUT_KEY = 3 def find_key(encrypted_response: bytes) -> Optional[str]: @@ -28,13 +31,13 @@ def find_key(encrypted_response: bytes) -> Optional[str]: ] number_of_keys = math.prod(len(l) for l in candidate_key_codepoints) - _LOGGER.info(f"{number_of_keys} keys to test") + _LOGGER.info("%d keys to test", number_of_keys) for key in itertools.product(*candidate_key_codepoints): decrypted = decrypt(key, encrypted_response) if _is_valid_json(decrypted): key_str = "".join(chr(point) for point in key) - _LOGGER.info(f"Potential key found: {key_str}") + _LOGGER.info("Potential key found: %s", key_str) return key_str return None diff --git a/custom_components/candy/config_flow.py b/custom_components/candy/config_flow.py index 2b5aff0..dcb8708 100644 --- a/custom_components/candy/config_flow.py +++ b/custom_components/candy/config_flow.py @@ -46,8 +46,8 @@ async def async_step_user( session=async_get_clientsession(self.hass), device_ip=user_input[CONF_IP_ADDRESS] ) - except Exception as e: # pylint: disable=broad-except - _LOGGER.exception(e) + except Exception as err: # pylint: disable=broad-except + _LOGGER.exception(err) errors["base"] = "detect_encryption" else: if encryption_type == Encryption.ENCRYPTION: diff --git a/custom_components/candy/sensor.py b/custom_components/candy/sensor.py index 9ad98b6..fcacf60 100644 --- a/custom_components/candy/sensor.py +++ b/custom_components/candy/sensor.py @@ -1,17 +1,20 @@ from abc import abstractmethod -from typing import Mapping, Any +from typing import Any, Mapping -from homeassistant.helpers.typing import StateType -from .client import WashingMachineStatus -from .client.model import MachineState, TumbleDryerStatus, DryerProgramState, OvenStatus, DishwasherStatus, \ - DishwasherState -from .const import * from homeassistant.components.sensor import SensorEntity from homeassistant.config_entries import ConfigEntry -from homeassistant.const import TIME_MINUTES, TEMP_CELSIUS +from homeassistant.const import TEMP_CELSIUS, TIME_MINUTES from homeassistant.core import HomeAssistant -from homeassistant.helpers.update_coordinator import CoordinatorEntity, DataUpdateCoordinator from homeassistant.helpers.entity import DeviceInfo +from homeassistant.helpers.typing import StateType +from homeassistant.helpers.update_coordinator import (CoordinatorEntity, + DataUpdateCoordinator) + +from .client import WashingMachineStatus +from .client.model import (DishwasherState, DishwasherStatus, + DryerProgramState, MachineState, OvenStatus, + TumbleDryerStatus) +from .const import * async def async_setup_entry(hass: HomeAssistant, config_entry: ConfigEntry, async_add_entities): @@ -20,24 +23,24 @@ async def async_setup_entry(hass: HomeAssistant, config_entry: ConfigEntry, asyn config_id = config_entry.entry_id coordinator = hass.data[DOMAIN][config_id][DATA_KEY_COORDINATOR] - if type(coordinator.data) is WashingMachineStatus: + if isinstance(coordinator.data, WashingMachineStatus): async_add_entities([ CandyWashingMachineSensor(coordinator, config_id), CandyWashCycleStatusSensor(coordinator, config_id), CandyWashRemainingTimeSensor(coordinator, config_id) ]) - elif type(coordinator.data) is TumbleDryerStatus: + elif isinstance(coordinator.data, TumbleDryerStatus): async_add_entities([ CandyTumbleDryerSensor(coordinator, config_id), CandyTumbleStatusSensor(coordinator, config_id), CandyTumbleRemainingTimeSensor(coordinator, config_id) ]) - elif type(coordinator.data) is OvenStatus: + elif isinstance(coordinator.data, OvenStatus): async_add_entities([ CandyOvenSensor(coordinator, config_id), CandyOvenTempSensor(coordinator, config_id) ]) - elif type(coordinator.data) is DishwasherStatus: + elif isinstance(coordinator.data, DishwasherStatus): async_add_entities([ CandyDishwasherSensor(coordinator, config_id), CandyDishwasherRemainingTimeSensor(coordinator, config_id) diff --git a/requirements_test.txt b/requirements_test.txt index eea05fa..de6d7f7 100644 --- a/requirements_test.txt +++ b/requirements_test.txt @@ -1,5 +1,4 @@ -pytest~=7.1 -pytest-homeassistant-custom-component==0.12.18 +pytest-homeassistant-custom-component==0.12.19 # Component dependencies backoff~=2.0 diff --git a/tests/test_client.py b/tests/test_client.py index 2ce24e6..0b987a2 100644 --- a/tests/test_client.py +++ b/tests/test_client.py @@ -1,14 +1,17 @@ import pytest +from homeassistant.helpers.aiohttp_client import async_get_clientsession from pytest_homeassistant_custom_component.common import load_fixture -from custom_components.candy.client import CandyClient, detect_encryption, Encryption -from custom_components.candy.client.model import MachineState, WashProgramState, WashingMachineStatus, DishwasherStatus -from .common import * +from custom_components.candy.client import (CandyClient, Encryption, + detect_encryption) +from custom_components.candy.client.model import (DishwasherStatus, + MachineState, + WashingMachineStatus, + WashProgramState) -from homeassistant.helpers.aiohttp_client import async_get_clientsession +from .common import * -@pytest.mark.asyncio async def test_idle(hass, aioclient_mock): """Test parsing the status when turning on the machine and selecting WiFi mode""" @@ -22,14 +25,13 @@ async def test_idle(hass, aioclient_mock): ) status = await client.status() - assert type(status) is WashingMachineStatus + assert isinstance(status, WashingMachineStatus) assert status.machine_state is MachineState.IDLE assert status.program_state is WashProgramState.STOPPED assert status.spin_speed == 800 assert status.temp == 40 -@pytest.mark.asyncio async def test_delayed_start_wait(hass, aioclient_mock): """Test parsing the status when machine is waiting for a delayed start wash cycle""" aioclient_mock.get( @@ -42,13 +44,12 @@ async def test_delayed_start_wait(hass, aioclient_mock): ) status = await client.status() - assert type(status) is WashingMachineStatus + assert isinstance(status, WashingMachineStatus) assert status.machine_state is MachineState.DELAYED_START_PROGRAMMED assert status.program_state is WashProgramState.STOPPED assert status.remaining_minutes == 50 -@pytest.mark.asyncio async def test_no_fillr_property(hass, aioclient_mock): """Test parsing the status when response doesn't contain the FillR property""" aioclient_mock.get( @@ -61,12 +62,11 @@ async def test_no_fillr_property(hass, aioclient_mock): ) status = await client.status() - assert type(status) is WashingMachineStatus + assert isinstance(status, WashingMachineStatus) assert status.machine_state is MachineState.IDLE assert status.fill_percent is None -@pytest.mark.asyncio async def test_detect_no_encryption(hass, aioclient_mock): aioclient_mock.get( f"http://{TEST_IP}/http-read.json?encrypted=0", @@ -79,7 +79,6 @@ async def test_detect_no_encryption(hass, aioclient_mock): assert key is None -@pytest.mark.asyncio async def test_detect_encryption_key(hass, aioclient_mock): aioclient_mock.get( f"http://{TEST_IP}/http-read.json?encrypted=0", @@ -97,7 +96,6 @@ async def test_detect_encryption_key(hass, aioclient_mock): assert key == TEST_ENCRYPTION_KEY -@pytest.mark.asyncio async def test_detect_encryption_without_key(hass, aioclient_mock): aioclient_mock.get( f"http://{TEST_IP}/http-read.json?encrypted=0", @@ -115,11 +113,10 @@ async def test_detect_encryption_without_key(hass, aioclient_mock): assert key is None -@pytest.mark.asyncio async def test_status_encryption_with_key(hass, aioclient_mock): aioclient_mock.get( f"http://{TEST_IP}/http-read.json", - text="2F7C6B441B390C094C3C42093A023429764B1A403343714A6B3D503902342E073D535B6F086854653240386F2E0C23283714243F4B250A0D1A7313085D416B4C5E78686F6A3E191C570D662C1E0B657B76434361344071611A0454390C2026333D120E6F0368484A14443B44644114353503151E4D25084A026B016F416E4D485D53353F5C23163D562613774F53656D597B68441B0F1B071A73137D4F4F4A4B5D78431D4B251F1A592413774F337263787C6B4430683D104C3B50091F1A657B76414361344071611A0641280327282E263E11391B705A581A653C47646A6505311D00346A3E191A4C6B0B6F5D416B4C5E78686F6B2F153C5124546F5741767364534D403343714A7520423E3E022B35764B437C1B66756231401300041034133D1F12281B705A581A653C47646A650E24140F0956250A4A026B016F416E4D485D5333284A2F0C4A026B016F416E4D485D5322255C29133D486B0B6F5D416B4C5E78686F4B7B5A521A7B136160694E487603536F0368484A14443B4464413572764B437F1B6675623140133F59417D6365534D403343714A4A7C13774F53656D597B68441B384E4A026B016F416E4D485D53137A1B705A5B1A653C47646A65336C535B6F086854653240386F1F5A657B763F3401756854653240386F1F5272636E53506F3440711535434C" + text="2F7C6B441B390C094C3C42093A023429764B1A403343714A6B3D503902342E073D535B6F086854653240386F2E0C23283714243F4B250A0D1A7313085D416B4C5E78686F6A3E191C570D662C1E0B657B76434361344071611A0454390C2026333D120E6F0368484A14443B44644114353503151E4D25084A026B016F416E4D485D53353F5C23163D562613774F53656D597B68441B0F1B071A73137D4F4F4A4B5D78431D4B251F1A592413774F337263787C6B4430683D104C3B50091F1A657B76414361344071611A0641280327282E263E11391B705A581A653C47646A6505311D00346A3E191A4C6B0B6F5D416B4C5E78686F6B2F153C5124546F5741767364534D403343714A7520423E3E022B35764B437C1B66756231401300041034133D1F12281B705A581A653C47646A650E24140F0956250A4A026B016F416E4D485D5333284A2F0C4A026B016F416E4D485D5322255C29133D486B0B6F5D416B4C5E78686F4B7B5A521A7B136160694E487603536F0368484A14443B4464413572764B437F1B6675623140133F59417D6365534D403343714A4A7C13774F53656D597B68441B384E4A026B016F416E4D485D53137A1B705A5B1A653C47646A65336C535B6F086854653240386F1F5A657B763F3401756854653240386F1F5272636E53506F3440711535434C" # pylint: disable=line-too-long ) client = CandyClient( @@ -127,17 +124,16 @@ async def test_status_encryption_with_key(hass, aioclient_mock): ) status = await client.status() - assert type(status) is DishwasherStatus + assert isinstance(status, DishwasherStatus) -@pytest.mark.asyncio async def test_status_encryption_without_key(hass, aioclient_mock): aioclient_mock.get( f"http://{TEST_IP}/http-read.json", - text="7B0D0A20202020227374617475734C6176617472696365223A7B0D0A2020202020202020202020202257694669537461747573223A2230222C0D0A20202020202020202020202022457272223A22323535222C0D0A202020202020202020202020224D6163684D64223A2232222C0D0A202020202020202020202020225072223A223133222C0D0A2020202020202020202020202250725068223A2235222C0D0A20202020202020202020202022534C6576656C223A22323535222C0D0A2020202020202020202020202254656D70223A2230222C0D0A202020202020202020202020225370696E5370223A2230222C0D0A202020202020202020202020224F707431223A2230222C0D0A202020202020202020202020224F707432223A2230222C0D0A202020202020202020202020224F707433223A2230222C0D0A202020202020202020202020224F707434223A2230222C0D0A202020202020202020202020224F707435223A2230222C0D0A202020202020202020202020224F707436223A2230222C0D0A202020202020202020202020224F707437223A2230222C0D0A202020202020202020202020224F707438223A2230222C0D0A20202020202020202020202022537465616D223A2230222C0D0A2020202020202020202020202244727954223A2230222C0D0A2020202020202020202020202244656C56616C223A22323535222C0D0A2020202020202020202020202252656D54696D65223A223130222C0D0A202020202020202020202020225265636970654964223A2230222C0D0A20202020202020202020202022436865636B55705374617465223A2230220D0A202020207D0D0A7D" + text="7B0D0A20202020227374617475734C6176617472696365223A7B0D0A2020202020202020202020202257694669537461747573223A2230222C0D0A20202020202020202020202022457272223A22323535222C0D0A202020202020202020202020224D6163684D64223A2232222C0D0A202020202020202020202020225072223A223133222C0D0A2020202020202020202020202250725068223A2235222C0D0A20202020202020202020202022534C6576656C223A22323535222C0D0A2020202020202020202020202254656D70223A2230222C0D0A202020202020202020202020225370696E5370223A2230222C0D0A202020202020202020202020224F707431223A2230222C0D0A202020202020202020202020224F707432223A2230222C0D0A202020202020202020202020224F707433223A2230222C0D0A202020202020202020202020224F707434223A2230222C0D0A202020202020202020202020224F707435223A2230222C0D0A202020202020202020202020224F707436223A2230222C0D0A202020202020202020202020224F707437223A2230222C0D0A202020202020202020202020224F707438223A2230222C0D0A20202020202020202020202022537465616D223A2230222C0D0A2020202020202020202020202244727954223A2230222C0D0A2020202020202020202020202244656C56616C223A22323535222C0D0A2020202020202020202020202252656D54696D65223A223130222C0D0A202020202020202020202020225265636970654964223A2230222C0D0A20202020202020202020202022436865636B55705374617465223A2230220D0A202020207D0D0A7D" # pylint: disable=line-too-long ) client = CandyClient(async_get_clientsession(hass), device_ip=TEST_IP, encryption_key="", use_encryption=True) status = await client.status() - assert type(status) is WashingMachineStatus + assert isinstance(status, WashingMachineStatus) diff --git a/tests/test_config_flow.py b/tests/test_config_flow.py index d29b4d0..391cbb4 100644 --- a/tests/test_config_flow.py +++ b/tests/test_config_flow.py @@ -57,7 +57,7 @@ def detect_encryption_without_key_fixture(): yield -async def test_no_encryption_detected(hass, detect_no_encryption): +async def test_no_encryption_detected(hass, detect_no_encryption): # pylint: disable=unused-argument """Test a successful config flow when detected encryption is no encryption.""" # Initialize a config flow @@ -84,7 +84,7 @@ async def test_no_encryption_detected(hass, detect_no_encryption): assert result["result"] -async def test_detected_encryption_and_key_found(hass, detect_encryption_find_key): +async def test_detected_encryption_and_key_found(hass, detect_encryption_find_key): # pylint: disable=unused-argument """Test a successful config flow when encryption is detected and key is found.""" # Initialize a config flow @@ -112,7 +112,7 @@ async def test_detected_encryption_and_key_found(hass, detect_encryption_find_ke assert result["result"] -async def test_detected_encryption_and_key_not_found(hass, detect_encryption_key_not_found): +async def test_detected_encryption_and_key_not_found(hass, detect_encryption_key_not_found): # pylint: disable=unused-argument """Test a failing config flow when encryption is detected and key is not found.""" # Initialize a config flow result = await hass.config_entries.flow.async_init( @@ -132,7 +132,7 @@ async def test_detected_encryption_and_key_not_found(hass, detect_encryption_key assert result["errors"] == {"base": "detect_encryption"} -async def test_detected_encryption_without_key(hass, detect_encryption_without_key): +async def test_detected_encryption_without_key(hass, detect_encryption_without_key): # pylint: disable=unused-argument """Test a successful config flow when encryption is detected without using a key.""" # Initialize a config flow result = await hass.config_entries.flow.async_init( diff --git a/tests/test_decryption.py b/tests/test_decryption.py index 7298b34..b7b9b76 100644 --- a/tests/test_decryption.py +++ b/tests/test_decryption.py @@ -1,4 +1,4 @@ - + # pylint: disable=line-too-long from custom_components.candy.client.decryption import find_key diff --git a/tests/test_sensor_dishwasher.py b/tests/test_sensor_dishwasher.py index 2c9cbda..0258773 100644 --- a/tests/test_sensor_dishwasher.py +++ b/tests/test_sensor_dishwasher.py @@ -1,8 +1,9 @@ """Tests for various sensors""" -from pytest_homeassistant_custom_component.common import MockConfigEntry, load_fixture -from pytest_homeassistant_custom_component.test_util.aiohttp import AiohttpClientMocker from homeassistant.core import HomeAssistant -from homeassistant.helpers import entity_registry, device_registry +from homeassistant.helpers import device_registry, entity_registry +from pytest_homeassistant_custom_component.common import load_fixture +from pytest_homeassistant_custom_component.test_util.aiohttp import \ + AiohttpClientMocker from .common import init_integration @@ -120,10 +121,10 @@ async def test_remaining_time_sensor_wash(hass: HomeAssistant, aioclient_mock: A async def test_main_sensor_device_info(hass: HomeAssistant, aioclient_mock: AiohttpClientMocker): await init_integration(hass, aioclient_mock, load_fixture("dishwasher/idle.json")) - er = entity_registry.async_get(hass) - dr = device_registry.async_get(hass) - entry = er.async_get("sensor.dishwasher") - device = dr.async_get(entry.device_id) + entity_reg = entity_registry.async_get(hass) + device_reg = device_registry.async_get(hass) + entry = entity_reg.async_get("sensor.dishwasher") + device = device_reg.async_get(entry.device_id) assert device assert device.manufacturer == "Candy" @@ -134,14 +135,14 @@ async def test_main_sensor_device_info(hass: HomeAssistant, aioclient_mock: Aioh async def test_sensors_device_info(hass: HomeAssistant, aioclient_mock: AiohttpClientMocker): await init_integration(hass, aioclient_mock, load_fixture("dishwasher/idle.json")) - er = entity_registry.async_get(hass) - dr = device_registry.async_get(hass) + entity_reg = entity_registry.async_get(hass) + device_reg = device_registry.async_get(hass) - main_sensor = er.async_get("sensor.dishwasher") - time_sensor = er.async_get("sensor.dishwasher_remaining_time") + main_sensor = entity_reg.async_get("sensor.dishwasher") + time_sensor = entity_reg.async_get("sensor.dishwasher_remaining_time") - main_device = dr.async_get(main_sensor.device_id) - time_device = dr.async_get(time_sensor.device_id) + main_device = device_reg.async_get(main_sensor.device_id) + time_device = device_reg.async_get(time_sensor.device_id) assert main_device assert time_device diff --git a/tests/test_sensor_oven.py b/tests/test_sensor_oven.py index 51412cd..c0d980b 100644 --- a/tests/test_sensor_oven.py +++ b/tests/test_sensor_oven.py @@ -1,8 +1,9 @@ """Tests for various sensors""" -from pytest_homeassistant_custom_component.common import MockConfigEntry, load_fixture -from pytest_homeassistant_custom_component.test_util.aiohttp import AiohttpClientMocker from homeassistant.core import HomeAssistant -from homeassistant.helpers import entity_registry, device_registry +from homeassistant.helpers import device_registry, entity_registry +from pytest_homeassistant_custom_component.common import (load_fixture) +from pytest_homeassistant_custom_component.test_util.aiohttp import \ + AiohttpClientMocker from .common import init_integration @@ -80,10 +81,10 @@ async def test_temp_sensor_heating(hass: HomeAssistant, aioclient_mock: AiohttpC async def test_main_sensor_device_info(hass: HomeAssistant, aioclient_mock: AiohttpClientMocker): await init_integration(hass, aioclient_mock, load_fixture("oven/idle.json")) - er = entity_registry.async_get(hass) - dr = device_registry.async_get(hass) - entry = er.async_get("sensor.oven") - device = dr.async_get(entry.device_id) + entity_reg = entity_registry.async_get(hass) + device_reg = device_registry.async_get(hass) + entry = entity_reg.async_get("sensor.oven") + device = device_reg.async_get(entry.device_id) assert device assert device.manufacturer == "Candy" @@ -94,14 +95,14 @@ async def test_main_sensor_device_info(hass: HomeAssistant, aioclient_mock: Aioh async def test_sensors_device_info(hass: HomeAssistant, aioclient_mock: AiohttpClientMocker): await init_integration(hass, aioclient_mock, load_fixture("oven/idle.json")) - er = entity_registry.async_get(hass) - dr = device_registry.async_get(hass) + entity_reg = entity_registry.async_get(hass) + device_reg = device_registry.async_get(hass) - main_sensor = er.async_get("sensor.oven") - temp_sensor = er.async_get("sensor.oven_temperature") + main_sensor = entity_reg.async_get("sensor.oven") + temp_sensor = entity_reg.async_get("sensor.oven_temperature") - main_device = dr.async_get(main_sensor.device_id) - temp_device = dr.async_get(temp_sensor.device_id) + main_device = device_reg.async_get(main_sensor.device_id) + temp_device = device_reg.async_get(temp_sensor.device_id) assert main_device assert temp_device diff --git a/tests/test_sensor_tumble_dryer.py b/tests/test_sensor_tumble_dryer.py index 8fb6c35..6ea780a 100644 --- a/tests/test_sensor_tumble_dryer.py +++ b/tests/test_sensor_tumble_dryer.py @@ -1,8 +1,9 @@ """Tests for various sensors""" -from pytest_homeassistant_custom_component.common import MockConfigEntry, load_fixture -from pytest_homeassistant_custom_component.test_util.aiohttp import AiohttpClientMocker from homeassistant.core import HomeAssistant -from homeassistant.helpers import entity_registry, device_registry +from homeassistant.helpers import device_registry, entity_registry +from pytest_homeassistant_custom_component.common import load_fixture +from pytest_homeassistant_custom_component.test_util.aiohttp import \ + AiohttpClientMocker from .common import init_integration @@ -108,10 +109,10 @@ async def test_remaining_time_sensor_running(hass: HomeAssistant, aioclient_mock async def test_main_sensor_device_info(hass: HomeAssistant, aioclient_mock: AiohttpClientMocker): await init_integration(hass, aioclient_mock, load_fixture("tumble_dryer/idle.json")) - er = entity_registry.async_get(hass) - dr = device_registry.async_get(hass) - entry = er.async_get("sensor.tumble_dryer") - device = dr.async_get(entry.device_id) + entity_reg = entity_registry.async_get(hass) + device_reg = device_registry.async_get(hass) + entry = entity_reg.async_get("sensor.tumble_dryer") + device = device_reg.async_get(entry.device_id) assert device assert device.manufacturer == "Candy" @@ -122,16 +123,16 @@ async def test_main_sensor_device_info(hass: HomeAssistant, aioclient_mock: Aioh async def test_sensors_device_info(hass: HomeAssistant, aioclient_mock: AiohttpClientMocker): await init_integration(hass, aioclient_mock, load_fixture("tumble_dryer/idle.json")) - er = entity_registry.async_get(hass) - dr = device_registry.async_get(hass) + entity_reg = entity_registry.async_get(hass) + device_reg = device_registry.async_get(hass) - main_sensor = er.async_get("sensor.tumble_dryer") - cycle_sensor = er.async_get("sensor.dryer_cycle_status") - time_sensor = er.async_get("sensor.dryer_cycle_remaining_time") + main_sensor = entity_reg.async_get("sensor.tumble_dryer") + cycle_sensor = entity_reg.async_get("sensor.dryer_cycle_status") + time_sensor = entity_reg.async_get("sensor.dryer_cycle_remaining_time") - main_device = dr.async_get(main_sensor.device_id) - cycle_device = dr.async_get(cycle_sensor.device_id) - time_device = dr.async_get(time_sensor.device_id) + main_device = device_reg.async_get(main_sensor.device_id) + cycle_device = device_reg.async_get(cycle_sensor.device_id) + time_device = device_reg.async_get(time_sensor.device_id) assert main_device assert cycle_device diff --git a/tests/test_sensor_washing_machine.py b/tests/test_sensor_washing_machine.py index a6f48a6..4b08ec1 100644 --- a/tests/test_sensor_washing_machine.py +++ b/tests/test_sensor_washing_machine.py @@ -1,8 +1,9 @@ """Tests for various sensors""" -from pytest_homeassistant_custom_component.common import MockConfigEntry, load_fixture -from pytest_homeassistant_custom_component.test_util.aiohttp import AiohttpClientMocker from homeassistant.core import HomeAssistant -from homeassistant.helpers import entity_registry, device_registry +from homeassistant.helpers import device_registry, entity_registry +from pytest_homeassistant_custom_component.common import load_fixture +from pytest_homeassistant_custom_component.test_util.aiohttp import \ + AiohttpClientMocker from .common import init_integration @@ -109,10 +110,10 @@ async def test_main_sensor_no_pr(hass: HomeAssistant, aioclient_mock: AiohttpCli async def test_main_sensor_device_info(hass: HomeAssistant, aioclient_mock: AiohttpClientMocker): await init_integration(hass, aioclient_mock, load_fixture("washing_machine/idle.json")) - er = entity_registry.async_get(hass) - dr = device_registry.async_get(hass) - entry = er.async_get("sensor.washing_machine") - device = dr.async_get(entry.device_id) + entity_reg = entity_registry.async_get(hass) + device_reg = device_registry.async_get(hass) + entry = entity_reg.async_get("sensor.washing_machine") + device = device_reg.async_get(entry.device_id) assert device assert device.manufacturer == "Candy" @@ -123,16 +124,16 @@ async def test_main_sensor_device_info(hass: HomeAssistant, aioclient_mock: Aioh async def test_sensors_device_info(hass: HomeAssistant, aioclient_mock: AiohttpClientMocker): await init_integration(hass, aioclient_mock, load_fixture("washing_machine/idle.json")) - er = entity_registry.async_get(hass) - dr = device_registry.async_get(hass) + entity_reg = entity_registry.async_get(hass) + device_reg = device_registry.async_get(hass) - main_sensor = er.async_get("sensor.washing_machine") - cycle_sensor = er.async_get("sensor.wash_cycle_status") - time_sensor = er.async_get("sensor.wash_cycle_remaining_time") + main_sensor = entity_reg.async_get("sensor.washing_machine") + cycle_sensor = entity_reg.async_get("sensor.wash_cycle_status") + time_sensor = entity_reg.async_get("sensor.wash_cycle_remaining_time") - main_device = dr.async_get(main_sensor.device_id) - cycle_device = dr.async_get(cycle_sensor.device_id) - time_device = dr.async_get(time_sensor.device_id) + main_device = device_reg.async_get(main_sensor.device_id) + cycle_device = device_reg.async_get(cycle_sensor.device_id) + time_device = device_reg.async_get(time_sensor.device_id) assert main_device assert cycle_device