File: test_endpoint.py

package info (click to toggle)
python-asusrouter 1.21.3-1
  • links: PTS, VCS
  • area: main
  • in suites:
  • size: 1,856 kB
  • sloc: python: 20,497; makefile: 3
file content (340 lines) | stat: -rw-r--r-- 10,142 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
339
340
"""Test for the main endpoint module."""

from unittest.mock import AsyncMock, MagicMock, patch

import pytest

from asusrouter.const import RequestType
from asusrouter.error import AsusRouter404Error, AsusRouterRequestFormatError
from asusrouter.modules.endpoint import (
    SENSITIVE_ENDPOINTS,
    Endpoint,
    EndpointService,
    EndpointTools,
    EndpointType,
    _get_module,
    check_available,
    data_get,
    data_set,
    get_request_type,
    is_sensitive_endpoint,
    process,
    read,
)

TEST_SENSITIVE_ENDPOINTS: tuple[EndpointType, ...] = (EndpointService.LOGIN,)
IDS_SENSITIVE_ENDPOINTS = ("login",)


@pytest.mark.parametrize(
    ("endpoint"), TEST_SENSITIVE_ENDPOINTS, ids=IDS_SENSITIVE_ENDPOINTS
)
def test_marked_sensitive_endpoint(endpoint: EndpointType) -> None:
    """Test if the endpoint is marked as sensitive."""

    assert endpoint in SENSITIVE_ENDPOINTS
    assert is_sensitive_endpoint(endpoint) is True


def test_sensitive_endpoints_immutable() -> None:
    """SENSITIVE_ENDPOINTS should be an immutable frozenset."""

    assert isinstance(SENSITIVE_ENDPOINTS, frozenset)
    # Attempting to call add should raise AttributeError
    with pytest.raises(AttributeError):
        SENSITIVE_ENDPOINTS.add(EndpointService.LOGOUT)  # type: ignore[attr-defined]

    # union returns a new frozenset; original remains unchanged
    new_set = SENSITIVE_ENDPOINTS | frozenset({EndpointService.LOGOUT})
    assert isinstance(new_set, frozenset)
    assert EndpointService.LOGOUT not in SENSITIVE_ENDPOINTS
    assert EndpointService.LOGOUT in new_set


@pytest.mark.parametrize(
    ("endpoint", "forced_request"),
    [
        (Endpoint.PORT_STATUS, RequestType.GET),
        (EndpointTools.NETWORK, RequestType.GET),
        (EndpointTools.TRAFFIC_BACKHAUL, RequestType.GET),
        (EndpointTools.TRAFFIC_ETHERNET, RequestType.GET),
        (EndpointTools.TRAFFIC_WIFI, RequestType.GET),
        (EndpointService.LOGIN, RequestType.POST),
    ],
)
def test_get_request_type(
    endpoint: EndpointType, forced_request: RequestType
) -> None:
    """Test get_request_type function."""

    assert get_request_type(endpoint) == forced_request


@pytest.mark.parametrize(
    ("endpoint", "expected"),
    [
        (EndpointService.LOGIN, True),
        (Endpoint.PORT_STATUS, False),
        (EndpointTools.NETWORK, False),
        (EndpointService.LOGOUT, False),
    ],
)
def test_is_sensitive_endpoint(
    endpoint: EndpointType,
    expected: bool,
) -> None:
    """is_sensitive_endpoint returns True only for sensitive endpoints."""

    assert is_sensitive_endpoint(endpoint) is expected


def test_get_module() -> None:
    """Test _get_module method."""

    # Test valid endpoint
    with patch(
        "importlib.import_module", return_value="mocked_module"
    ) as mock_import:
        result = _get_module(Endpoint.PORT_STATUS)
        assert result == "mocked_module"  # type: ignore[comparison-overlap]
        mock_import.assert_called_once_with(
            "asusrouter.modules.endpoint.port_status"
        )

    # Test invalid endpoint
    with patch("importlib.import_module") as mock_import:
        mock_import.side_effect = ModuleNotFoundError
        result = _get_module(Endpoint.FIRMWARE)
        assert result is None
        mock_import.assert_called_once_with(
            "asusrouter.modules.endpoint.firmware"
        )


def test_read() -> None:
    """Test read method."""

    # Mock the module and its read method
    mock_module = MagicMock()
    mock_module.read.return_value = {"mocked": "data"}

    # Test valid endpoint
    with patch(
        "asusrouter.modules.endpoint._get_module", return_value=mock_module
    ) as mock_get_module:
        result = read(Endpoint.FIRMWARE, "content")
        assert result == {"mocked": "data"}
        mock_get_module.assert_called_once_with(Endpoint.FIRMWARE)
        mock_module.read.assert_called_once_with("content")

    # Test invalid endpoint
    with patch(
        "asusrouter.modules.endpoint._get_module", return_value=None
    ) as mock_get_module:
        result = read(Endpoint.PORT_STATUS, "content")
        assert result == {}
        mock_get_module.assert_called_once_with(Endpoint.PORT_STATUS)


def test_read_module_return_fail() -> None:
    """Test read method when the module returns wrong result."""

    mock_module = MagicMock()
    mock_module.read.return_value = "not_a_dict"

    with patch(
        "asusrouter.modules.endpoint._get_module", return_value=mock_module
    ) as mock_get_module:
        result = read(Endpoint.FIRMWARE, "content")
        assert result == {}
        mock_get_module.assert_called_once_with(Endpoint.FIRMWARE)


