File: test_subscription.py

package info (click to toggle)
pytraccar 3.0.0-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 456 kB
  • sloc: python: 786; makefile: 3
file content (208 lines) | stat: -rw-r--r-- 5,932 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
"""Test subscription."""

from __future__ import annotations

import asyncio
from typing import Any, NoReturn
from unittest.mock import patch

import aiohttp
import pytest
from aiohttp import WSMsgType

from pytraccar import (
    ApiClient,
    SubscriptionStatus,
    TraccarConnectionException,
    TraccarException,
)
from tests.common import WSMessage, WSMessageHandler


@pytest.mark.parametrize(
    "messages",
    [
        [
            WSMessage(messagetype=WSMsgType.TEXT, json={}),
            WSMessage(messagetype=WSMsgType.TEXT, json=None),
        ],
        [
            WSMessage(messagetype=WSMsgType.TEXT, json={"devices": []}),
        ],
        [
            WSMessage(messagetype=WSMsgType.TEXT, json={"positions": []}),
        ],
        [
            WSMessage(messagetype=WSMsgType.TEXT, json={"events": []}),
        ],
        [
            WSMessage(messagetype=WSMsgType.TEXT, json={"devices": []}),
            WSMessage(messagetype=WSMsgType.TEXT, json={"positions": []}),
            WSMessage(messagetype=WSMsgType.TEXT, json={"events": []}),
        ],
        [
            WSMessage(messagetype=WSMsgType.TEXT, json={"events": [], "devices": []}),
        ],
    ],
)
@pytest.mark.asyncio
async def test_subscription_text_message(
    api_client: ApiClient,
    messages: list[WSMessage],
    mock_ws_messages: WSMessageHandler,
) -> None:
    """Test subscription text message."""
    _handled = []
    _expected_handled = []
    for message in messages:
        mock_ws_messages.add(message)
        if message.type == WSMsgType.TEXT and (data := message.json()):
            _expected_handled.append(
                {
                    "devices": None,
                    "events": None,
                    "positions": None,
                    **data,
                }
            )

    async def _handler(data: Any) -> None:
        _handled.append(data)

    await api_client.subscribe(_handler)
    assert _handled == _expected_handled


@pytest.mark.parametrize(
    "message",
    [
        WSMessage(messagetype=WSMsgType.CLOSE),
        WSMessage(messagetype=WSMsgType.CLOSED),
        WSMessage(messagetype=WSMsgType.CLOSING),
        WSMessage(messagetype=WSMsgType.ERROR),
    ],
)
@pytest.mark.asyncio
async def test_subscription_stopping_message(
    api_client: ApiClient,
    message: WSMessage,
    mock_ws_messages: WSMessageHandler,
) -> None:
    """Test subscription stopping message."""
    _handled = []
    mock_ws_messages.add(message)

    async def _handler(data: Any) -> None:
        _handled.append(data)

    with pytest.raises(
        TraccarConnectionException,
        match=f"WebSocket connection closed with {message.type.name}",
    ):
        await api_client.subscribe(_handler)
    assert len(_handled) == 0


@pytest.mark.parametrize(
    "message",
    [
        WSMessage(messagetype=WSMsgType.CONTINUATION),
        WSMessage(messagetype=WSMsgType.BINARY),
        WSMessage(messagetype=WSMsgType.PING),
        WSMessage(messagetype=WSMsgType.PONG),
    ],
)
@pytest.mark.asyncio
async def test_subscription_unknown_type(
    api_client: ApiClient,
    message: WSMessage,
    mock_ws_messages: WSMessageHandler,
    caplog: pytest.LogCaptureFixture,
) -> None:
    """Test subscription unknown type."""
    _handled = []
    mock_ws_messages.add(message)

    async def _handler(data: Any) -> None:
        _handled.append(data)

    assert f"Unexpected message type {message.type.name}" not in caplog.text

    await api_client.subscribe(_handler)

    assert len(_handled) == 0
    assert f"Unexpected message type {message.type.name}" in caplog.text


@pytest.mark.asyncio
async def test_subscription_bad_handler(
    api_client: ApiClient,
    mock_ws_messages: WSMessageHandler,
    caplog: pytest.LogCaptureFixture,
) -> None:
    """Test subscription unknown type."""
    mock_ws_messages.add(WSMessage(messagetype=WSMsgType.TEXT, json={"devices": []}))

    async def _handler(_: Any) -> NoReturn:
        raise ValueError("Bad handler")

    await api_client.subscribe(_handler)

    assert "Exception while handling message: ValueError(Bad handler)" in caplog.text


@pytest.mark.parametrize(
    ("side_effect", "raises", "with_message"),
    [
        (
            KeyError("boom"),
            TraccarException,
            "Unexpected error",
        ),
        (
            asyncio.TimeoutError(),
            TraccarConnectionException,
            "Timeout error connecting to Traccar",
        ),
        (
            aiohttp.ClientError("boom"),
            TraccarConnectionException,
            "Could not communicate with Traccar",
        ),
        (
            TraccarConnectionException(),
            TraccarConnectionException,
            None,
        ),
    ],
)
@pytest.mark.asyncio
async def test_subscription_exceptions(
    api_client: ApiClient,
    side_effect: Exception,
    raises: Exception,
    with_message: str | None,
) -> None:
    """Test subscription exceptions."""
    assert api_client.subscription_status == SubscriptionStatus.DISCONNECTED
    with patch("aiohttp.ClientSession.ws_connect", side_effect=side_effect):
        if with_message is not None:
            with pytest.raises(raises, match=with_message):
                await api_client.subscribe(None)
        else:
            with pytest.raises(raises):
                await api_client.subscribe(None)

    assert api_client.subscription_status == SubscriptionStatus.ERROR


@pytest.mark.asyncio
async def test_subscription_cancelation(api_client: ApiClient) -> None:
    """Test subscription exceptions."""
    assert api_client.subscription_status == SubscriptionStatus.DISCONNECTED
    with patch(
        "aiohttp.ClientSession.ws_connect", side_effect=asyncio.CancelledError("boom")
    ):
        await api_client.subscribe(None)

    assert api_client.subscription_status == SubscriptionStatus.DISCONNECTED