Skip to content

Commit 4aaa4dc

Browse files
committed
ruff format the tests
1 parent 1fc9c88 commit 4aaa4dc

File tree

6 files changed

+299
-166
lines changed

6 files changed

+299
-166
lines changed
Lines changed: 11 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,22 @@
11
# Test package for traceback timestamps feature
22

3+
34
def load_tests(loader, tests, pattern):
45
"""Load all tests from the package."""
56
import unittest
6-
from . import test_basic, test_pickle, test_user_exceptions, test_timestamp_presence
7-
7+
from . import (
8+
test_basic,
9+
test_pickle,
10+
test_user_exceptions,
11+
test_timestamp_presence,
12+
)
13+
814
suite = unittest.TestSuite()
9-
15+
1016
# Add tests from all modules
1117
suite.addTests(loader.loadTestsFromModule(test_basic))
1218
suite.addTests(loader.loadTestsFromModule(test_pickle))
1319
suite.addTests(loader.loadTestsFromModule(test_user_exceptions))
1420
suite.addTests(loader.loadTestsFromModule(test_timestamp_presence))
15-
16-
return suite
21+
22+
return suite

Lib/test/test_traceback_timestamps/shared_utils.py

Lines changed: 47 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,23 @@
11
"""
22
Shared utilities for traceback timestamps tests.
33
"""
4+
45
import json
56
import sys
67

78

89
def get_builtin_exception_types():
910
"""Get all built-in exception types from the exception hierarchy."""
1011
exceptions = []
11-
12+
1213
def collect_exceptions(exc_class):
13-
if (hasattr(__builtins__, exc_class.__name__) and
14-
issubclass(exc_class, BaseException)):
14+
if hasattr(__builtins__, exc_class.__name__) and issubclass(
15+
exc_class, BaseException
16+
):
1517
exceptions.append(exc_class.__name__)
1618
for subclass in exc_class.__subclasses__():
1719
collect_exceptions(subclass)
18-
20+
1921
collect_exceptions(BaseException)
2022
return sorted(exceptions)
2123

@@ -26,26 +28,44 @@ def create_exception_instance(exc_class_name):
2628
if hasattr(__builtins__, exc_class_name):
2729
exc_class = getattr(__builtins__, exc_class_name)
2830
else:
29-
exc_class = getattr(sys.modules['builtins'], exc_class_name)
30-
31+
exc_class = getattr(sys.modules["builtins"], exc_class_name)
32+
3133
# Create exception with appropriate arguments
32-
if exc_class_name in ('OSError', 'IOError', 'PermissionError', 'FileNotFoundError',
33-
'FileExistsError', 'IsADirectoryError', 'NotADirectoryError',
34-
'InterruptedError', 'ChildProcessError', 'ConnectionError',
35-
'BrokenPipeError', 'ConnectionAbortedError', 'ConnectionRefusedError',
36-
'ConnectionResetError', 'ProcessLookupError', 'TimeoutError'):
34+
if exc_class_name in (
35+
"OSError",
36+
"IOError",
37+
"PermissionError",
38+
"FileNotFoundError",
39+
"FileExistsError",
40+
"IsADirectoryError",
41+
"NotADirectoryError",
42+
"InterruptedError",
43+
"ChildProcessError",
44+
"ConnectionError",
45+
"BrokenPipeError",
46+
"ConnectionAbortedError",
47+
"ConnectionRefusedError",
48+
"ConnectionResetError",
49+
"ProcessLookupError",
50+
"TimeoutError",
51+
):
3752
return exc_class(2, "No such file or directory")
38-
elif exc_class_name == 'UnicodeDecodeError':
39-
return exc_class('utf-8', b'\xff', 0, 1, 'invalid start byte')
40-
elif exc_class_name == 'UnicodeEncodeError':
41-
return exc_class('ascii', '\u1234', 0, 1, 'ordinal not in range')
42-
elif exc_class_name == 'UnicodeTranslateError':
43-
return exc_class('\u1234', 0, 1, 'character maps to <undefined>')
44-
elif exc_class_name in ('SyntaxError', 'IndentationError', 'TabError'):
53+
elif exc_class_name == "UnicodeDecodeError":
54+
return exc_class("utf-8", b"\xff", 0, 1, "invalid start byte")
55+
elif exc_class_name == "UnicodeEncodeError":
56+
return exc_class("ascii", "\u1234", 0, 1, "ordinal not in range")
57+
elif exc_class_name == "UnicodeTranslateError":
58+
return exc_class("\u1234", 0, 1, "character maps to <undefined>")
59+
elif exc_class_name in ("SyntaxError", "IndentationError", "TabError"):
4560
return exc_class("invalid syntax", ("test.py", 1, 1, "bad code"))
46-
elif exc_class_name == 'SystemExit':
61+
elif exc_class_name == "SystemExit":
4762
return exc_class(0)
48-
elif exc_class_name in ('KeyboardInterrupt', 'StopIteration', 'StopAsyncIteration', 'GeneratorExit'):
63+
elif exc_class_name in (
64+
"KeyboardInterrupt",
65+
"StopIteration",
66+
"StopAsyncIteration",
67+
"GeneratorExit",
68+
):
4969
return exc_class()
5070
else:
5171
try:
@@ -57,18 +77,18 @@ def create_exception_instance(exc_class_name):
5777
def run_subprocess_test(script_code, args, xopts=None, env_vars=None):
5878
"""Run a test script in subprocess and return parsed JSON result."""
5979
from test.support import script_helper
60-
80+
6181
cmd_args = []
6282
if xopts:
6383
for opt in xopts:
6484
cmd_args.extend(["-X", opt])
6585
cmd_args.extend(["-c", script_code])
6686
cmd_args.extend(args)
67-
87+
6888
kwargs = {}
6989
if env_vars:
7090
kwargs.update(env_vars)
71-
91+
7292
result = script_helper.assert_python_ok(*cmd_args, **kwargs)
7393
return json.loads(result.out.decode())
7494

