Skip to content

Commit

Permalink
Fix SIM, T (return) and bugbear warnings
Browse files Browse the repository at this point in the history
  • Loading branch information
rytilahti committed Feb 7, 2021
1 parent 85c2c45 commit 8c5a7cc
Show file tree
Hide file tree
Showing 17 changed files with 95 additions and 89 deletions.
9 changes: 5 additions & 4 deletions devtools/containers.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ def python_type_for_type(x):
return "int"
if x == "string":
return "str"
if x == "float" or x == "bool":
if x in ["float", "bool"]:
return x

return f"unknown type {x}"
Expand All @@ -40,10 +40,11 @@ class ModelMapping(DataClassJsonMixin):
instances: List[InstanceInfo]

def urn_for_model(self, model: str):
matches = [inst.type for inst in self.instances if inst.model == model]
matches = [inst for inst in self.instances if inst.model == model]
if len(matches) > 1:
print(
"WARNING more than a single match for model %s: %s" % (model, matches)
print( # noqa: T001
"WARNING more than a single match for model %s, using the first one: %s"
% (model, matches)
)

return matches[0]
Expand Down
6 changes: 3 additions & 3 deletions devtools/miottemplate.py
Original file line number Diff line number Diff line change
Expand Up @@ -79,12 +79,12 @@ def generate(file):
)
data = file.read()
gen = Generator(data)
print(gen.generate())
click.echo(gen.generate())


@cli.command()
@cli.command(name="print")
@click.argument("file", type=click.File())
def print(file):
def _print(file):
"""Print out device information (props, actions, events)."""
data = file.read()
gen = Generator(data)
Expand Down
4 changes: 3 additions & 1 deletion miio/airconditioningcompanionMCN.py
Original file line number Diff line number Diff line change
Expand Up @@ -126,11 +126,13 @@ def __init__(
self,
ip: str = None,
token: str = None,
start_id: int = random.randint(0, 999),
start_id: int = None,
debug: int = 0,
lazy_discover: bool = True,
model: str = MODEL_ACPARTNER_MCN02,
) -> None:
if start_id is None:
start_id = random.randint(0, 999)
super().__init__(ip, token, start_id, debug, lazy_discover)

