File: test_airconditioningcompanion.py

package info (click to toggle)
python-miio 0.5.0.1-2
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 1,288 kB
  • sloc: python: 14,798; makefile: 20
file content (299 lines) | stat: -rw-r--r-- 9,750 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
import json
import os
import string
from unittest import TestCase

import pytest

from miio import AirConditioningCompanion, AirConditioningCompanionV3
from miio.airconditioningcompanion import (
    MODEL_ACPARTNER_V3,
    STORAGE_SLOT_ID,
    AirConditioningCompanionException,
    AirConditioningCompanionStatus,
    FanSpeed,
    Led,
    OperationMode,
    Power,
    SwingMode,
)
from miio.tests.dummies import DummyDevice

STATE_ON = ["on"]
STATE_OFF = ["off"]

PUBLIC_ENUMS = {
    "OperationMode": OperationMode,
    "FanSpeed": FanSpeed,
    "Power": Power,
    "SwingMode": SwingMode,
    "Led": Led,
}


def as_enum(d):
    if "__enum__" in d:
        name, member = d["__enum__"].split(".")
        return getattr(PUBLIC_ENUMS[name], member)
    else:
        return d


with open(
    os.path.join(os.path.dirname(__file__), "test_airconditioningcompanion.json")
) as inp:
    test_data = json.load(inp, object_hook=as_enum)


class EnumEncoder(json.JSONEncoder):
    def default(self, obj):
        if type(obj) in PUBLIC_ENUMS.values():
            return {"__enum__": str(obj)}
        return json.JSONEncoder.default(self, obj)


class DummyAirConditioningCompanion(DummyDevice, AirConditioningCompanion):
    def __init__(self, *args, **kwargs):
        self.state = ["010500978022222102", "01020119A280222221", "2"]
        self.last_ir_played = None

        self.return_values = {
            "get_model_and_state": self._get_state,
            "start_ir_learn": lambda x: True,
            "end_ir_learn": lambda x: True,
            "get_ir_learn_result": lambda x: True,
            "send_ir_code": lambda x: self._send_input_validation(x),
            "send_cmd": lambda x: self._send_input_validation(x),
            "set_power": lambda x: self._set_power(x),
        }
        self.start_state = self.state.copy()
        super().__init__(args, kwargs)

    def _reset_state(self):
        """Revert back to the original state."""
        self.state = self.start_state.copy()

    def _get_state(self, props):
        """Return the requested data"""
        return self.state

    def _set_power(self, value: str):
        """Set the requested power state"""
        if value == STATE_ON:
            self.state[1] = self.state[1][:2] + "1" + self.state[1][3:]

        if value == STATE_OFF:
            self.state[1] = self.state[1][:2] + "0" + self.state[1][3:]

    @staticmethod
    def _hex_input_validation(payload):
        return all(c in string.hexdigits for c in payload[0])

    def _send_input_validation(self, payload):
        if self._hex_input_validation(payload[0]):
            self.last_ir_played = payload[0]
            return True

        return False

    def get_last_ir_played(self):
        return self.last_ir_played


@pytest.fixture(scope="class")
def airconditioningcompanion(request):
    request.cls.device = DummyAirConditioningCompanion()
    # TODO add ability to test on a real device