@@ -112,7 +132,7 @@ def create_exception_instance(exc_class_name):
112132
'''
113133

114134

115-
PICKLE_TEST_SCRIPT = f'''
135+
PICKLE_TEST_SCRIPT = f"""
116136
import pickle
117137
import sys
118138
import json
@@ -148,10 +168,10 @@ def test_exception_pickle(exc_class_name, with_timestamps=False):
148168
exc_name = sys.argv[1]
149169
with_timestamps = len(sys.argv) > 2 and sys.argv[2] == 'with_timestamps'
150170
test_exception_pickle(exc_name, with_timestamps)
151-
'''
171+
"""
152172

153173

154-
TIMESTAMP_TEST_SCRIPT = f'''
174+
TIMESTAMP_TEST_SCRIPT = f"""
155175
import sys
156176
import json
157177
import traceback
@@ -188,4 +208,4 @@ def test_exception_timestamp(exc_class_name):
188208
if __name__ == "__main__":
189209
exc_name = sys.argv[1]
190210
test_exception_timestamp(exc_name)
191-
'''
211+
"""

Lib/test/test_traceback_timestamps/test_basic.py

Lines changed: 45 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -39,10 +39,9 @@ def cause_exception():
3939
self.addCleanup(unlink, self.flags_script_path)
4040

4141
self.env = EnvironmentVarGuard()
42-
self.env.set('PYTHONUTF8', '1') # -X utf8=1
42+
self.env.set("PYTHONUTF8", "1") # -X utf8=1
4343
self.addCleanup(self.env.__exit__)
4444

45-
4645
def test_no_traceback_timestamps(self):
4746
"""Test that traceback timestamps are not shown by default"""
4847
result = script_helper.assert_python_ok(self.script_path)
@@ -78,7 +77,9 @@ def test_traceback_timestamps_flag_iso(self):
7877
)
7978
self.assertIn(b"<@", result.err) # Timestamp should be present
8079
# ISO format with Z suffix for UTC
81-
self.assertRegex(result.err, br"<@\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{6}Z>")
80+
self.assertRegex(
81+
result.err, rb"<@\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{6}Z>"
82+
)
8283

8384
def test_traceback_timestamps_flag_value(self):
8485
"""Test that sys.flags.traceback_timestamps shows the right value"""
@@ -180,7 +181,9 @@ def test_traceback_timestamps_invalid_flag(self):
180181
result = script_helper.assert_python_failure(
181182
"-X", "traceback_timestamps=invalid", self.flags_script_path
182183
)
183-
self.assertIn(b"Invalid -X traceback_timestamps=value option", result.err)
184+
self.assertIn(
185+
b"Invalid -X traceback_timestamps=value option", result.err
186+
)
184187

185188

186189
class StripExcTimestampsTests(unittest.TestCase):
@@ -215,23 +218,37 @@ def test_strip_exc_timestamps_function(self):
215218
for mode in ("us", "ns", "iso"):
216219
with self.subTest(mode):
217220
result = script_helper.assert_python_failure(
218-
"-X", f"traceback_timestamps={mode}",
219-
self.script_strip_path
221+
"-X",
222+
f"traceback_timestamps={mode}",
223+
self.script_strip_path,
224+
)
225+
output = result.out.decode() + result.err.decode(
226+
errors="ignore"
220227
)
221-
output = result.out.decode() + result.err.decode(errors='ignore')
222228

223229
# call strip_exc_timestamps in a process using the same mode as what generated our output.
224230
result = script_helper.assert_python_ok(
225-
"-X", f"traceback_timestamps={mode}",
226-
self.script_strip_path, output
231+
"-X",
232+
f"traceback_timestamps={mode}",
233+
self.script_strip_path,
234+
output,
235+
)
236+
stripped_output = result.out.decode() + result.err.decode(
237+
errors="ignore"
227238
)
228-
stripped_output = result.out.decode() + result.err.decode(errors='ignore')
229239

230240
# Verify original strings have timestamps and stripped ones don't
231241
self.assertIn("ZeroDivisionError: division by zero <@", output)
232-
self.assertNotRegex(output, "(?m)ZeroDivisionError: division by zero(\n|\r|$)")
233-
self.assertRegex(stripped_output, "(?m)ZeroDivisionError: division by zero(\r|\n|$)")
234-
self.assertRegex(stripped_output, "(?m)FakeError: not an exception(\r|\n|$)")
242+
self.assertNotRegex(
243+
output, "(?m)ZeroDivisionError: division by zero(\n|\r|$)"
244+
)
245+
self.assertRegex(
246+
stripped_output,
247+
"(?m)ZeroDivisionError: division by zero(\r|\n|$)",
248+
)
249+
self.assertRegex(
250+
stripped_output, "(?m)FakeError: not an exception(\r|\n|$)"
251+
)
235252

236253
@force_not_colorized
237254
def test_strip_exc_timestamps_with_disabled_timestamps(self):
@@ -240,24 +257,31 @@ def test_strip_exc_timestamps_with_disabled_timestamps(self):
240257
result = script_helper.assert_python_failure(
241258
"-X", "traceback_timestamps=0", self.script_strip_path
242259
)
243-
output = result.out.decode() + result.err.decode(errors='ignore')
260+
output = result.out.decode() + result.err.decode(errors="ignore")
244261

245262
# call strip_exc_timestamps in a process using the same mode as what generated our output.
246263
result = script_helper.assert_python_ok(
247264
"-X", "traceback_timestamps=0", self.script_strip_path, output
248265
)
249-
stripped_output = result.out.decode() + result.err.decode(errors='ignore')
266+
stripped_output = result.out.decode() + result.err.decode(
267+
errors="ignore"
268+
)
250269

251270
# All strings should be unchanged by the strip function
252-
self.assertRegex(stripped_output, "(?m)ZeroDivisionError: division by zero(\r|\n|$)")
271+
self.assertRegex(
272+
stripped_output, "(?m)ZeroDivisionError: division by zero(\r|\n|$)"
273+
)
253274
# it fits the pattern but traceback timestamps were disabled to strip_exc_timestamps does nothing.
254275
self.assertRegex(
255-
stripped_output, "(?m)FakeError: not an exception <@1234567890.123456>(\r|\n|$)"
276+
stripped_output,
277+
"(?m)FakeError: not an exception <@1234567890.123456>(\r|\n|$)",
256278
)
257279

258280
def test_timestamp_regex_pattern(self):
259281
"""Test the regex pattern used by strip_exc_timestamps"""
260-
pattern = re.compile(TIMESTAMP_AFTER_EXC_MSG_RE_GROUP, flags=re.MULTILINE)
282+
pattern = re.compile(
283+
TIMESTAMP_AFTER_EXC_MSG_RE_GROUP, flags=re.MULTILINE
284+
)
261285

262286
# Test microsecond format
263287
self.assertTrue(pattern.search(" <@1234567890.123456>"))
@@ -268,7 +292,9 @@ def test_timestamp_regex_pattern(self):
268292

269293
# Test what should not match
270294
self.assertFalse(pattern.search("<@>")) # Empty timestamp
271-
self.assertFalse(pattern.search(" <1234567890.123456>")) # Missing @ sign
295+
self.assertFalse(
296+
pattern.search(" <1234567890.123456>")
297+
) # Missing @ sign
272298
self.assertFalse(pattern.search("<@abc>")) # Non-numeric timestamp
273299

274300

Lines changed: 42 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
"""
22
Tests for pickle/unpickle of exception types with timestamp feature.
33
"""
4+
45
import unittest
56
from test.support import script_helper
67
from .shared_utils import get_builtin_exception_types, PICKLE_TEST_SCRIPT
@@ -12,51 +13,68 @@ class ExceptionPickleTests(unittest.TestCase):
1213
def _get_builtin_exception_types(self):
1314
"""Get concrete built-in exception types (excluding abstract bases)."""
1415
all_types = get_builtin_exception_types()
15-
return [exc for exc in all_types if exc not in ['BaseException', 'Exception']]
16+
return [
17+
exc
18+
for exc in all_types
19+
if exc not in ["BaseException", "Exception"]
20+
]
1621

1722
def test_builtin_exception_pickle_without_timestamps(self):
1823
"""Test that all built-in exception types can be pickled without timestamps."""
1924
exception_types = self._get_builtin_exception_types()
20-
25+
2126
for exc_name in exception_types:
2227
with self.subTest(exception_type=exc_name):
2328
result = script_helper.assert_python_ok(
2429
"-c", PICKLE_TEST_SCRIPT, exc_name
2530
)
26-
31+
2732
import json
33+
2834
output = json.loads(result.out.decode())
29-
30-
self.assertNotIn('error', output,
31-
f"Error pickling {exc_name}: {output.get('error', 'Unknown')}")
32-
self.assertEqual(output['exception_type'], exc_name)
33-
self.assertTrue(output['has_custom_attr'])
34-
self.assertEqual(output['custom_attr_value'], 'custom_value')
35-
self.assertFalse(output['has_timestamp'])
35+
36+
self.assertNotIn(
37+
"error",
38+
output,
39+
f"Error pickling {exc_name}: {output.get('error', 'Unknown')}",
40+
)
41+
self.assertEqual(output["exception_type"], exc_name)
42+
self.assertTrue(output["has_custom_attr"])
43+
self.assertEqual(output["custom_attr_value"], "custom_value")
44+
self.assertFalse(output["has_timestamp"])
3645

3746
def test_builtin_exception_pickle_with_timestamps(self):
3847
"""Test that all built-in exception types can be pickled with timestamps."""
3948
exception_types = self._get_builtin_exception_types()
40-
49+
4150
for exc_name in exception_types:
4251
with self.subTest(exception_type=exc_name):
4352
result = script_helper.assert_python_ok(
44-
"-X", "traceback_timestamps=us",
45-
"-c", PICKLE_TEST_SCRIPT,
46-
exc_name, "with_timestamps"
53+
"-X",
54+
"traceback_timestamps=us",
55+
"-c",
56+
PICKLE_TEST_SCRIPT,
57+
exc_name,
58+
"with_timestamps",
4759
)
48-
60+
4961
import json
62+
5063
output = json.loads(result.out.decode())
51-
52-
self.assertNotIn('error', output,
53-
f"Error pickling {exc_name}: {output.get('error', 'Unknown')}")
54-
self.assertEqual(output['exception_type'], exc_name)
55-
self.assertTrue(output['has_custom_attr'])
56-
self.assertEqual(output['custom_attr_value'], 'custom_value')
57-
self.assertTrue(output['has_timestamp'])
58-
self.assertEqual(output['timestamp_value'], 1234567890123456789)
64+
65+
self.assertNotIn(
66+
"error",
67+
output,
68+
f"Error pickling {exc_name}: {output.get('error', 'Unknown')}",
69+
)
70+
self.assertEqual(output["exception_type"], exc_name)
71+
self.assertTrue(output["has_custom_attr"])
72+
self.assertEqual(output["custom_attr_value"], "custom_value")
73+
self.assertTrue(output["has_timestamp"])
74+
self.assertEqual(
75+
output["timestamp_value"], 1234567890123456789
76+
)
5977

6078

6179
if __name__ == "__main__":
62-
unittest.main()
80+
unittest.main()

0 commit comments

Comments
 (0)