if model != MODEL_ACPARTNER_MCN02:
Expand Down
4 changes: 3 additions & 1 deletion miio/chuangmi_camera.py
Original file line number Diff line number Diff line change
Expand Up @@ -395,11 +395,13 @@ def get_nas_config(self):
def set_nas_config(
self,
state: NASState,
share={},
share=None,
sync_interval: NASSyncInterval = NASSyncInterval.Realtime,
video_retention_time: NASVideoRetentionTime = NASVideoRetentionTime.Week,
):
"""Set NAS configuration."""
if share is None:
share = {}
return self.send(
"nas_set_config",
{
Expand Down
15 changes: 8 additions & 7 deletions miio/chuangmi_ir.py
Original file line number Diff line number Diff line change
Expand Up @@ -144,17 +144,18 @@ def play(self, command: str):
else:
command_type, command, *command_args = command.split(":")

arg_types = [int]
if len(command_args) > len(arg_types):
raise ChuangmiIrException("Invalid command arguments count")

if command_type not in ["raw", "pronto"]:
raise ChuangmiIrException("Invalid command type")

if command_type == "raw":
play_method = self.play_raw
arg_types = [int]

elif command_type == "pronto":
play_method = self.play_pronto
arg_types = [int]
else:
raise ChuangmiIrException("Invalid command type")

if len(command_args) > len(arg_types):
raise ChuangmiIrException("Invalid command arguments count")

try:
command_args = [t(v) for v, t in zip(command_args, arg_types)]
Expand Down
4 changes: 2 additions & 2 deletions miio/click_common.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
from .exceptions import DeviceError

if sys.version_info < (3, 5):
print(
click.echo(
"To use this script you need python 3.5 or newer, got %s" % (sys.version_info,)
)
sys.exit(1)
Expand Down Expand Up @@ -124,7 +124,7 @@ def __new__(mcs, name, bases, namespace) -> type:

def _get_commands_for_namespace(namespace):
commands = {}
for key, val in namespace.items():
for _, val in namespace.items():
if not callable(val):
continue
device_group_command = getattr(val, "_device_group_command", None)
Expand Down
7 changes: 4 additions & 3 deletions miio/fan_miot.py
Original file line number Diff line number Diff line change
Expand Up @@ -176,10 +176,11 @@ def __init__(
lazy_discover: bool = True,
model: str = MODEL_FAN_P10,
) -> None:
if model in MIOT_MAPPING:
self.model = model
else:
if model not in MIOT_MAPPING:
raise FanException("Invalid FanMiot model: %s" % model)

self.model = model

super().__init__(MIOT_MAPPING[model], ip, token, start_id, debug, lazy_discover)

@command(
Expand Down
30 changes: 15 additions & 15 deletions miio/miioprotocol.py
Original file line number Diff line number Diff line change
Expand Up @@ -69,24 +69,24 @@ def send_handshake(self, *, retry_count=3) -> Message:

raise ex

if m is not None:
header = m.header.value
self._device_id = header.device_id
self._device_ts = header.ts
self._discovered = True

if self.debug > 1:
_LOGGER.debug(m)
_LOGGER.debug(
"Discovered %s with ts: %s, token: %s",
binascii.hexlify(self._device_id).decode(),
self._device_ts,
codecs.encode(m.checksum, "hex"),
)
else:
if m is None:
_LOGGER.debug("Unable to discover a device at address %s", self.ip)
raise DeviceException("Unable to discover the device %s" % self.ip)

header = m.header.value
self._device_id = header.device_id
self._device_ts = header.ts
self._discovered = True

if self.debug > 1:
_LOGGER.debug(m)
_LOGGER.debug(
"Discovered %s with ts: %s, token: %s",
binascii.hexlify(self._device_id).decode(),
self._device_ts,
codecs.encode(m.checksum, "hex"),
)

return m

@staticmethod
Expand Down
12 changes: 6 additions & 6 deletions miio/tests/test_airhumidifier_jsq.py
Original file line number Diff line number Diff line change
Expand Up @@ -169,17 +169,17 @@ def mode():

with pytest.raises(AirHumidifierException) as excinfo:
self.device.set_mode(Bunch(value=10))
assert "10 is not a valid OperationMode value" == str(excinfo.value)
assert str(excinfo.value) == "10 is not a valid OperationMode value"
assert mode() == OperationMode.Level3

with pytest.raises(AirHumidifierException) as excinfo:
self.device.set_mode(Bunch(value=-1))
assert "-1 is not a valid OperationMode value" == str(excinfo.value)
assert str(excinfo.value) == "-1 is not a valid OperationMode value"
assert mode() == OperationMode.Level3

with pytest.raises(AirHumidifierException) as excinfo:
self.device.set_mode(Bunch(value="smth"))
assert "smth is not a valid OperationMode value" == str(excinfo.value)
assert str(excinfo.value) == "smth is not a valid OperationMode value"
assert mode() == OperationMode.Level3

def test_set_led_brightness(self):
Expand All @@ -204,17 +204,17 @@ def led_brightness():

with pytest.raises(AirHumidifierException) as excinfo:
self.device.set_led_brightness(Bunch(value=10))
assert "10 is not a valid LedBrightness value" == str(excinfo.value)
assert str(excinfo.value) == "10 is not a valid LedBrightness value"
assert led_brightness() == LedBrightness.Low

with pytest.raises(AirHumidifierException) as excinfo:
self.device.set_led_brightness(Bunch(value=-10))
assert "-10 is not a valid LedBrightness value" == str(excinfo.value)
assert str(excinfo.value) == "-10 is not a valid LedBrightness value"
assert led_brightness() == LedBrightness.Low

with pytest.raises(AirHumidifierException) as excinfo:
self.device.set_led_brightness(Bunch(value="smth"))
assert "smth is not a valid LedBrightness value" == str(excinfo.value)
assert str(excinfo.value) == "smth is not a valid LedBrightness value"
assert led_brightness() == LedBrightness.Low

def test_set_led(self):
Expand Down
6 changes: 3 additions & 3 deletions miio/tests/test_device.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,15 +22,15 @@ def test_get_properties_splitting(mocker, max_properties):
def test_default_timeout_and_retry(mocker):
send = mocker.patch("miio.miioprotocol.MiIOProtocol.send")
d = Device("127.0.0.1", "68ffffffffffffffffffffffffffffff")
assert 5 == d._protocol._timeout
assert d._protocol._timeout == 5
d.send(command="fake_command", parameters=[])
send.assert_called_with("fake_command", [], 3, extra_parameters=None)


def test_timeout_retry(mocker):
send = mocker.patch("miio.miioprotocol.MiIOProtocol.send")
d = Device("127.0.0.1", "68ffffffffffffffffffffffffffffff", timeout=4)
assert 4 == d._protocol._timeout
assert d._protocol._timeout == 4
d.send("fake_command", [], 1)
send.assert_called_with("fake_command", [], 1, extra_parameters=None)
d.send("fake_command", [])
Expand All @@ -41,7 +41,7 @@ class CustomDevice(Device):
timeout = 1

d2 = CustomDevice("127.0.0.1", "68ffffffffffffffffffffffffffffff")
assert 1 == d2._protocol._timeout
assert d2._protocol._timeout == 1
d2.send("fake_command", [])
send.assert_called_with("fake_command", [], 5, extra_parameters=None)

Expand Down
21 changes: 11 additions & 10 deletions miio/tests/test_toiletlid.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,20 +49,20 @@ def __init__(self, *args, **kwargs):
def set_aled_v_of_uid(self, args):
uid, color = args
if uid:
if uid in self.users:
self.users.setdefault("ambient_light", AmbientLightColor(color).name)
else:
if uid not in self.users:
raise ValueError("This user is not bind.")

self.users.setdefault("ambient_light", AmbientLightColor(color).name)
else:
return self._set_state("ambient_light", [AmbientLightColor(color).name])

def get_aled_v_of_uid(self, args):
uid = args[0]
if uid:
if uid in self.users:
color = self.users.get("ambient_light")
else:
raise ValueError("This user is not bind.")
if uid not in self.users:
raise ValueError("This user is not b.")

color = self.users.get("ambient_light")
else:
color = self._get_state(["ambient_light"])
if not AmbientLightColor._member_map_.get(color[0]):
Expand All @@ -71,15 +71,16 @@ def get_aled_v_of_uid(self, args):

def uid_mac_op(self, args):
xiaomi_id, band_mac, alias, operating = args
if operating not in ["bind", "unbind"]:
raise ValueError("operating not bind or unbind, but %s" % operating)

if operating == "bind":
info = self.users.setdefault(
xiaomi_id, {"rssi": -50, "set": "3-0-2-2-0-0-5-5"}
)
info.update(mac=band_mac, name=alias)
elif operating == "unbind":
self.users.pop(xiaomi_id)
else:
raise ValueError("operating error")

def get_all_user_info(self):
users = {}
Expand Down Expand Up @@ -141,7 +142,7 @@ def test_nozzle_clean(self):

def test_get_all_user_info(self):
users = self.device.get_all_user_info()
for name, info in users.items():
for _name, info in users.items():
assert info["uid"] in self.MOCK_USER
data = self.MOCK_USER[info["uid"]]
assert info["name"] == data["name"]
Expand Down
1 change: 0 additions & 1 deletion miio/tests/test_yeelight_dual_switch.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,6 @@ def switch(request):
class TestYeelightDualControlModule(TestCase):
def test_1_on(self):
self.device.off(Switch.First) # ensure off
print(self.device.status())
assert self.device.status().switch_1_state is False

self.device.on(Switch.First)
Expand Down
4 changes: 2 additions & 2 deletions miio/updater.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ class OneShotServer:
def __init__(self, file, interface=None):
addr = ("", 0)
self.server = HTTPServer(addr, SingleFileHandler)
setattr(self.server, "got_request", False)
setattr(self.server, "got_request", False) # noqa: B010

self.addr, self.port = self.server.server_address
self.server.timeout = 10
Expand Down Expand Up @@ -83,7 +83,7 @@ def url(self, ip=None):

def serve_once(self):
self.server.handle_request()
if getattr(self.server, "got_request"):
if getattr(self.server, "got_request"): # noqa: B009
_LOGGER.info("Got a request, should be downloading now.")
return True
else:
Expand Down
2 changes: 1 addition & 1 deletion miio/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ def new_func1(*args, **kwargs):

return decorator

elif inspect.isclass(reason) or inspect.isfunction(reason):
elif inspect.isclass(reason) or inspect.isfunction(reason): # noqa: SIM106

# The @deprecated is used without any 'reason'.
#
Expand Down
26 changes: 14 additions & 12 deletions miio/vacuum.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import contextlib
import datetime
import enum
import json
Expand Down Expand Up @@ -284,22 +285,24 @@ def edit_map(self, start):
@command(click.option("--version", default=1))
def fresh_map(self, version):
"""Return fresh map?"""
if version not in [1, 2]:
raise VacuumException("Unknown map version: %s" % version)

if version == 1:
return self.send("get_fresh_map")
elif version == 2:
return self.send("get_fresh_map_v2")
else:
raise VacuumException("Unknown map version: %s" % version)

@command(click.option("--version", default=1))
def persist_map(self, version):
"""Return fresh map?"""
if version not in [1, 2]:
raise VacuumException("Unknown map version: %s" % version)

if version == 1:
return self.send("get_persist_map")
elif version == 2:
return self.send("get_persist_map_v2")
else:
raise VacuumException("Unknown map version: %s" % version)

@command(
click.argument("x1", type=int),
Expand Down Expand Up @@ -728,14 +731,13 @@ def callback(ctx, *args, id_file, **kwargs):
kwargs["debug"] = gco.debug

start_id = manual_seq = 0
try:
with open(id_file, "r") as f:
x = json.load(f)
start_id = x.get("seq", 0)
manual_seq = x.get("manual_seq", 0)
_LOGGER.debug("Read stored sequence ids: %s", x)
except (FileNotFoundError, TypeError, ValueError):
pass
with open(id_file, "r") as f, contextlib.suppress(
FileNotFoundError, TypeError, ValueError
):
x = json.load(f)
start_id = x.get("seq", 0)
manual_seq = x.get("manual_seq", 0)
_LOGGER.debug("Read stored sequence ids: %s", x)

ctx.obj = cls(*args, start_id=start_id, **kwargs)
ctx.obj.manual_seqnum = manual_seq
Expand Down
Loading

0 comments on commit 8c5a7cc

Please sign in to comment.