Skip to content

Commit 86a7158

Browse files
committed
gh-131178: Use support.captured_stdout() and support.captured_stderr()
1 parent 35759fe commit 86a7158

23 files changed

+93
-145
lines changed

Lib/test/test_argparse.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -56,7 +56,7 @@ class StdStreamTest(unittest.TestCase):
5656
def test_skip_invalid_stderr(self):
5757
parser = argparse.ArgumentParser()
5858
with (
59-
contextlib.redirect_stderr(None),
59+
captured_stderr(),
6060
mock.patch('argparse._sys.exit')
6161
):
6262
parser.exit(status=0, message='foo')

Lib/test/test_ast/test_ast.py

Lines changed: 3 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
import _ast_unparse
22
import ast
33
import builtins
4-
import contextlib
54
import copy
65
import dis
76
import enum
@@ -14,7 +13,6 @@
1413
import types
1514
import unittest
1615
import weakref
17-
from io import StringIO
1816
from pathlib import Path
1917
from textwrap import dedent
2018
try:
@@ -3417,11 +3415,9 @@ def set_source(self, content):
34173415
Path(self.filename).write_text(self.text_normalize(content))
34183416

34193417
def invoke_ast(self, *flags):
3420-
stderr = StringIO()
3421-
stdout = StringIO()
34223418
with (
3423-
contextlib.redirect_stdout(stdout),
3424-
contextlib.redirect_stderr(stderr),
3419+
support.captured_stdout() as stdout,
3420+
support.captured_stderr() as stderr,
34253421
):
34263422
ast.main(args=[*flags, self.filename])
34273423
self.assertEqual(stderr.getvalue(), '')
@@ -3462,9 +3458,8 @@ def f(x: int) -> int:
34623458
def test_help_message(self):
34633459
for flag in ('-h', '--help', '--unknown'):
34643460
with self.subTest(flag=flag):
3465-
output = StringIO()
34663461
with self.assertRaises(SystemExit):
3467-
with contextlib.redirect_stderr(output):
3462+
with support.captured_stderr() as output:
34683463
ast.main(args=flag)
34693464
self.assertStartsWith(output.getvalue(), 'usage: ')
34703465

Lib/test/test_compile.py

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,4 @@
1-
import contextlib
21
import dis
3-
import io
42
import itertools
53
import math
64
import opcode
@@ -967,8 +965,7 @@ class C:
967965
for mode in ["exec", "single"]:
968966
with self.subTest(opt=opt, mode=mode):
969967
code = compile(src, "<test>", mode, optimize=opt)
970-
output = io.StringIO()
971-
with contextlib.redirect_stdout(output):
968+
with support.captured_stdout() as output:
972969
dis.dis(code)
973970
self.assertNotIn('NOP', output.getvalue())
974971

Lib/test/test_compileall.py

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@
22
import contextlib
33
import filecmp
44
import importlib.util
5-
import io
65
import os
76
import py_compile
87
import shutil
@@ -89,7 +88,7 @@ def test_year_2038_mtime_compilation(self):
8988
os.utime(self.source_path, (2**32 - 1, 2**32 - 1))
9089
except (OverflowError, OSError):
9190
self.skipTest("filesystem doesn't support timestamps near 2**32")
92-
with contextlib.redirect_stdout(io.StringIO()):
91+
with support.captured_stdout():
9392
self.assertTrue(compileall.compile_file(self.source_path))
9493

9594
def test_larger_than_32_bit_times(self):
@@ -99,7 +98,7 @@ def test_larger_than_32_bit_times(self):
9998
os.utime(self.source_path, (2**35, 2**35))
10099
except (OverflowError, OSError):
101100
self.skipTest("filesystem doesn't support large timestamps")
102-
with contextlib.redirect_stdout(io.StringIO()):
101+
with support.captured_stdout():
103102
self.assertTrue(compileall.compile_file(self.source_path))
104103

105104
def recreation_check(self, metadata):
@@ -206,7 +205,7 @@ def test_no_pycache_in_non_package(self):
206205
def test_compile_file_encoding_fallback(self):
207206
# Bug 44666 reported that compile_file failed when sys.stdout.encoding is None
208207
self.add_bad_source_file()
209-
with contextlib.redirect_stdout(io.StringIO()):
208+
with support.captured_stdout():
210209
self.assertFalse(compileall.compile_file(self.bad_source_path))
211210