@pytest.mark.parametrize(
    ("require_history", "require_firmware", "require_wlan", "call_count"),
    [
        (True, False, False, 1),
        (False, True, False, 1),
        (False, False, True, 1),
        (False, False, False, 0),
        (True, True, True, 3),
    ],
)
def test_process(
    require_history: bool,
    require_firmware: bool,
    require_wlan: bool,
    call_count: int,
) -> None:
    """Test process method."""

    # Mock the module and its process method
    mock_module = MagicMock()
    mock_module.process.return_value = {"mocked": "data"}

    # Mock the data_set function
    mock_data_set = MagicMock()

    # Define a side effect function for getattr
    def getattr_side_effect(
        _: object, attr: str, default: bool | None = None
    ) -> bool | None:
        """Return the value of the attribute if it exists."""

        if attr == "REQUIRE_HISTORY":
            return require_history
        if attr == "REQUIRE_FIRMWARE":
            return require_firmware
        if attr == "REQUIRE_WLAN":
            return require_wlan
        return bool(default) if default is not None else None

    # Test valid endpoint
    with (
        patch(
            "asusrouter.modules.endpoint._get_module", return_value=mock_module
        ),
        patch("asusrouter.modules.endpoint.data_set", mock_data_set),
        patch(
            "asusrouter.modules.endpoint.getattr",
            side_effect=getattr_side_effect,
        ),
    ):
        result = process(Endpoint.DEVICEMAP, {"key": "value"})
        assert result == {"mocked": "data"}
        mock_module.process.assert_called_once_with({"key": "value"})
        assert mock_data_set.call_count == call_count


def test_process_no_module() -> None:
    """Test process method when no module is found."""

    # Mock the _get_module function to return None
    with patch(
        "asusrouter.modules.endpoint._get_module", return_value=None
    ) as mock_get_module:
        result = process(Endpoint.PORT_STATUS, {"key": "value"})
        assert result == {}
        mock_get_module.assert_called_once_with(Endpoint.PORT_STATUS)


def test_process_module_return_fail() -> None:
    """Test process method when the module returns wrong result."""

    mock_module = MagicMock()
    mock_module.process.return_value = "not_a_dict"

    with patch(
        "asusrouter.modules.endpoint._get_module", return_value=mock_module
    ) as mock_get_module:
        result = process(Endpoint.DEVICEMAP, {"key": "value"})
        assert result == {}
        mock_get_module.assert_called_once_with(Endpoint.DEVICEMAP)


@pytest.mark.parametrize(
    ("error"),
    [
        AttributeError,
        ValueError,
    ],
)
def test_process_module_raises(error: type[Exception]) -> None:
    """Test process method when an exception is raised."""

    mock_module = MagicMock()
    mock_module.process.side_effect = error

    with patch(
        "asusrouter.modules.endpoint._get_module", return_value=mock_module
    ) as mock_get_module:
        result = process(Endpoint.DEVICEMAP, {"key": "value"})
        assert result == {}
        mock_get_module.assert_called_once_with(Endpoint.DEVICEMAP)


def test_data_set() -> None:
    """Test data_set function."""

    # Test data
    data = {"key1": "value1"}
    kwargs = {"key2": "value2", "key3": "value3"}

    # Call the function
    result = data_set(data, **kwargs)

    # Check the result
    assert result == {"key1": "value1", "key2": "value2", "key3": "value3"}


@pytest.mark.parametrize(
    ("data", "key", "expected", "data_left"),
    [
        # Key exists
        (
            {"key1": "value1", "key2": "value2"},
            "key1",
            "value1",
            {"key2": "value2"},
        ),
        # Key does not exist
        (
            {"key1": "value1", "key2": "value2"},
            "key3",
            None,
            {"key1": "value1", "key2": "value2"},
        ),
        # Empty data
        ({}, "key1", None, {}),
    ],
)
def test_data_get(
    data: dict[str, str],
    key: str,
    expected: str | None,
    data_left: dict[str, str],
) -> None:
    """Test data_get function."""

    # Call the function
    result = data_get(data, key)

    # Check the result
    assert result == expected
    assert data == data_left


@pytest.mark.asyncio
@pytest.mark.parametrize(
    ("api_query_return", "expected_result"),
    [
        # Test case: status 200
        ((200, None, None), (True, None)),
        # Test case: status 200 and content
        ((200, None, "content"), (True, "content")),
        # Test case: status not 200
        ((403, None, None), (False, None)),
        # Test case: AsusRouterRequestFormatError is raised
        (AsusRouterRequestFormatError(), (True, None)),
        # Test case: AsusRouter404Error is raised
        (AsusRouter404Error(), (False, None)),
    ],
)
async def test_check_available(
    api_query_return: tuple[int, str | None, str | None],
    expected_result: tuple[bool, str | None],
) -> None:
    """Test check_available function."""

    # Mock the api_query function
    api_query = AsyncMock()
    if isinstance(api_query_return, Exception):
        api_query.side_effect = api_query_return
    else:
        api_query.return_value = api_query_return

    # Call the function
    result = await check_available(Endpoint.DEVICEMAP, api_query)

    # Check the result
    assert result == expected_result