File: test_bpup.py

package info (click to toggle)
python-bond-async 0.2.1-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 204 kB
  • sloc: python: 1,537; makefile: 4
file content (213 lines) | stat: -rw-r--r-- 6,582 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
"""Unit tests for Bond BPUP."""

from unittest.mock import call, MagicMock, patch
from typing import Optional
import asyncio
import pytest
import datetime as dt

from . import mock_time_changed
from bond_async.bpup import BPUPSubscriptions, BPUProtocol, start_bpup

MOCK_ADDR = ("127.0.0.1", 1)


def mock_protocol_connection_lost(
    protocol: asyncio.BaseProtocol, exc: Optional[Exception]
) -> None:
    """Mock an asyncio.Protocol connection lost callback."""
    protocol.connection_lost(exc)
    protocol.transport.is_closing = MagicMock(return_value=True)


@pytest.fixture(name="transport")
def transport_fixture():
    """Creates transport fixture."""
    transport = MagicMock(auto_spec=asyncio.DatagramTransport)
    transport.is_closing = MagicMock(return_value=False)

    def _mock_close(*_):
        transport.is_closing = MagicMock(return_value=True)

    transport.close = _mock_close
    return transport


@pytest.mark.asyncio
async def test_protocol_keep_alive_close(transport):
    bpup_subscriptions = BPUPSubscriptions()
    loop = asyncio.get_event_loop()
    bpup_protocol = BPUProtocol(bpup_subscriptions)

    bpup_protocol.connection_made(transport)
    assert transport.sendto.mock_calls == [call(b"\n")]
    transport.sendto.reset_mock()

    mock_time_changed(loop, dt.datetime.now(dt.timezone.utc) + dt.timedelta(seconds=60))
    assert transport.sendto.mock_calls == [call(b"\n")]
    transport.sendto.reset_mock()

    bpup_protocol.stop()

    mock_time_changed(
        loop, dt.datetime.now(dt.timezone.utc) + dt.timedelta(seconds=120)
    )
    assert transport.sendto.mock_calls == []


@pytest.mark.asyncio
async def test_protocol_keep_connection_lost_no_error(transport, caplog):
    bpup_subscriptions = BPUPSubscriptions()
    loop = asyncio.get_event_loop()
    bpup_protocol = BPUProtocol(bpup_subscriptions)

    bpup_protocol.connection_made(transport)
    assert transport.sendto.mock_calls == [call(b"\n")]
    transport.sendto.reset_mock()
    assert bpup_subscriptions.alive is False
    bpup_protocol.datagram_received(
        b'{"B":"KNKSADE42149","d":0,"v":"v2.29.2-beta"}\n', MOCK_ADDR
    )
    assert bpup_subscriptions.alive is True

    mock_time_changed(loop, dt.datetime.now(dt.timezone.utc) + dt.timedelta(seconds=60))
    assert transport.sendto.mock_calls == [call(b"\n")]
    transport.sendto.reset_mock()

    mock_protocol_connection_lost(bpup_protocol, None)
    assert "BPUP connection lost" not in caplog.text
    assert bpup_subscriptions.alive is False

    mock_time_changed(
        loop, dt.datetime.now(dt.timezone.utc) + dt.timedelta(seconds=120)
    )
    assert transport.sendto.mock_calls == []