212211

@@ -510,8 +509,7 @@ def tearDown(self):
510509
shutil.rmtree(self.directory)
511510

512511
def test_error(self):
513-
buffer = io.TextIOWrapper(io.BytesIO(), encoding='ascii')
514-
with contextlib.redirect_stdout(buffer):
512+
with support.captured_stdout() as buffer:
515513
compiled = compileall.compile_dir(self.directory)
516514
self.assertFalse(compiled) # should not be successful
517515
buffer.seek(0)

Lib/test/test_concurrent_futures/test_interpreter_pool.py

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
import _thread
22
import asyncio
33
import contextlib
4-
import io
54
import os
65
import subprocess
76
import sys
@@ -199,14 +198,14 @@ def init2():
199198
nonlocal count
200199
count += 1
201200

202-
with contextlib.redirect_stderr(io.StringIO()) as stderr:
201+
with support.captured_stderr() as stderr:
203202
with self.executor_type(initializer=init1) as executor:
204203
fut = executor.submit(lambda: None)
205204
self.assertIn('NotShareableError', stderr.getvalue())
206205
with self.assertRaises(BrokenInterpreterPool):
207206
fut.result()
208207

209-
with contextlib.redirect_stderr(io.StringIO()) as stderr:
208+
with support.captured_stderr() as stderr:
210209
with self.executor_type(initializer=init2) as executor:
211210
fut = executor.submit(lambda: None)
212211
self.assertIn('NotShareableError', stderr.getvalue())
@@ -219,7 +218,7 @@ def initializer(self):
219218
raise NotImplementedError
220219
spam = Spam()
221220

222-
with contextlib.redirect_stderr(io.StringIO()) as stderr:
221+
with support.captured_stderr() as stderr:
223222
with self.executor_type(initializer=spam.initializer) as executor:
224223
fut = executor.submit(lambda: None)
225224
self.assertIn('NotShareableError', stderr.getvalue())
@@ -230,7 +229,7 @@ def initializer(self):
230229
def test_init_exception_in_script(self):
231230
executor = self.executor_type(initializer='raise Exception("spam")')
232231
with executor:
233-
with contextlib.redirect_stderr(io.StringIO()) as stderr:
232+
with support.captured_stderr() as stderr:
234233
fut = executor.submit('pass')
235234
with self.assertRaises(BrokenInterpreterPool):
236235
fut.result()
@@ -244,7 +243,7 @@ def test_init_exception_in_func(self):
244243
executor = self.executor_type(initializer=fail,
245244
initargs=(Exception, 'spam'))
246245
with executor:
247-
with contextlib.redirect_stderr(io.StringIO()) as stderr:
246+
with support.captured_stderr() as stderr:
248247
fut = executor.submit(noop)
249248
with self.assertRaises(BrokenInterpreterPool):
250249
fut.result()

Lib/test/test_descr.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1295,7 +1295,7 @@ def __init__(self):
12951295
def __del__(self_):
12961296
self.assertEqual(self_.a, 1)
12971297
self.assertEqual(self_.b, 2)
1298-
with support.captured_output('stderr') as s:
1298+
with support.captured_stderr() as s:
12991299
h = H()
13001300
del h
13011301
self.assertEqual(s.getvalue(), '')

Lib/test/test_dis.py

Lines changed: 10 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
# Minimal tests for dis module
22

33
import ast
4-
import contextlib
54
import dis
65
import functools
76
import io
@@ -13,9 +12,9 @@
1312
import textwrap
1413
import types
1514
import unittest
16-
from test.support import (captured_stdout, requires_debug_ranges,
17-
requires_specialization, cpython_only,
18-
os_helper, import_helper, reset_code)
15+
from test.support import (captured_stderr, captured_stdout,
16+
requires_debug_ranges, requires_specialization,
17+
cpython_only, os_helper, import_helper, reset_code)
1918
from test.support.bytecode_helper import BytecodeTestCase
2019

2120

@@ -971,8 +970,7 @@ class DisTests(DisTestBase):
971970

