Debian Codegraph @

test/__init__.py

raw symbols SCIP
1 # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2 # SPDX-License-Identifier: Apache-2.0.
3
4 # Enable native memory tracing so that tests can detect leaks.
5 # This env-var MUST be set before awscrt is imported.
6 # the "noqa" comment prevents the autoformatter from moving this line below other imports
7 import os
8 os.environ['AWS_CRT_MEMORY_TRACING'] = '2' # noqa
9 os.environ['AWS_CRT_CRASH_HANDLER'] = '1' # noqa
10
11 from awscrt import NativeResource
12 from awscrt._test import check_for_leaks
13 import time
14 import unittest
15
16 TIMEOUT = 30.0
17
18
19 class NativeResourceTest(unittest.TestCase):
20 """
21 Test fixture asserts there are no living NativeResources when a test completes.
22 """
23
24 _previous_test_failed = False
25
26 def setUp(self):
27 NativeResource._track_lifetime = True
28 # init_logging(LogLevel.Trace, 'stderr')
29
30 def tearDown(self):
31 # Stop checking for leaks if any test has failed.
32 # It's likely that the failed test leaks data, which will make
33 # all future tests look like they're leaking too.
34 if NativeResourceTest._previous_test_failed:
35 return
36
37 # Determine whether the current test just failed.
38 # This isn't possible with the public API,
39 # and the technique to pull it off can vary by Python version.
40 if hasattr(self._outcome, 'errors'):
41 # Works in Python 3.10 and earlier
42 result = self.defaultTestResult()
43 self._feedErrorsToResult(result, self._outcome.errors)
44 else:
45 # Works in Python 3.11 and later
46 result = self._outcome.result
47
48 current_test_failed = any(failed_test == self for failed_test, _ in result.errors + result.failures)
49 if current_test_failed:
50 NativeResourceTest._previous_test_failed = True
51 return
52
53 # All tests have passed so far, check for leaks
54 try:
55 check_for_leaks(timeout_sec=TIMEOUT)
56 except Exception:
57 NativeResourceTest._previous_test_failed = True
58 raise
59
60
61 MAX_RETRIES = 5
62
63
64 def _is_retryable_exception(e):
65 exception_text = str(e)
66 return "AWS_IO_TLS_NEGOTIATION_TIMEOUT" in exception_text or "AWS_IO_SOCKET_TIMEOUT" in exception_text
67
68
69 def test_retry_wrapper(test_function):
70 for i in range(MAX_RETRIES):
71 try:
72 test_function()
73 return
74 except Exception as e:
75 if _is_retryable_exception(e) and i + 1 < MAX_RETRIES:
76 check_for_leaks(timeout_sec=TIMEOUT) # Force cleanup between retries
77 time.sleep(1)
78 else:
79 raise