File: test_state.py

package info (click to toggle)
python-asusrouter 1.21.3-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 1,856 kB
  • sloc: python: 20,497; makefile: 3
file content (338 lines) | stat: -rw-r--r-- 8,734 bytes parent folder | download
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
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
"""Tests for the state module."""

from typing import Any
from unittest import mock

import pytest

from asusrouter import AsusData
from asusrouter.modules.state import (
    AsusState,
    _get_module,
    _get_module_name,
    _has_method,
    add_conditional_state,
    get_datatype,
    keep_state,
    save_state,
    set_state,
)
from asusrouter.modules.system import AsusSystem
from asusrouter.modules.vpnc import AsusVPNC
from asusrouter.modules.wlan import AsusWLAN

mock_state_map = {
    AsusState.SYSTEM: AsusData.SYSTEM,
    AsusState.VPNC: AsusData.VPNC,
    AsusState.WLAN: AsusData.WLAN,
    AsusState.NONE: None,
}


class MockModule:
    """Mock module."""

    def __init__(
        self, require_state: bool = False, require_identity: bool = False
    ) -> None:
        """Initialize the mock module."""

        self.REQUIRE_STATE = require_state  # pylint: disable=invalid-name
        self.REQUIRE_IDENTITY = require_identity  # pylint: disable=invalid-name

        self.update_state = mock.Mock()
        self.offset_time = mock.Mock()

    async def set_state(self, **_: Any) -> bool:
        """Set the state."""

        return True

    async def keep_state(self, *_: Any, **__: Any) -> None:
        """Keep the state."""

        return


@pytest.mark.parametrize(
    ("state", "data", "success"),
    [
        # Existing values of AsusState
        (AsusState.LED, AsusData.LED, True),
        (AsusState.WIREGUARD_CLIENT, AsusData.WIREGUARD_CLIENT, True),
        (AsusState.PARENTAL_CONTROL, AsusData.PARENTAL_CONTROL, True),
        # Partial data
        (AsusState.PORT_FORWARDING, None, False),
        (None, AsusData.LED, False),
        # None
        (None, None, False),
        # Wrong types
        (1, AsusData.SYSTEM, False),
        (AsusState.CONNECTION, 1, False),
    ],
)
def test_add_conditional_state(
    state: AsusState, data: AsusData | None, success: bool
) -> None:
    """Test add_conditional_state."""

    # Try to add the state
    with mock.patch("asusrouter.modules.state.AsusStateMap", mock_state_map):
        add_conditional_state(state, data)

    # Check the result
    if success:
        assert mock_state_map[state] == data
    else:
        assert state not in mock_state_map


@pytest.mark.parametrize(
    ("state", "expected"),
    [
        # Existing values of AsusState
        (AsusSystem.REBOOT, AsusData.SYSTEM),
        (AsusVPNC.ON, AsusData.VPNC),
        (AsusWLAN.OFF, AsusData.WLAN),
        # None
        (None, None),
        # Wrong types
        (1, None),
        ("string", None),
    ],
)
def test_get_datatype(
    state: AsusState | None, expected: AsusData | None
) -> None:
    """Test get_datatype."""

    # Try to get the datatype
    with mock.patch("asusrouter.modules.state.AsusStateMap", mock_state_map):
        result = get_datatype(state)

    # Check the result
    assert result == expected


@pytest.mark.parametrize(
    ("state", "expected"),
    [
        # Existing values of AsusState
        (AsusState.SYSTEM, AsusData.SYSTEM.value),
        (AsusState.VPNC, AsusData.VPNC.value),
        (AsusState.WLAN, AsusData.WLAN.value),
        # None
        (None, None),
        # Wrong types
        (1, None),
        ("string", None),
    ],
)
def test_get_module_name(
    state: AsusState | None, expected: str | None
) -> None:
    """Test _get_module_name."""

    # Mock the get_datatype function
    with mock.patch(
        "asusrouter.modules.state.get_datatype",
        lambda s: mock_state_map.get(s),
    ):
        result = _get_module_name(state)

    # Check the result
    assert result == expected


