Skip to content

Commit

Permalink
Remove DisplayNameIntEnum (#469)
Browse files Browse the repository at this point in the history
  • Loading branch information
edenhaus authored Apr 12, 2024
1 parent 7c2cf9d commit 75d1e3a
Show file tree
Hide file tree
Showing 16 changed files with 32 additions and 110 deletions.
3 changes: 2 additions & 1 deletion deebot_client/commands/json/efficiency.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
from deebot_client.command import InitParam
from deebot_client.events import EfficiencyMode, EfficiencyModeEvent
from deebot_client.message import HandlingResult
from deebot_client.util import get_enum

from .common import JsonGetCommand, JsonSetCommand

Expand Down Expand Up @@ -41,5 +42,5 @@ class SetEfficiencyMode(JsonSetCommand):

def __init__(self, efficiency: EfficiencyMode | str) -> None:
if isinstance(efficiency, str):
efficiency = EfficiencyMode.get(efficiency)
efficiency = get_enum(EfficiencyMode, efficiency)
super().__init__({"efficiency": efficiency.value})
3 changes: 2 additions & 1 deletion deebot_client/commands/json/fan_speed.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
from deebot_client.command import InitParam
from deebot_client.events import FanSpeedEvent, FanSpeedLevel
from deebot_client.message import HandlingResult
from deebot_client.util import get_enum

from .common import JsonGetCommand, JsonSetCommand

Expand Down Expand Up @@ -41,5 +42,5 @@ class SetFanSpeed(JsonSetCommand):

def __init__(self, speed: FanSpeedLevel | str) -> None:
if isinstance(speed, str):
speed = FanSpeedLevel.get(speed)
speed = get_enum(FanSpeedLevel, speed)
super().__init__({"speed": speed.value})
3 changes: 2 additions & 1 deletion deebot_client/commands/json/water_info.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
from deebot_client.command import InitParam
from deebot_client.events import WaterAmount, WaterInfoEvent
from deebot_client.message import HandlingResult
from deebot_client.util import get_enum

from .common import JsonGetCommand, JsonSetCommand

Expand Down Expand Up @@ -52,5 +53,5 @@ class SetWaterInfo(JsonSetCommand):

def __init__(self, amount: WaterAmount | str) -> None:
if isinstance(amount, str):
amount = WaterAmount.get(amount)
amount = get_enum(WaterAmount, amount)
super().__init__({"amount": amount.value})
3 changes: 2 additions & 1 deletion deebot_client/commands/json/work_mode.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
from deebot_client.command import InitParam
from deebot_client.events import WorkMode, WorkModeEvent
from deebot_client.message import HandlingResult
from deebot_client.util import get_enum

from .common import JsonGetCommand, JsonSetCommand

Expand Down Expand Up @@ -41,5 +42,5 @@ class SetWorkMode(JsonSetCommand):

def __init__(self, mode: WorkMode | str) -> None:
if isinstance(mode, str):
mode = WorkMode.get(mode)
mode = get_enum(WorkMode, mode)
super().__init__({"mode": mode.value})
1 change: 1 addition & 0 deletions deebot_client/events/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,7 @@ class BatteryEvent(Event):
value: int


@unique
class CleanJobStatus(IntEnum):
"""Enum of the different clean job status."""

Expand Down
6 changes: 3 additions & 3 deletions deebot_client/events/efficiency_mode.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,13 @@
from __future__ import annotations

from dataclasses import dataclass

from deebot_client.util import DisplayNameIntEnum
from enum import IntEnum, unique

from .base import Event


class EfficiencyMode(DisplayNameIntEnum):
@unique
class EfficiencyMode(IntEnum):
"""Enum class for all possible efficiency modes."""

STANDARD_MODE = 0
Expand Down
6 changes: 3 additions & 3 deletions deebot_client/events/fan_speed.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,13 @@
from __future__ import annotations

from dataclasses import dataclass

from deebot_client.util import DisplayNameIntEnum
from enum import IntEnum, unique

from .base import Event


class FanSpeedLevel(DisplayNameIntEnum):
@unique
class FanSpeedLevel(IntEnum):
"""Enum class for all possible fan speed levels."""

# Values should be sort from low to high on their meanings
Expand Down
6 changes: 3 additions & 3 deletions deebot_client/events/water_info.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,13 @@
from __future__ import annotations

from dataclasses import dataclass, field

from deebot_client.util import DisplayNameIntEnum
from enum import IntEnum, unique

from .base import Event


class WaterAmount(DisplayNameIntEnum):
@unique
class WaterAmount(IntEnum):
"""Enum class for all possible water amounts."""

LOW = 1
Expand Down
6 changes: 3 additions & 3 deletions deebot_client/events/work_mode.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,13 @@
from __future__ import annotations

from dataclasses import dataclass

from deebot_client.util import DisplayNameIntEnum
from enum import IntEnum, unique

from .base import Event


class WorkMode(DisplayNameIntEnum):
@unique
class WorkMode(IntEnum):
"""Enum class for all possible work modes."""

VACUUM_AND_MOP = 0
Expand Down
58 changes: 11 additions & 47 deletions deebot_client/util/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,17 +5,17 @@
import asyncio
import base64
from contextlib import suppress
from enum import IntEnum, unique
from enum import Enum
import hashlib
import lzma
from typing import TYPE_CHECKING, Any, Self, TypeVar
from typing import TYPE_CHECKING, Any, TypeVar

from deebot_client.logging_filter import get_logger

_LOGGER = get_logger(__name__)

if TYPE_CHECKING:
from collections.abc import Callable, Coroutine, Iterable, Mapping
from collections.abc import Callable, Coroutine, Iterable

_T = TypeVar("_T")

Expand Down Expand Up @@ -62,53 +62,17 @@ async def cancel(tasks: set[asyncio.Future[Any]]) -> None:
await asyncio.gather(*tasks_to_wait)


@unique
class DisplayNameIntEnum(IntEnum):
"""Int enum with a property "display_name"."""
_S = TypeVar("_S", bound=Enum)

def __new__(cls, *args: int, **_: Mapping[Any, Any]) -> Self:
"""Create new DisplayNameIntEnum."""
obj = int.__new__(cls)
obj._value_ = args[0]
return obj

def __init__(self, value: int, display_name: str | None = None) -> None:
super().__init__()
self._value_ = value
self._display_name = display_name
def get_enum(enum: type[_S], value: str) -> _S:
"""Get enum member from name."""
value = value.upper()
if value in enum.__members__:
return enum[value]

@property
def display_name(self) -> str:
"""Return the custom display name or the lowered name property."""
if self._display_name:
return self._display_name

return self.name.lower()

@classmethod
def get(cls, value: str) -> Self:
"""Get enum member from name or display_name."""
value = str(value).upper()
if value in cls.__members__:
return cls[value]

for member in cls:
if value == member.display_name.upper():
return member

msg = f"'{value}' is not a valid {cls.__name__} member"
raise ValueError(msg)

def __eq__(self, x: object) -> bool:
if not isinstance(x, type(self)):
return False
return bool(self._value_ == x._value_)

def __ne__(self, x: object) -> bool:
return not self.__eq__(x)

def __hash__(self) -> int:
return hash(self._value_)
msg = f"'{value}' is not a valid {enum.__name__} member"
raise ValueError(msg)


class OnChangedList(list[_T]):
Expand Down
5 changes: 0 additions & 5 deletions tests/commands/json/test_efficiency.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,16 +9,11 @@
from tests.helpers import (
get_request_json,
get_success_body,
verify_DisplayNameEnum_unique,
)

from . import assert_command, assert_set_command


def test_WorkMode_unique() -> None:
verify_DisplayNameEnum_unique(EfficiencyMode)


@pytest.mark.parametrize(
("json", "expected"),
[
Expand Down
5 changes: 0 additions & 5 deletions tests/commands/json/test_fan_speed.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,16 +8,11 @@
from tests.helpers import (
get_request_json,
get_success_body,
verify_DisplayNameEnum_unique,
)

from . import assert_command, assert_set_command


def test_FanSpeedLevel_unique() -> None:
verify_DisplayNameEnum_unique(FanSpeedLevel)


async def test_GetFanSpeed() -> None:
json = get_request_json(get_success_body({"speed": 2}))
await assert_command(GetFanSpeed(), json, FanSpeedEvent(FanSpeedLevel.MAX_PLUS))
Expand Down
5 changes: 0 additions & 5 deletions tests/commands/json/test_water_info.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,16 +9,11 @@
from tests.helpers import (
get_request_json,
get_success_body,
verify_DisplayNameEnum_unique,
)

from . import assert_command, assert_set_command


def test_WaterAmount_unique() -> None:
verify_DisplayNameEnum_unique(WaterAmount)


@pytest.mark.parametrize(
("json", "expected"),
[
Expand Down
5 changes: 0 additions & 5 deletions tests/commands/json/test_work_mode.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,16 +9,11 @@
from tests.helpers import (
get_request_json,
get_success_body,
verify_DisplayNameEnum_unique,
)

from . import assert_command, assert_set_command


def test_WorkMode_unique() -> None:
verify_DisplayNameEnum_unique(WorkMode)


@pytest.mark.parametrize(
("json", "expected"),
[
Expand Down
8 changes: 0 additions & 8 deletions tests/events/test_water_info.py

This file was deleted.

19 changes: 0 additions & 19 deletions tests/helpers/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@
from deebot_client.capabilities import Capabilities
from deebot_client.const import DataType
from deebot_client.models import StaticDeviceInfo
from deebot_client.util import DisplayNameIntEnum

if TYPE_CHECKING:
from collections.abc import Mapping
Expand All @@ -15,24 +14,6 @@
from deebot_client.events.base import Event


def verify_DisplayNameEnum_unique(enum: type[DisplayNameIntEnum]) -> None:
assert issubclass(enum, DisplayNameIntEnum)
names: set[str] = set()
values: set[int] = set()
for member in enum:
assert member.value not in values
values.add(member.value)

name = member.name.lower()
assert name not in names
names.add(name)

display_name = member.display_name.lower()
if display_name != name:
assert display_name not in names
names.add(display_name)


def get_request_json(body: dict[str, Any]) -> dict[str, Any]:
return {"id": "ALZf", "ret": "ok", "resp": get_message_json(body)}

Expand Down

0 comments on commit 75d1e3a

Please sign in to comment.