@pytest.mark.asyncio
async def test_protocol_keep_connection_lost_with_error(transport, caplog):
    bpup_subscriptions = BPUPSubscriptions()
    loop = asyncio.get_event_loop()
    bpup_protocol = BPUProtocol(bpup_subscriptions)

    bpup_protocol.connection_made(transport)
    assert transport.sendto.mock_calls == [call(b"\n")]
    transport.sendto.reset_mock()
    assert bpup_subscriptions.alive is False
    bpup_protocol.datagram_received(
        b'{"B":"KNKSADE42149","d":0,"v":"v2.29.2-beta"}\n', MOCK_ADDR
    )

    mock_time_changed(loop, dt.datetime.now(dt.timezone.utc) + dt.timedelta(seconds=60))
    assert transport.sendto.mock_calls == [call(b"\n")]
    transport.sendto.reset_mock()
    assert bpup_subscriptions.alive is True

    mock_protocol_connection_lost(bpup_protocol, OSError())

    assert "BPUP connection lost" in caplog.text
    assert bpup_subscriptions.alive is False

    assert transport.sendto.mock_calls == []
    mock_time_changed(
        loop, dt.datetime.now(dt.timezone.utc) + dt.timedelta(seconds=120)
    )
    assert transport.sendto.mock_calls == []


@pytest.mark.asyncio
async def test_protocol_subscriptions(transport, caplog):
    bpup_subscriptions = BPUPSubscriptions()
    bpup_protocol = BPUProtocol(bpup_subscriptions)
    last_msg = None

    def _on_new_message(msg):
        nonlocal last_msg
        last_msg = msg

    bpup_subscriptions.subscribe("1", _on_new_message)

    bpup_protocol.connection_made(transport)
    # Make sure we can do it again
    bpup_protocol.connection_made(transport)
    bpup_protocol.datagram_received(
        b'{"B":"KNKSADE42149","d":0,"v":"v2.29.2-beta"}\n', MOCK_ADDR
    )

    bpup_protocol.datagram_received(
        b'{"t":"devices/1/state","s":200,"b":{"power":1,"speed":1,"timer":0,"breeze":[0,50,50],"_":"690b6aff"}}\n',
        MOCK_ADDR,
    )

    assert last_msg == {
        "t": "devices/1/state",
        "s": 200,
        "b": {
            "power": 1,
            "speed": 1,
            "timer": 0,
            "breeze": [0, 50, 50],
            "_": "690b6aff",
        },
    }

    bpup_protocol.datagram_received(
        b'{"t":"devices/1/state","s":200,"b":{"power":1,"speed":1,"timer":0,"breeze":[0,50,50],"_":"690b6aff"}}\n',
        MOCK_ADDR,
    )
    # 500 error should not trigger a new message
    assert last_msg == {
        "t": "devices/1/state",
        "s": 200,
        "b": {
            "power": 1,
            "speed": 1,
            "timer": 0,
            "breeze": [0, 50, 50],
            "_": "690b6aff",
        },
    }

    last_msg = {}
    bpup_subscriptions.unsubscribe("1", _on_new_message)
    bpup_protocol.datagram_received(
        b'{"t":"devices/1/state","s":200,"b":{"power":1,"speed":1,"timer":0,"breeze":[0,50,50],"_":"690b6aff"}}\n',
        MOCK_ADDR,
    )
    assert last_msg == {}

    bpup_protocol.datagram_received(
        b'{"B":"KVPRBDGXXXXX","_error_id":633,"_error_msg":"BPUP client timeout"}',
        MOCK_ADDR,
    )
    assert last_msg == {}

    bpup_protocol.datagram_received(
        b"GIGO",
        MOCK_ADDR,
    )
    assert "Failed to process BPUP message" in caplog.text
    assert "GIGO" in caplog.text


@pytest.mark.asyncio
async def test_protocol_errors(transport, caplog):
    bpup_subscriptions = BPUPSubscriptions()
    bpup_protocol = BPUProtocol(bpup_subscriptions)
    bpup_protocol.connection_made(transport)
    bpup_protocol.error_received(OSError())
    assert "BPUP error" in caplog.text


@pytest.mark.asyncio
async def test_start_bpup(transport):
    loop = asyncio.get_event_loop()
    bpup_subscriptions = BPUPSubscriptions()

    async def _mock_create_datagram_endpoint(func, remote_addr=None):
        return transport, func()

    with patch.object(loop, "create_datagram_endpoint", _mock_create_datagram_endpoint):
        stop = await start_bpup("127.0.0.1", bpup_subscriptions)

    stop()