File: test_mqtt.py

package info (click to toggle)
aws-crt-python 0.16.8%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 78,328 kB
  • sloc: ansic: 330,743; python: 18,949; makefile: 6,271; sh: 3,712; asm: 754; cpp: 699; ruby: 208; java: 77; perl: 73; javascript: 46; xml: 11
file content (302 lines) | stat: -rw-r--r-- 11,999 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
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0.

from awscrt.io import ClientBootstrap, ClientTlsContext, DefaultHostResolver, EventLoopGroup, Pkcs11Lib, TlsContextOptions, LogLevel, init_logging
from awscrt.mqtt import Client, Connection, QoS
from test import NativeResourceTest
from concurrent.futures import Future
import enum
import os
import pathlib
import sys
import unittest
import uuid

TIMEOUT = 100.0


class MqttClientTest(NativeResourceTest):
    def test_lifetime(self):
        elg = EventLoopGroup()
        resolver = DefaultHostResolver(elg)
        bootstrap = ClientBootstrap(elg, resolver)
        client = Client(bootstrap)


AuthType = enum.Enum('AuthType', ['CERT_AND_KEY', 'PKCS11', 'ECC_CERT_AND_KEY'])


class Config:
    def __init__(self, auth_type):
        self.endpoint = self._get_env('AWS_TEST_IOT_MQTT_ENDPOINT')
        self.cert_path = self._get_env('AWS_TEST_TLS_CERT_PATH')
        self.cert = pathlib.Path(self.cert_path).read_text().encode('utf-8')

        if auth_type == AuthType.ECC_CERT_AND_KEY:
            self.key_path = self._get_env('AWS_TEST_ECC_KEY_PATH')
            self.key = pathlib.Path(self.key_path).read_text().encode('utf-8')
            self.cert_path = self._get_env('AWS_TEST_ECC_CERT_PATH')
            self.cert = pathlib.Path(self.cert_path).read_text().encode('utf-8')

        if auth_type == AuthType.CERT_AND_KEY:
            self.key_path = self._get_env('AWS_TEST_TLS_KEY_PATH')
            self.key = pathlib.Path(self.key_path).read_text().encode('utf-8')

        elif auth_type == AuthType.PKCS11:
            self.pkcs11_lib_path = self._get_env('AWS_TEST_PKCS11_LIB')
            self.pkcs11_pin = self._get_env('AWS_TEST_PKCS11_PIN')
            self.pkcs11_token_label = self._get_env('AWS_TEST_PKCS11_TOKEN_LABEL')
            self.pkcs11_key_label = self._get_env('AWS_TEST_PKCS11_KEY_LABEL')

    def _get_env(self, name):
        val = os.environ.get(name)
        if not val:
            raise unittest.SkipTest(f"test requires env var: {name}")
        return val


def create_client_id():
    return 'aws-crt-python-unit-test-{0}'.format(uuid.uuid4())