@pytest.mark.usefixtures("airconditioningcompanion")
class TestAirConditioningCompanion(TestCase):
    def is_on(self):
        return self.device.status().is_on

    def state(self):
        return self.device.status()

    def test_on(self):
        self.device.off()  # ensure off
        assert self.is_on() is False

        self.device.on()
        assert self.is_on() is True

    def test_off(self):
        self.device.on()  # ensure on
        assert self.is_on() is True

        self.device.off()
        assert self.is_on() is False

    def test_status(self):
        self.device._reset_state()

        assert repr(self.state()) == repr(
            AirConditioningCompanionStatus(
                dict(model_and_state=self.device.start_state)
            )
        )

        assert self.is_on() is False
        assert self.state().power_socket is None
        assert self.state().load_power == 2
        assert self.state().air_condition_model == bytes.fromhex("010500978022222102")
        assert self.state().model_format == 1
        assert self.state().device_type == 5
        assert self.state().air_condition_brand == int("0097", 16)
        assert self.state().air_condition_remote == int("80222221", 16)
        assert self.state().state_format == 2
        assert self.state().air_condition_configuration == "020119A2"
        assert self.state().target_temperature == 25
        assert self.state().swing_mode == SwingMode.Off
        assert self.state().fan_speed == FanSpeed.Low
        assert self.state().mode == OperationMode.Auto
        assert self.state().led is False

    def test_status_without_target_temperature(self):
        self.device._reset_state()
        self.device.state[1] = None
        assert self.state().target_temperature is None

    def test_status_without_swing_mode(self):
        self.device._reset_state()
        self.device.state[1] = None
        assert self.state().swing_mode is None

    def test_status_without_mode(self):
        self.device._reset_state()
        self.device.state[1] = None
        assert self.state().mode is None

    def test_status_without_fan_speed(self):
        self.device._reset_state()
        self.device.state[1] = None
        assert self.state().fan_speed is None

    def test_learn(self):
        assert self.device.learn(STORAGE_SLOT_ID) is True
        assert self.device.learn() is True

    def test_learn_result(self):
        assert self.device.learn_result() is True

    def test_learn_stop(self):
        assert self.device.learn_stop(STORAGE_SLOT_ID) is True
        assert self.device.learn_stop() is True

    def test_send_ir_code(self):
        for args in test_data["test_send_ir_code_ok"]:
            with self.subTest():
                self.device._reset_state()
                self.assertTrue(self.device.send_ir_code(*args["in"]))
                self.assertSequenceEqual(self.device.get_last_ir_played(), args["out"])

        for args in test_data["test_send_ir_code_exception"]:
            with pytest.raises(AirConditioningCompanionException):
                self.device.send_ir_code(*args["in"])

    def test_send_command(self):
        assert self.device.send_command("0000000") is True

    def test_send_configuration(self):

        for args in test_data["test_send_configuration_ok"]:
            with self.subTest():
                self.device._reset_state()
                self.assertTrue(self.device.send_configuration(*args["in"]))
                self.assertSequenceEqual(self.device.get_last_ir_played(), args["out"])


class DummyAirConditioningCompanionV3(DummyDevice, AirConditioningCompanionV3):
    def __init__(self, *args, **kwargs):
        self.state = ["010507950000257301", "011001160100002573", "807"]
        self.device_prop = {"lumi.0": {"plug_state": ["on"]}}
        self.model = MODEL_ACPARTNER_V3
        self.last_ir_played = None

        self.return_values = {
            "get_model_and_state": self._get_state,
            "get_device_prop": self._get_device_prop,
            "toggle_plug": self._toggle_plug,
        }
        self.start_state = self.state.copy()
        self.start_device_prop = self.device_prop.copy()
        super().__init__(args, kwargs)

    def _reset_state(self):
        """Revert back to the original state."""
        self.state = self.start_state.copy()

    def _get_state(self, props):
        """Return the requested data"""
        return self.state

    def _get_device_prop(self, props):
        """Return the requested data"""
        return self.device_prop[props[0]][props[1]]

    def _toggle_plug(self, props):
        """Toggle the lumi.0 plug state"""
        self.device_prop["lumi.0"]["plug_state"] = [props.pop()]


@pytest.fixture(scope="class")
def airconditioningcompanionv3(request):
    request.cls.device = DummyAirConditioningCompanionV3()
    # TODO add ability to test on a real device


@pytest.mark.usefixtures("airconditioningcompanionv3")
class TestAirConditioningCompanionV3(TestCase):
    def state(self):
        return self.device.status()

    def is_on(self):
        return self.device.status().is_on

    def test_socket_on(self):
        self.device.socket_off()  # ensure off
        assert self.state().power_socket == "off"

        self.device.socket_on()
        assert self.state().power_socket == "on"

    def test_socket_off(self):
        self.device.socket_on()  # ensure on
        assert self.state().power_socket == "on"

        self.device.socket_off()
        assert self.state().power_socket == "off"

    def test_status(self):
        self.device._reset_state()

        assert repr(self.state()) == repr(
            AirConditioningCompanionStatus(
                dict(
                    model_and_state=self.device.start_state,
                    power_socket=self.device.start_device_prop["lumi.0"]["plug_state"][
                        0
                    ],
                )
            )
        )

        assert self.is_on() is True
        assert self.state().power_socket == "on"
        assert self.state().load_power == 807
        assert self.state().air_condition_model == bytes.fromhex("010507950000257301")
        assert self.state().model_format == 1
        assert self.state().device_type == 5
        assert self.state().air_condition_brand == int("0795", 16)
        assert self.state().air_condition_remote == int("00002573", 16)
        assert self.state().state_format == 1
        assert self.state().air_condition_configuration == "10011601"
        assert self.state().target_temperature == 22
        assert self.state().swing_mode == SwingMode.Off
        assert self.state().fan_speed == FanSpeed.Low
        assert self.state().mode == OperationMode.Heat
        assert self.state().led is True