972971
def get_disassembly(self, func, lasti=-1, wrapper=True, **kwargs):
973972
# We want to test the default printing behaviour, not the file arg
974-
output = io.StringIO()
975-
with contextlib.redirect_stdout(output):
973+
with captured_stdout() as output:
976974
if wrapper:
977975
dis.dis(func, **kwargs)
978976
else:
@@ -988,8 +986,7 @@ def do_disassembly_test(self, func, expected, **kwargs):
988986
self.do_disassembly_compare(got, expected)
989987
# Add checks for dis.disco
990988
if hasattr(func, '__code__'):
991-
got_disco = io.StringIO()
992-
with contextlib.redirect_stdout(got_disco):
989+
with captured_stdout() as got_disco:
993990
dis.disco(func.__code__, **kwargs)
994991
self.do_disassembly_compare(got_disco.getvalue(), expected)
995992

@@ -1709,8 +1706,7 @@ def _stringify_instruction(instr):
17091706
return base + "),"
17101707

17111708
def _prepare_test_cases():
1712-
ignore = io.StringIO()
1713-
with contextlib.redirect_stdout(ignore):
1709+
with captured_stdout():
17141710
f = outer()
17151711
inner = f()
17161712
_instructions_outer = dis.get_instructions(outer, first_line=expected_outer_line)
@@ -2428,8 +2424,7 @@ def setUp(self) -> None:
24282424
return super().setUp()
24292425

24302426
def get_disassembly(self, tb):
2431-
output = io.StringIO()
2432-
with contextlib.redirect_stdout(output):
2427+
with captured_stdout() as output:
24332428
dis.distb(tb)
24342429
return output.getvalue()
24352430

@@ -2455,8 +2450,7 @@ def test_distb_explicit_arg(self):
24552450
class TestDisTracebackWithFile(TestDisTraceback):
24562451
# Run the `distb` tests again, using the file arg instead of print
24572452
def get_disassembly(self, tb):
2458-
output = io.StringIO()
2459-
with contextlib.redirect_stdout(output):
2453+
with captured_stdout() as output:
24602454
dis.distb(tb, file=output)
24612455
return output.getvalue()
24622456

@@ -2506,8 +2500,7 @@ def set_source(self, content):
25062500
fp.write(self.text_normalize(content))
25072501

25082502
def invoke_dis(self, *flags):
2509-
output = io.StringIO()
2510-
with contextlib.redirect_stdout(output):
2503+
with captured_stdout() as output:
25112504
dis.main(args=[*flags, self.filename])
25122505
return self.text_normalize(output.getvalue())
25132506

@@ -2541,7 +2534,7 @@ def f():
25412534

25422535
with self.assertRaises(SystemExit):
25432536
# suppress argparse error message
2544-
with contextlib.redirect_stderr(io.StringIO()):
2537+
with captured_stderr():
25452538
_ = self.invoke_dis('--unknown')
25462539

25472540
def test_show_cache(self):

Lib/test/test_future_stmt/test_future_multiple_features.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ def test_unicode_literals(self):
1212
self.assertIsInstance("", str)
1313

1414
def test_print_function(self):
15-
with support.captured_output("stderr") as s:
15+
with support.captured_stderr() as s:
1616
print("foo", file=sys.stderr)
1717
self.assertEqual(s.getvalue(), "foo\n")
1818

Lib/test/test_itertools.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -879,7 +879,7 @@ def __next__(self):
879879
def run(r1, r2):
880880
result = []
881881
for i, j in zip_longest(r1, r2, fillvalue=0):
882-
with support.captured_output('stdout'):
882+
with support.captured_stdout():
883883
print((i, j))
884884
result.append((i, j))
885885
return result

Lib/test/test_pdb.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@
1717
import zipfile
1818

1919
from asyncio.events import _set_event_loop_policy
20-
from contextlib import ExitStack, redirect_stdout
20+
from contextlib import ExitStack
2121
from io import StringIO
2222
from test import support
2323
from test.support import has_socket_support, os_helper
@@ -4571,7 +4571,7 @@ def test_checkline_is_not_executable(self):
45714571
with open(os_helper.TESTFN, "w") as f:
45724572
f.write(s)
45734573
num_lines = len(s.splitlines()) + 2 # Test for EOF
4574-
with redirect_stdout(StringIO()):
4574+
with support.captured_stdout():
45754575
db = pdb.Pdb()
45764576
for lineno in range(num_lines):
45774577
self.assertFalse(db.checkline(os_helper.TESTFN, lineno))

0 commit comments

Comments
 (0)