class MqttConnectionTest(NativeResourceTest):
    TEST_TOPIC = '/test/me/senpai'
    TEST_MSG = 'NOTICE ME!'.encode('utf8')

    def _create_connection(self, auth_type=AuthType.CERT_AND_KEY, use_static_singletons=False):
        config = Config(auth_type)

        if auth_type == AuthType.CERT_AND_KEY or auth_type == AuthType.ECC_CERT_AND_KEY:
            tls_opts = TlsContextOptions.create_client_with_mtls_from_path(config.cert_path, config.key_path)
            tls = ClientTlsContext(tls_opts)

        elif auth_type == AuthType.PKCS11:
            try:
                pkcs11_lib = Pkcs11Lib(
                    file=config.pkcs11_lib_path,
                    behavior=Pkcs11Lib.InitializeFinalizeBehavior.STRICT)

                tls_opts = TlsContextOptions.create_client_with_mtls_pkcs11(
                    pkcs11_lib=pkcs11_lib,
                    user_pin=config.pkcs11_pin,
                    token_label=config.pkcs11_token_label,
                    private_key_label=config.pkcs11_key_label,
                    cert_file_path=config.cert_path)

                tls = ClientTlsContext(tls_opts)

            except Exception as e:
                if 'AWS_ERROR_UNIMPLEMENTED' in str(e):
                    raise unittest.SkipTest(f'TLS with PKCS#11 not supported on this platform ({sys.platform})')
                else:
                    # re-raise exception
                    raise

        if use_static_singletons:
            client = Client(tls_ctx=tls)
        else:
            elg = EventLoopGroup()
            resolver = DefaultHostResolver(elg)
            bootstrap = ClientBootstrap(elg, resolver)
            client = Client(bootstrap, tls)

        connection = Connection(
            client=client,
            client_id=create_client_id(),
            host_name=config.endpoint,
            port=8883)
        return connection

    def test_connect_disconnect(self):
        connection = self._create_connection()
        connection.connect().result(TIMEOUT)
        connection.disconnect().result(TIMEOUT)

    def test_ecc_connect_disconnect(self):
        connection = self._create_connection(AuthType.ECC_CERT_AND_KEY)
        connection.connect().result(TIMEOUT)
        connection.disconnect().result(TIMEOUT)

    def test_pkcs11(self):
        connection = self._create_connection(AuthType.PKCS11)
        connection.connect().result(TIMEOUT)
        connection.disconnect().result(TIMEOUT)

    def test_pub_sub(self):
        connection = self._create_connection()
        connection.connect().result(TIMEOUT)
        received = Future()

        def on_message(**kwargs):
            received.set_result(kwargs)

        # subscribe
        subscribed, packet_id = connection.subscribe(self.TEST_TOPIC, QoS.AT_LEAST_ONCE, on_message)
        suback = subscribed.result(TIMEOUT)
        self.assertEqual(packet_id, suback['packet_id'])
        self.assertEqual(self.TEST_TOPIC, suback['topic'])
        self.assertIs(QoS.AT_LEAST_ONCE, suback['qos'])

        # publish
        published, packet_id = connection.publish(self.TEST_TOPIC, self.TEST_MSG, QoS.AT_LEAST_ONCE)
        puback = published.result(TIMEOUT)
        self.assertEqual(packet_id, puback['packet_id'])

        # receive message
        rcv = received.result(TIMEOUT)
        self.assertEqual(self.TEST_TOPIC, rcv['topic'])
        self.assertEqual(self.TEST_MSG, rcv['payload'])
        self.assertFalse(rcv['dup'])
        self.assertEqual(QoS.AT_LEAST_ONCE, rcv['qos'])
        self.assertFalse(rcv['retain'])

        # unsubscribe
        unsubscribed, packet_id = connection.unsubscribe(self.TEST_TOPIC)
        unsuback = unsubscribed.result(TIMEOUT)
        self.assertEqual(packet_id, unsuback['packet_id'])

        # disconnect
        connection.disconnect().result(TIMEOUT)

    def test_on_message(self):
        connection = self._create_connection()
        received = Future()

        def on_message(**kwargs):
            received.set_result(kwargs)

        # on_message for connection has to be set before connect, or possible race will happen
        connection.on_message(on_message)

        connection.connect().result(TIMEOUT)
        # subscribe without callback
        subscribed, packet_id = connection.subscribe(self.TEST_TOPIC, QoS.AT_LEAST_ONCE)
        subscribed.result(TIMEOUT)

        # publish
        published, packet_id = connection.publish(self.TEST_TOPIC, self.TEST_MSG, QoS.AT_LEAST_ONCE)
        puback = published.result(TIMEOUT)

        # receive message
        rcv = received.result(TIMEOUT)
        self.assertEqual(self.TEST_TOPIC, rcv['topic'])
        self.assertEqual(self.TEST_MSG, rcv['payload'])
        self.assertFalse(rcv['dup'])
        self.assertEqual(QoS.AT_LEAST_ONCE, rcv['qos'])
        self.assertFalse(rcv['retain'])

        # disconnect
        connection.disconnect().result(TIMEOUT)

    def test_on_message_old_fn_signature(self):
        # ensure that message-received callbacks with the old function signature still work
        connection = self._create_connection()

        any_received = Future()
        sub_received = Future()

        # Note: Testing degenerate callback signature that failed to take
        # forward-compatibility **kwargs.
        def on_any_message(topic, payload):
            any_received.set_result({'topic': topic, 'payload': payload})

        def on_sub_message(topic, payload):
            sub_received.set_result({'topic': topic, 'payload': payload})

        # on_message for connection has to be set before connect, or possible race will happen
        connection.on_message(on_any_message)

        connection.connect().result(TIMEOUT)
        # subscribe without callback
        subscribed, packet_id = connection.subscribe(self.TEST_TOPIC, QoS.AT_LEAST_ONCE, on_sub_message)
        subscribed.result(TIMEOUT)

        # publish
        published, packet_id = connection.publish(self.TEST_TOPIC, self.TEST_MSG, QoS.AT_LEAST_ONCE)
        puback = published.result(TIMEOUT)

        # receive message
        rcv = any_received.result(TIMEOUT)
        self.assertEqual(self.TEST_TOPIC, rcv['topic'])
        self.assertEqual(self.TEST_MSG, rcv['payload'])

        rcv = sub_received.result(TIMEOUT)
        self.assertEqual(self.TEST_TOPIC, rcv['topic'])
        self.assertEqual(self.TEST_MSG, rcv['payload'])

        # disconnect
        connection.disconnect().result(TIMEOUT)

    def test_connect_disconnect_with_default_singletons(self):
        connection = self._create_connection(use_static_singletons=True)
        connection.connect().result(TIMEOUT)
        connection.disconnect().result(TIMEOUT)

        # free singletons
        ClientBootstrap.release_static_default()
        EventLoopGroup.release_static_default()
        DefaultHostResolver.release_static_default()

    def test_connect_publish_wait_statistics_disconnect(self):
        connection = self._create_connection()
        connection.connect().result(TIMEOUT)

        # check operation statistics
        statistics = connection.get_stats()
        self.assertEqual(statistics.incomplete_operation_count, 0)
        self.assertEqual(statistics.incomplete_operation_size, 0)
        self.assertEqual(statistics.unacked_operation_count, 0)
        self.assertEqual(statistics.unacked_operation_size, 0)

        # publish
        published, packet_id = connection.publish(self.TEST_TOPIC, self.TEST_MSG, QoS.AT_LEAST_ONCE)
        puback = published.result(TIMEOUT)
        self.assertEqual(packet_id, puback['packet_id'])

        # check operation statistics
        statistics = connection.get_stats()
        self.assertEqual(statistics.incomplete_operation_count, 0)
        self.assertEqual(statistics.incomplete_operation_size, 0)
        self.assertEqual(statistics.unacked_operation_count, 0)
        self.assertEqual(statistics.unacked_operation_size, 0)

        # disconnect
        connection.disconnect().result(TIMEOUT)

    def test_connect_publish_statistics_wait_disconnect(self):
        connection = self._create_connection()
        connection.connect().result(TIMEOUT)

        # publish
        published, packet_id = connection.publish(self.TEST_TOPIC, self.TEST_MSG, QoS.AT_LEAST_ONCE)
        # Per packet: (The size of the topic, the size of the payload, 2 for the header and 2 for the packet ID)
        expected_size = len(self.TEST_TOPIC) + len(self.TEST_MSG) + 4

        # check operation statistics
        statistics = connection.get_stats()
        self.assertEqual(statistics.incomplete_operation_count, 1)
        self.assertEqual(statistics.incomplete_operation_size, expected_size)
        # NOTE: Unacked MAY be zero because we have not invoked the future yet
        # and so it has not had time to move to the socket. With Python especially, it seems to heavily depend on how fast
        # the test is executed, which makes it sometimes rarely get into the unacked operation and then it is non-zero.
        # To fix this, we just make sure it is within expected bounds (0 or within packet size).
        self.assertTrue(statistics.unacked_operation_count <= 1)
        self.assertTrue(statistics.unacked_operation_count <= expected_size)

        # wait for PubAck
        puback = published.result(TIMEOUT)
        self.assertEqual(packet_id, puback['packet_id'])

        # check operation statistics
        statistics = connection.get_stats()
        self.assertEqual(statistics.incomplete_operation_count, 0)
        self.assertEqual(statistics.incomplete_operation_size, 0)
        self.assertEqual(statistics.unacked_operation_count, 0)
        self.assertEqual(statistics.unacked_operation_size, 0)

        # disconnect
        connection.disconnect().result(TIMEOUT)


if __name__ == 'main':
    unittest.main()