Debian Codegraph @

test/test_io.py

raw symbols SCIP
1 # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2 # SPDX-License-Identifier: Apache-2.0.
3
4 from awscrt.io import *
5 from awscrt.logging import init_logging, set_log_level, log, LogSubject
6 from test import NativeResourceTest, TIMEOUT
7 import io
8 import logging
9 import os
10 import sys
11 import unittest
12
13
14 class EventLoopGroupTest(NativeResourceTest):
15 def test_init_defaults(self):
16 event_loop_group = EventLoopGroup()
17
18 def test_1_thread(self):
19 event_loop_group = EventLoopGroup(1)
20
21 def test_cpu_group(self):
22 event_loop_group = EventLoopGroup(cpu_group=0)
23
24 def test_shutdown_complete(self):
25 event_loop_group = EventLoopGroup()
26 shutdown_event = event_loop_group.shutdown_event
27 del event_loop_group
28 self.assertTrue(shutdown_event.wait(TIMEOUT))
29
30 def test_init_defaults_singleton(self):
31 event_loop_group = EventLoopGroup.get_or_create_static_default()
32
33 def test_init_defaults_singleton_is_singleton(self):
34 event_loop_group_one = EventLoopGroup.get_or_create_static_default()
35 event_loop_group_two = EventLoopGroup.get_or_create_static_default()
36 self.assertTrue(event_loop_group_one == event_loop_group_two)
37
38 def test_shutdown_complete_singleton(self):
39 event_loop_group = EventLoopGroup.get_or_create_static_default()
40 shutdown_event = event_loop_group.shutdown_event
41 del event_loop_group
42 EventLoopGroup.release_static_default()
43 self.assertTrue(shutdown_event.wait(TIMEOUT))
44
45
46 class DefaultHostResolverTest(NativeResourceTest):
47 def test_init(self):
48 event_loop_group = EventLoopGroup()
49 host_resolver = DefaultHostResolver(event_loop_group)
50
51 def test_init_singleton(self):
52 host_resolver = DefaultHostResolver.get_or_create_static_default()
53
54 def test_init_singleton_is_singleton(self):
55 host_resolver_one = DefaultHostResolver.get_or_create_static_default()
56 host_resolver_two = DefaultHostResolver.get_or_create_static_default()
57 self.assertTrue(host_resolver_one == host_resolver_two)
58
59
60 class ClientBootstrapTest(NativeResourceTest):
61 def test_create_destroy(self):
62 event_loop_group = EventLoopGroup()
63 host_resolver = DefaultHostResolver(event_loop_group)
64 bootstrap = ClientBootstrap(event_loop_group, host_resolver)
65
66 # ensure shutdown_event fires
67 bootstrap_shutdown_event = bootstrap.shutdown_event
68 del bootstrap
69 self.assertTrue(bootstrap_shutdown_event.wait(TIMEOUT))
70
71 def test_create_destroy_singleton(self):
72 bootstrap = ClientBootstrap.get_or_create_static_default()
73
74 # ensure shutdown_event fires
75 bootstrap_shutdown_event = bootstrap.shutdown_event
76 del bootstrap
77 ClientBootstrap.release_static_default()
78 self.assertTrue(bootstrap_shutdown_event.wait(TIMEOUT))
79
80 def test_init_singleton_is_singleton(self):
81 client_one = ClientBootstrap.get_or_create_static_default()
82 client_two = ClientBootstrap.get_or_create_static_default()
83 self.assertTrue(client_one == client_two)
84
85
86 class ClientTlsContextTest(NativeResourceTest):
87 def test_init_defaults(self):
88 opt = TlsContextOptions()
89 ctx = ClientTlsContext(opt)
90
91 def test_with_mtls_from_path(self):
92 opt = TlsContextOptions.create_client_with_mtls_from_path(
93 'test/resources/unittest.crt', 'test/resources/unittest.key')
94 ctx = ClientTlsContext(opt)
95
96 def test_with_mtls_pkcs12(self):
97 try:
98 opt = TlsContextOptions.create_client_with_mtls_pkcs12(
99 'test/resources/unittest.p12', '1234')
100 ctx = ClientTlsContext(opt)
101 except Exception as e:
102 if 'PLATFORM_NOT_SUPPORTED' in str(e):
103 raise unittest.SkipTest(f'PKCS#12 not supported on this platform ({sys.platform})')
104 else:
105 # well then this is a real error
106 raise e
107
108 def test_override_default_trust_store_dir(self):
109 opt = TlsContextOptions()
110 opt.override_default_trust_store_from_path('test/resources', None)
111 ctx = ClientTlsContext(opt)
112
113 def test_override_default_trust_store_file(self):
114 opt = TlsContextOptions()
115 opt.override_default_trust_store_from_path(None, 'test/resources/ca.crt')
116 ctx = ClientTlsContext(opt)
117
118 def test_set_cipher_preference_tlsv1_2_2025(self):
119 opt = TlsContextOptions()
120 opt.cipher_pref = TlsCipherPref.TLSv1_2_2025_07
121
122 try:
123 ctx = ClientTlsContext(opt)
124 except Exception as e:
125 if sys.platform.startswith("linux"):
126 # On Linux, this should not fail
127 self.fail(f"Unexpected error on Linux: {e}")
128 else:
129 # On non-Linux platforms, verify we get the expected error and skip
130 self.assertIn('AWS_IO_TLS_CIPHER_PREF_UNSUPPORTED', str(e))
131 self.skipTest(f"TLSv1_2_2025_07 not supported on {sys.platform}")
132
133
134 class TlsConnectionOptionsTest(NativeResourceTest):
135 def test_init(self):
136 opt = TlsContextOptions()
137 ctx = ClientTlsContext(opt)
138 conn_opt = TlsConnectionOptions(ctx)
139
140 def test_alpn_list(self):
141 opt = TlsContextOptions()
142 ctx = ClientTlsContext(opt)
143 conn_opt = TlsConnectionOptions(ctx)
144 conn_opt.set_alpn_list(['h2', 'http/1.1'])
145
146 def test_server_name(self):
147 opt = TlsContextOptions()
148 ctx = ClientTlsContext(opt)
149 conn_opt = TlsConnectionOptions(ctx)
150 conn_opt.set_server_name('localhost')
151
152
153 class MockPythonStream:
154 """For testing duck-typed stream classes.
155 Doesn't inherit from io.IOBase. Doesn't implement readinto()"""
156
157 def __init__(self, src_data):
158 self.data = bytes(src_data)
159 self.len = len(src_data)
160 self.pos = 0
161
162 def seek(self, where):
163 self.pos = where
164
165 def tell(self):
166 return self.pos
167
168 def read(self, amount=None):
169 if amount is None:
170 amount = self.len - self.pos
171 else:
172 amount = min(amount, self.len - self.pos)
173 prev_pos = self.pos
174 self.pos += amount
175 return self.data[prev_pos: self.pos]
176
177
178 class InputStreamTest(NativeResourceTest):
179 def _test(self, python_stream, expected):
180 input_stream = InputStream(python_stream)
181 result = bytearray()
182 fixed_mv_len = 4
183 fixed_mv = memoryview(bytearray(fixed_mv_len))
184 while True:
185 read_len = input_stream._read_into_memoryview(fixed_mv)
186 if read_len is None:
187 continue
188 if read_len == 0:
189 break
190 if read_len > 0:
191 self.assertLessEqual(read_len, fixed_mv_len)
192 result += fixed_mv[0:read_len]
193
194 self.assertEqual(expected, result)
195
196 def test_read_official_io(self):
197 # Read from a class defined in the io module
198 src_data = b'a long string here'
199 python_stream = io.BytesIO(src_data)
200 self._test(python_stream, src_data)
201
202 def test_read_duck_typed_io(self):
203 # Read from a class defined in the io module
204 src_data = b'a man a can a planal canada'
205 python_stream = MockPythonStream(src_data)
206 self._test(python_stream, src_data)
207
208
209 class Pkcs11LibTest(NativeResourceTest):
210 def _lib_path(self):
211 val = os.environ.get("AWS_TEST_PKCS11_LIB")
212 if not val:
213 raise unittest.SkipTest(f"test requires env var: AWS_TEST_PKCS11_LIB")
214 return val
215
216 def test_init(self):
217 # sanity check that we can create/destroy
218 lib_path = self._lib_path()
219 pcks11_lib = Pkcs11Lib(file=lib_path, behavior=Pkcs11Lib.InitializeFinalizeBehavior.STRICT)
220
221 def test_exceptions(self):
222 # check that initialization errors bubble up as exceptions
223 with self.assertRaises(Exception):
224 pkcs11_lib = Pkcs11Lib(file='obviously-invalid-path.so')
225
226 with self.assertRaises(Exception):
227 with open(self._lib_path()) as literal_open_file:
228 # a filepath str should passed, not a literal open file
229 pkcs11_lib = Pkcs11Lib(file=literal_open_file)
230
231 def test_strict_behavior(self):
232 lib_path = self._lib_path()
233 lib1 = Pkcs11Lib(file=lib_path, behavior=Pkcs11Lib.InitializeFinalizeBehavior.STRICT)
234 # InitializeFinalizeBehavior.STRICT behavior should fail if the PKCS#11 lib is already loaded
235 with self.assertRaises(Exception):
236 lib2 = Pkcs11Lib(file=lib_path, behavior=Pkcs11Lib.InitializeFinalizeBehavior.STRICT)
237
238 def test_omit_behavior(self):
239 lib_path = self._lib_path()
240 # InitializeFinalizeBehavior.OMIT should fail unless another instance of the PKCS#11 lib is already loaded
241 with self.assertRaises(Exception):
242 lib = Pkcs11Lib(file=lib_path, behavior=Pkcs11Lib.InitializeFinalizeBehavior.OMIT)
243
244 # InitializeFinalizeBehavior.OMIT behavior should be fine when another
245 # instance of the PKCS#11 lib is already loaded
246 strict_lib = Pkcs11Lib(file=lib_path, behavior=Pkcs11Lib.InitializeFinalizeBehavior.STRICT)
247 omit_lib = Pkcs11Lib(file=lib_path, behavior=Pkcs11Lib.InitializeFinalizeBehavior.OMIT)
248
249 def test_is_tls_cipher_supported(self):
250 self.assertEqual(True, TlsCipherPref.DEFAULT.is_supported())
251
252
253 class PythonLoggingTest(NativeResourceTest):
254 @classmethod
255 def setUpClass(cls):
256 init_logging(logging.DEBUG)
257
258 def test_log_level_and_message(self):
259 handler = logging.Handler()
260 handler.records = []
261 handler.emit = lambda record: handler.records.append(record)
262
263 logger = logging.getLogger('awscrt')
264 logger.setLevel(logging.DEBUG)
265 logger.addHandler(handler)
266
267 try:
268 log(logging.INFO, LogSubject.COMMON_GENERAL, "test message")
269
270 self.assertEqual(len(handler.records), 1)
271 self.assertEqual(handler.records[0].levelno, logging.INFO)
272 self.assertIn("test message", handler.records[0].getMessage())
273 finally:
274 logger.removeHandler(handler)
275
276 def test_log_subject(self):
277 handler = logging.Handler()
278 handler.records = []
279 handler.emit = lambda record: handler.records.append(record)
280
281 logger = logging.getLogger('awscrt')
282 logger.setLevel(logging.DEBUG)
283 logger.addHandler(handler)
284
285 try:
286 log(logging.DEBUG, LogSubject.IO_EVENT_LOOP, "event loop test")
287
288 self.assertEqual(len(handler.records), 1)
289 self.assertEqual(handler.records[0].name, "awscrt.io.event-loop")
290 self.assertIn("event loop test", handler.records[0].getMessage())
291 finally:
292 logger.removeHandler(handler)
293
294 def test_log_subject_hierarchy(self):
295 """Verify that log subjects from different CRT packages produce correct hierarchical logger names."""
296 cases = [
297 (LogSubject.COMMON_GENERAL, "awscrt.common."),
298 (LogSubject.IO_EVENT_LOOP, "awscrt.io."),
299 (LogSubject.HTTP_GENERAL, "awscrt.http."),
300 (LogSubject.EVENT_STREAM_GENERAL, "awscrt.event-stream."),
301 (LogSubject.MQTT_GENERAL, "awscrt.mqtt."),
302 (LogSubject.AUTH_GENERAL, "awscrt.auth."),
303 (LogSubject.CAL_GENERAL, "awscrt.cal."),
304 (LogSubject.S3_GENERAL, "awscrt.s3."),
305 (LogSubject.SDKUTILS_GENERAL, "awscrt.sdkutils."),
306 ]
307
308 handler = logging.Handler()
309 handler.records = []
310 handler.emit = lambda record: handler.records.append(record)
311
312 logger = logging.getLogger('awscrt')
313 logger.setLevel(logging.DEBUG)
314 logger.addHandler(handler)
315
316 try:
317 for subject, expected_prefix in cases:
318 handler.records.clear()
319 log(logging.DEBUG, subject, "test")
320 self.assertEqual(len(handler.records), 1)
321 self.assertTrue(
322 handler.records[0].name.startswith(expected_prefix),
323 f"Subject {subject.name}: expected logger starting with "
324 f"'{expected_prefix}', got '{handler.records[0].name}'"
325 )
326 finally:
327 logger.removeHandler(handler)
328
329 def _emit_all_subjects_and_levels(self):
330 """Emit logs across all subjects at INFO and DEBUG levels."""
331 for subject in (LogSubject.IO_EVENT_LOOP, LogSubject.HTTP_GENERAL,
332 LogSubject.EVENT_STREAM_GENERAL, LogSubject.MQTT_GENERAL,
333 LogSubject.S3_GENERAL, LogSubject.AUTH_GENERAL,
334 LogSubject.CAL_GENERAL, LogSubject.SDKUTILS_GENERAL,
335 LogSubject.COMMON_GENERAL):
336 log(logging.INFO, subject, f"{subject.name} info")
337 log(logging.DEBUG, subject, f"{subject.name} debug")
338
339 def test_logging_filters(self):
340 """Verify level and subject filtering across different logger configurations."""
341 handler = logging.Handler()
342 handler.records = []
343 handler.emit = lambda record: handler.records.append(record)
344
345 root = logging.getLogger('awscrt')
346 root.addHandler(handler)
347
348 try:
349 # All at DEBUG: should get all 18 records (9 subjects x 2 levels)
350 root.setLevel(logging.DEBUG)
351 self._emit_all_subjects_and_levels()
352 self.assertEqual(len(handler.records), 18)
353 handler.records.clear()
354
355 # All at INFO: should get only 9 INFO records
356 root.setLevel(logging.INFO)
357 self._emit_all_subjects_and_levels()
358 self.assertEqual(len(handler.records), 9)
359 self.assertTrue(all(r.levelno == logging.INFO for r in handler.records))
360 handler.records.clear()
361
362 # All at WARNING: nothing should pass
363 root.setLevel(logging.WARNING)
364 self._emit_all_subjects_and_levels()
365 self.assertEqual(len(handler.records), 0)
366
367 # Enable only HTTP at DEBUG: should get 2 HTTP records
368 logging.getLogger('awscrt.http').setLevel(logging.DEBUG)
369 self._emit_all_subjects_and_levels()
370 self.assertEqual(len(handler.records), 2)
371 self.assertTrue(all(r.name.startswith("awscrt.http.") for r in handler.records))
372 handler.records.clear()
373
374 # Also enable S3 at INFO: should get 2 HTTP + 1 S3 INFO
375 logging.getLogger('awscrt.s3').setLevel(logging.INFO)
376 self._emit_all_subjects_and_levels()
377 http_records = [r for r in handler.records if r.name.startswith("awscrt.http.")]
378 s3_records = [r for r in handler.records if r.name.startswith("awscrt.s3.")]
379 self.assertEqual(len(http_records), 2)
380 self.assertEqual(len(s3_records), 1)
381 self.assertEqual(s3_records[0].levelno, logging.INFO)
382 self.assertEqual(len(handler.records), 3)
383 handler.records.clear()
384
385 finally:
386 root.setLevel(logging.DEBUG)
387 logging.getLogger('awscrt.http').setLevel(logging.NOTSET)
388 logging.getLogger('awscrt.s3').setLevel(logging.NOTSET)
389 root.removeHandler(handler)
390
391 @classmethod
392 def tearDownClass(cls):
393 set_log_level(logging.NOTSET)
394
395
396 if __name__ == '__main__':
397 unittest.main()