@pytest.mark.parametrize(
    (
        "state",
        "module_name",
        "expected_module",
        "import_result",
        "import_exception",
        "expected",
    ),
    [
        # Existing values of AsusState
        (
            AsusState.SYSTEM,
            "system",
            "system",
            mock.MagicMock(),
            None,
            "mock_module",
        ),
        (
            AsusState.VPNC,
            "vpnc",
            "vpnc",
            mock.MagicMock(),
            None,
            "mock_module",
        ),
        (
            AsusState.WLAN,
            "wlan",
            "wlan",
            mock.MagicMock(),
            None,
            "mock_module",
        ),
        (
            AsusState.WIREGUARD_CLIENT,
            "wireguard_client",
            "wireguard",
            mock.MagicMock(),
            None,
            "mock_module",
        ),
        # ModuleNotFoundError
        (
            AsusState.SYSTEM,
            "system",
            "system",
            None,
            ModuleNotFoundError,
            None,
        ),
        # None
        (None, None, None, None, None, None),
        # Wrong types
        (1, None, None, None, None, None),
        ("string", None, None, None, None, None),
    ],
)
def test_get_module(  # noqa: PLR0913
    state: AsusState | None,
    module_name: str | None,
    expected_module: str | None,
    import_result: Any,
    import_exception: Exception | None,
    expected: str | None,
) -> None:
    """Test _get_module."""

    # Mock the _get_module_name function and importlib.import_module function
    with (
        mock.patch(
            "asusrouter.modules.state._get_module_name",
            return_value=module_name,
        ),
        mock.patch("importlib.import_module") as mock_import,
    ):
        mock_import.return_value = import_result
        mock_import.side_effect = import_exception
        result = _get_module(state)
        if expected_module and import_result is not None:
            mock_import.assert_called_once_with(
                f"asusrouter.modules.{expected_module}"
            )

    # Check the result
    assert (result is not None) == (expected is not None)


@pytest.mark.parametrize(
    ("module", "method", "expected"),
    [
        # Existing method
        (MockModule(), "set_state", True),
        # Non-existing method
        (MockModule(), "non_existing_method", False),
    ],
)
def test_has_method(module: MockModule, method: str, expected: bool) -> None:
    """Test _has_method."""

    result = _has_method(module, method)

    assert result == expected


@pytest.mark.asyncio
@pytest.mark.parametrize(
    ("has_method", "require_state", "require_identity", "expected"),
    [
        (True, False, False, True),
        (True, True, False, True),
        (True, False, True, True),
        (False, False, False, False),
    ],
)
async def test_set_state(
    has_method: bool,
    require_state: bool,
    require_identity: bool,
    expected: bool,
) -> None:
    """Test set_state."""

    # Mock the _get_module function and _has_method function
    with (
        mock.patch(
            "asusrouter.modules.state._get_module",
            return_value=MockModule(require_state, require_identity),
        ),
        mock.patch(
            "asusrouter.modules.state._has_method", return_value=has_method
        ),
    ):
        result = await set_state(mock.AsyncMock(), AsusState.SYSTEM)

    assert result == expected


@pytest.mark.parametrize(
    ("state", "datatype"),
    [
        (AsusState.VPNC, AsusData.VPNC),
        (AsusState.VPNC, None),
    ],
)
def test_save_state(state: AsusState, datatype: AsusData | None) -> None:
    """Test save_state."""

    # Mock the get_datatype function
    with mock.patch(
        "asusrouter.modules.state.get_datatype", return_value=datatype
    ):
        # Mock the AsusDataState objects
        library = {AsusData.VPNC: MockModule()}

        # Call the function
        save_state(state, library)

    # Check the calls to the AsusDataState methods
    if datatype is not None:
        library[datatype].update_state.assert_called_once_with(state, None)
        library[datatype].offset_time.assert_called_once_with(None)


@pytest.mark.asyncio
@pytest.mark.parametrize(
    ("states", "has_method", "expected"),
    [
        ([AsusState.SYSTEM], True, None),
        (AsusState.SYSTEM, True, None),  # Single value, not a list
        ([AsusState.SYSTEM], False, None),
        (None, False, None),
    ],
)
async def test_keep_state(
    states: list[AsusState] | None, has_method: bool, expected: bool | None
) -> None:
    """Test keep_state."""

    # Mock the _get_module function and _has_method function
    with (
        mock.patch(
            "asusrouter.modules.state._get_module", return_value=MockModule()
        ),
        mock.patch(
            "asusrouter.modules.state._has_method", return_value=has_method
        ),
    ):
        result = await keep_state(mock.AsyncMock(), states)

    assert result == expected