From c56169026964f7f023f32ff12fd0a6d3cd0153b1 Mon Sep 17 00:00:00 2001 From: Inada Naoki Date: Sat, 27 Jun 2026 21:27:00 +0900 Subject: [PATCH] use d-string --- Lib/idlelib/config_key.py | 14 +- Lib/idlelib/idle_test/htest.py | 9 +- Lib/idlelib/idle_test/test_colorizer.py | 9 +- Lib/idlelib/run.py | 8 +- Lib/importlib/metadata/__init__.py | 5 +- Lib/pdb.py | 35 ++- Lib/pydoc.py | 4 +- Lib/test/_test_multiprocessing.py | 32 +-- Lib/test/datetimetester.py | 17 +- Lib/test/support/import_helper.py | 11 +- Lib/test/test_annotationlib.py | 7 +- Lib/test/test_argparse.py | 132 +++++----- Lib/test/test_ast/test_ast.py | 110 ++++---- Lib/test/test_asyncio/test_subprocess.py | 5 +- Lib/test/test_atexit.py | 22 +- Lib/test/test_capi/test_exceptions.py | 9 +- Lib/test/test_capi/test_mem.py | 5 +- Lib/test/test_capi/test_misc.py | 48 ++-- Lib/test/test_capi/test_object.py | 8 +- Lib/test/test_capi/test_opt.py | 56 ++-- Lib/test/test_cmd.py | 9 +- Lib/test/test_cmd_line.py | 4 +- Lib/test/test_cmd_line_script.py | 21 +- Lib/test/test_code.py | 25 +- Lib/test/test_compile.py | 150 +++++------ Lib/test/test_compiler_assemble.py | 5 +- Lib/test/test_compiler_codegen.py | 9 +- .../test_interpreter_pool.py | 5 +- Lib/test/test_configparser.py | 93 ++++--- Lib/test/test_dataclasses/__init__.py | 5 +- Lib/test/test_descr.py | 5 +- Lib/test/test_email/test_contentmanager.py | 165 ++++++------ Lib/test/test_email/test_defect_handling.py | 37 ++- Lib/test/test_email/test_email.py | 136 +++++----- Lib/test/test_email/test_generator.py | 73 +++--- Lib/test/test_email/test_headerregistry.py | 19 +- Lib/test/test_email/test_inversion.py | 1 + Lib/test/test_email/test_message.py | 69 +++-- Lib/test/test_email/test_pickleable.py | 5 +- Lib/test/test_email/test_policy.py | 5 +- Lib/test/test_embed.py | 20 +- Lib/test/test_external_inspection.py | 48 +--- Lib/test/test_faulthandler.py | 61 +++-- Lib/test/test_frame.py | 5 +- Lib/test/test_funcattrs.py | 5 +- Lib/test/test_future_stmt/test_future.py | 42 +-- Lib/test/test_gc.py | 27 +- Lib/test/test_gc_stats.py | 4 +- Lib/test/test_gdb/test_backtrace.py | 5 +- Lib/test/test_gdb/test_cfunction.py | 5 +- Lib/test/test_generators.py | 5 +- Lib/test/test_import/__init__.py | 52 ++-- Lib/test/test_importlib/metadata/test_api.py | 5 +- Lib/test/test_importlib/test_util.py | 24 +- Lib/test/test_inspect/test_inspect.py | 28 +- Lib/test/test_interpreters/test_lifecycle.py | 4 +- Lib/test/test_io/test_general.py | 15 +- Lib/test/test_json/test_indent.py | 5 +- Lib/test/test_json/test_separators.py | 5 +- Lib/test/test_json/test_tool.py | 25 +- Lib/test/test_lazy_import/__init__.py | 168 ++++++------ Lib/test/test_list.py | 9 +- Lib/test/test_listcomps.py | 248 +++++++++--------- Lib/test/test_logging.py | 20 +- Lib/test/test_mailbox.py | 9 +- Lib/test/test_marshal.py | 5 +- Lib/test/test_mmap.py | 5 +- Lib/test/test_monitoring.py | 16 +- Lib/test/test_multibytecodec.py | 5 +- Lib/test/test_optparse.py | 10 +- Lib/test/test_os/test_os.py | 5 +- Lib/test/test_os/test_posix.py | 20 +- Lib/test/test_os/test_windows.py | 5 +- Lib/test/test_peepholer.py | 20 +- Lib/test/test_peg_generator/test_pegen.py | 42 ++- .../test_sampling_profiler/test_blocking.py | 5 +- .../test_profiling/test_tracing_profiler.py | 5 +- Lib/test/test_pyexpat.py | 12 +- Lib/test/test_pystats.py | 14 +- Lib/test/test_re.py | 12 +- Lib/test/test_readline.py | 9 +- Lib/test/test_regrtest.py | 176 ++++++------- Lib/test/test_runpy.py | 13 +- Lib/test/test_select.py | 5 +- Lib/test/test_smtplib.py | 5 +- Lib/test/test_sqlite3/test_cli.py | 21 +- Lib/test/test_str.py | 5 +- Lib/test/test_structseq.py | 5 +- Lib/test/test_subprocess.py | 24 +- Lib/test/test_super.py | 7 +- Lib/test/test_support.py | 9 +- Lib/test/test_syntax.py | 53 ++-- Lib/test/test_sys.py | 16 +- Lib/test/test_sys_settrace.py | 5 +- Lib/test/test_sysconfig.py | 5 +- Lib/test/test_thread_local_bytecode.py | 25 +- Lib/test/test_threading.py | 28 +- Lib/test/test_tomllib/test_misc.py | 7 +- Lib/test/test_tools/test_freeze.py | 5 +- Lib/test/test_trace.py | 13 +- Lib/test/test_traceback.py | 94 +++---- Lib/test/test_tracemalloc.py | 5 +- Lib/test/test_type_annotations.py | 74 +++--- Lib/test/test_type_params.py | 82 +++--- Lib/test/test_types.py | 5 +- Lib/test/test_typing.py | 6 +- Lib/test/test_unittest/test_result.py | 10 +- Lib/test/test_utf8_mode.py | 17 +- Lib/test/test_warnings/__init__.py | 21 +- Lib/test/test_weakref.py | 5 +- Lib/test/test_xml_etree.py | 9 +- Lib/test/test_zipimport_support.py | 9 +- 112 files changed, 1524 insertions(+), 1661 deletions(-) diff --git a/Lib/idlelib/config_key.py b/Lib/idlelib/config_key.py index e5f67e8d4069ee..b821e423deb33f 100644 --- a/Lib/idlelib/config_key.py +++ b/Lib/idlelib/config_key.py @@ -109,12 +109,14 @@ def create_widgets(self): # Basic entry help text. help_basic = Label(self.frame_controls_basic, justify='left', - text="Select the desired modifier keys\n"+ - "above, and the final key from the\n"+ - "list on the right.\n\n" + - "Use upper case Symbols when using\n" + - "the Shift modifier. (Letters will be\n" + - "converted automatically.)") + text=d""" + Select the desired modifier keys + above, and the final key from the + list on the right. + + Use upper case Symbols when using + the Shift modifier. (Letters will be + converted automatically.)""") help_basic.grid(row=1, column=0, columnspan=4, padx=2, sticky='w') # Basic entry key list. diff --git a/Lib/idlelib/idle_test/htest.py b/Lib/idlelib/idle_test/htest.py index b63ff9ec2877b9..f076665d6071f2 100644 --- a/Lib/idlelib/idle_test/htest.py +++ b/Lib/idlelib/idle_test/htest.py @@ -65,7 +65,6 @@ import idlelib.pyshell # Set Windows DPI awareness before Tk(). from importlib import import_module -import textwrap import tkinter as tk from tkinter.ttk import Scrollbar tk.NoDefaultRoot() @@ -215,10 +214,10 @@ _module_browser_spec = { 'file': 'browser', 'kwds': {}, - 'msg': textwrap.dedent(""" + 'msg': d""" "Inspect names of module, class(with superclass if applicable), "methods and functions. Toggle nested items. Double clicking - "on items prints a traceback for an exception that is ignored.""") + "on items prints a traceback for an exception that is ignored.""" } _multistatus_bar_spec = { @@ -302,7 +301,7 @@ _sidebar_number_scrolling_spec = { 'file': 'sidebar', 'kwds': {}, - 'msg': textwrap.dedent("""\ + 'msg': d""" 1. Click on the line numbers and drag down below the edge of the window, moving the mouse a bit and then leaving it there for a while. The text and line numbers should gradually scroll down, @@ -316,7 +315,7 @@ line numbers should gradually scroll up, with the selection updated continuously. - 4. Repeat step #2, clicking a line number below the selection."""), + 4. Repeat step #2, clicking a line number below the selection.""", } _stackbrowser_spec = { diff --git a/Lib/idlelib/idle_test/test_colorizer.py b/Lib/idlelib/idle_test/test_colorizer.py index fb6ee825086750..301b2331f70372 100644 --- a/Lib/idlelib/idle_test/test_colorizer.py +++ b/Lib/idlelib/idle_test/test_colorizer.py @@ -6,7 +6,6 @@ from idlelib.idle_test.tkinter_testing_utils import run_in_tk_mainloop from functools import partial -import textwrap from tkinter import Tk, Text from idlelib import config from idlelib.percolator import Percolator @@ -20,7 +19,7 @@ 'extensions': config.IdleUserConfParser(''), } -source = textwrap.dedent("""\ +source = d""" if True: int ('1') # keyword, builtin, string, comment elif False: print(0) # 'string' in comment else: float(None) # if in comment @@ -52,7 +51,7 @@ async def f(): await g() ''' case _:''' "match x:" - """) + """ def setUpModule(): @@ -561,13 +560,13 @@ def test_lazy_soft_keyword(self): self._assert_highlighting('lazy foo', {}) def test_long_multiline_string(self): - source = textwrap.dedent('''\ + source = d''' """a b c d e""" - ''') + ''' self._assert_highlighting(source, {'STRING': [('1.0', '5.4')]}) @run_in_tk_mainloop(delay=50) diff --git a/Lib/idlelib/run.py b/Lib/idlelib/run.py index e1c40fee8f4805..0f174e29a2ee50 100644 --- a/Lib/idlelib/run.py +++ b/Lib/idlelib/run.py @@ -481,21 +481,21 @@ def handle_error(self, request, client_address): thread.interrupt_main() except: erf = sys.__stderr__ - print(textwrap.dedent(f""" + print(fd""" {'-'*40} Unhandled exception in user code execution server!' Thread: {threading.current_thread().name} IDLE Client Address: {client_address} Request: {request!r} - """), file=erf) + """, file=erf) traceback.print_exc(limit=-20, file=erf) - print(textwrap.dedent(f""" + print(fd""" *** Unrecoverable, server exiting! Users should never see this message; it is likely transient. If this recurs, report this with a copy of the message and an explanation of how to make it repeat. - {'-'*40}"""), file=erf) + {'-'*40}""", file=erf) quitting = True thread.interrupt_main() diff --git a/Lib/importlib/metadata/__init__.py b/Lib/importlib/metadata/__init__.py index 32f4b7d2d6e08b..f53c94b4ed08a7 100644 --- a/Lib/importlib/metadata/__init__.py +++ b/Lib/importlib/metadata/__init__.py @@ -20,7 +20,6 @@ import posixpath import re import sys -import textwrap import types from collections.abc import Iterable, Mapping from contextlib import suppress @@ -101,8 +100,7 @@ class Sectioned: [] """ - _sample = textwrap.dedent( - """ + _sample = d""" [sec1] # comments ignored a = 1 @@ -111,7 +109,6 @@ class Sectioned: [sec2] a = 2 """ - ).lstrip() @classmethod def section_pairs(cls, text): diff --git a/Lib/pdb.py b/Lib/pdb.py index 01451f0229cacb..02ce4eca92ac83 100644 --- a/Lib/pdb.py +++ b/Lib/pdb.py @@ -3621,12 +3621,11 @@ def _connect( elif version != remote_pdb.protocol_version(): target_ver = f"0x{remote_pdb.protocol_version():08X}" attach_ver = f"0x{version:08X}" - remote_pdb.error( - f"The target process is running a Python version that is" - f" incompatible with this PDB module." - f"\nTarget process pdb protocol version: {target_ver}" - f"\nLocal pdb module's protocol version: {attach_ver}" - ) + remote_pdb.error(df""" + The target process is running a Python version that is\ + incompatible with this PDB module. + Target process pdb protocol version: {target_ver} + Local pdb module's protocol version: {attach_ver}""") else: remote_pdb.set_trace(frame=frame, commands=commands.splitlines()) @@ -3647,20 +3646,18 @@ def attach(pid, commands=()): colorize = _colorize.can_colorize() connect_script.write( - textwrap.dedent( - f""" - import pdb, sys - pdb._connect( - host="localhost", - port={port}, - frame=sys._getframe(1), - commands={json.dumps("\n".join(commands))}, - version={_PdbServer.protocol_version()}, - signal_raising_thread={use_signal_thread!r}, - colorize={colorize!r}, - ) - """ + fd""" + import pdb, sys + pdb._connect( + host="localhost", + port={port}, + frame=sys._getframe(1), + commands={json.dumps("\n".join(commands))}, + version={_PdbServer.protocol_version()}, + signal_raising_thread={use_signal_thread!r}, + colorize={colorize!r}, ) + """ ) connect_script.close() orig_mode = os.stat(connect_script.name).st_mode diff --git a/Lib/pydoc.py b/Lib/pydoc.py index 041ee26c791f36..3d3f16cc363b3e 100644 --- a/Lib/pydoc.py +++ b/Lib/pydoc.py @@ -1803,7 +1803,7 @@ def _introdoc(): F1: enter interactive help, F2: enter history browsing mode, F3: enter paste mode (press again to exit). ''' - return textwrap.dedent(f'''\ + return fd''' Welcome to Python {ver}'s help utility! If this is your first time using Python, you should definitely check out the tutorial at https://docs.python.org/{ver}/tutorial/. @@ -1819,7 +1819,7 @@ def _introdoc(): To quit this help utility and return to the interpreter, enter "q", "quit" or "exit". - ''') + ''' class Helper: diff --git a/Lib/test/_test_multiprocessing.py b/Lib/test/_test_multiprocessing.py index 115a187a8a8588..d82a50eb5556b5 100644 --- a/Lib/test/_test_multiprocessing.py +++ b/Lib/test/_test_multiprocessing.py @@ -6453,7 +6453,7 @@ def test_resource_tracker_mp_fork_reuse_and_prompt_reap(self): # tracker (the at-fork handler preserves the inherited pipe fd), # *and* the parent should be able to reap the tracker promptly # after joining the child, without hitting the waitpid timeout. - cmd = textwrap.dedent(''' + cmd = d''' import multiprocessing as mp from multiprocessing.resource_tracker import _resource_tracker @@ -6485,7 +6485,7 @@ def child(conn): print(child_has_fd, child_pid_none, child_alive, _resource_tracker._waitpid_timed_out, _resource_tracker._exitcode) - ''') + ''' rc, out, err = script_helper.assert_python_ok('-c', cmd) parts = out.decode().split() self.assertEqual(parts, ['True', 'True', 'True', 'False', '0'], @@ -6497,7 +6497,7 @@ def test_resource_tracker_raw_fork_prompt_reap(self): # child's inherited fd, so the parent can reap the tracker # immediately -- even while the child is still alive -- rather # than waiting out the 1s timeout. - cmd = textwrap.dedent(''' + cmd = d''' import os, signal from multiprocessing.resource_tracker import _resource_tracker @@ -6524,7 +6524,7 @@ def test_resource_tracker_raw_fork_prompt_reap(self): print(child_fd_closed, _resource_tracker._waitpid_timed_out, _resource_tracker._exitcode) - ''') + ''' rc, out, err = script_helper.assert_python_ok('-c', cmd) parts = out.decode().split() self.assertEqual(parts, ['True', 'False', '0'], @@ -6535,7 +6535,7 @@ def test_resource_tracker_lock_reinit_after_fork(self): # gh-146313: If a parent thread held the tracker's lock at fork # time, the child would inherit the held lock and deadlock on # its next ensure_running(). The at-fork handler reinits it. - cmd = textwrap.dedent(''' + cmd = d''' import os, threading from multiprocessing.resource_tracker import _resource_tracker @@ -6558,7 +6558,7 @@ def hold(): t.join() _, status = os.waitpid(pid, 0) print(os.waitstatus_to_exitcode(status)) - ''') + ''' rc, out, err = script_helper.assert_python_ok( '-W', 'ignore::DeprecationWarning', '-c', cmd) self.assertEqual(out.strip(), b'0', @@ -6570,7 +6570,7 @@ def test_resource_tracker_safety_net_timeout(self): # fd and the parent calls _stop() without joining (simulating # abnormal shutdown), the safety-net timeout should fire rather # than deadlocking. - cmd = textwrap.dedent(''' + cmd = d''' import multiprocessing as mp import signal from multiprocessing.resource_tracker import _resource_tracker @@ -6585,7 +6585,7 @@ def test_resource_tracker_safety_net_timeout(self): print(_resource_tracker._waitpid_timed_out) p.terminate() p.join() - ''') + ''' rc, out, err = script_helper.assert_python_ok('-c', cmd) self.assertEqual(out.strip(), b'True', f"safety-net timeout did not fire: stderr={err!r}") @@ -7146,7 +7146,7 @@ def test_global_named_resource_spawn(self): testfn = os_helper.TESTFN self.addCleanup(os_helper.unlink, testfn) with open(testfn, 'w', encoding='utf-8') as f: - f.write(textwrap.dedent('''\ + f.write(d''' import multiprocessing as mp ctx = mp.get_context('spawn') global_resource = ctx.Semaphore() @@ -7155,7 +7155,7 @@ def submain(): pass p = ctx.Process(target=submain) p.start() p.join() - ''')) + ''') rc, out, err = script_helper.assert_python_ok(testfn) # on error, err = 'UserWarning: resource_tracker: There appear to # be 1 leaked semaphore objects to clean up at shutdown' @@ -7301,13 +7301,13 @@ def test_large_pool(self): testfn = os_helper.TESTFN self.addCleanup(os_helper.unlink, testfn) with open(testfn, 'w', encoding='utf-8') as f: - f.write(textwrap.dedent('''\ + f.write(d''' import multiprocessing def f(x): return x*x if __name__ == '__main__': with multiprocessing.Pool(200) as p: print(sum(p.map(f, range(1000)))) - ''')) + ''') rc, out, err = script_helper.assert_python_ok(testfn) self.assertEqual("332833500", out.decode('utf-8').strip()) self.assertFalse(err, msg=err.decode('utf-8')) @@ -7638,7 +7638,7 @@ class SemLock(_multiprocessing.SemLock): class ForkInThreads(unittest.TestCase): def test_fork(self): - code = """ + code = d""" import os, sys, threading, time t = threading.Thread(target=time.sleep, args=(1,), daemon=True) @@ -7666,7 +7666,7 @@ def test_fork(self): self.assertIn(b'is multi-threaded, use of fork() may lead to deadlocks in the child', res.err) def test_forkpty(self): - code = """ + code = d""" import os, sys, threading, time t = threading.Thread(target=time.sleep, args=(1,), daemon=True) @@ -7698,7 +7698,7 @@ class TestSharedMemoryNames(unittest.TestCase): def test_that_shared_memory_name_with_colons_has_no_resource_tracker_errors( self, use_simple_format): # Test script that creates and cleans up shared memory with colon in name - test_script = textwrap.dedent(""" + test_script = d""" import sys from multiprocessing import shared_memory from multiprocessing import resource_tracker @@ -7733,7 +7733,7 @@ def test_that_shared_memory_name_with_colons_has_no_resource_tracker_errors( sys.exit(1) print("SUCCESS") - """ % use_simple_format) + """ % use_simple_format rc, out, err = assert_python_ok("-c", test_script) self.assertIn(b"SUCCESS", out) diff --git a/Lib/test/datetimetester.py b/Lib/test/datetimetester.py index 28c3ab2605c45d..c60765e718b399 100644 --- a/Lib/test/datetimetester.py +++ b/Lib/test/datetimetester.py @@ -12,7 +12,6 @@ import re import struct import sys -import textwrap import unittest import warnings @@ -7400,7 +7399,7 @@ def test_type_check_in_subinterp(self): else: extension_loader = "ExtensionFileLoader" - script = textwrap.dedent(f""" + script = fd""" if {_interpreters is None}: import _testcapi as module module.test_datetime_capi() @@ -7424,7 +7423,7 @@ def run(type_checker, obj): run(module.datetime_check_time, _datetime.time(12, 30)) run(module.datetime_check_delta, _datetime.timedelta(1)) run(module.datetime_check_tzinfo, _datetime.tzinfo()) - """) + """ if _interpreters is None: ret = support.run_in_subinterp(script) self.assertEqual(ret, 0) @@ -7445,7 +7444,7 @@ def setUp(self): @support.cpython_only def test_gh_120161(self): with self.subTest('simple'): - script = textwrap.dedent(""" + script = d""" import datetime from _ast import Tuple f = lambda: None @@ -7453,11 +7452,11 @@ def test_gh_120161(self): class tzutc(datetime.tzinfo): pass - """) + """ script_helper.assert_python_ok('-c', script) with self.subTest('complex'): - script = textwrap.dedent(""" + script = d""" import asyncio import datetime from typing import Type @@ -7474,12 +7473,12 @@ class FakeDate(datetime.date, metaclass=FakeDateMeta): def pickle_fake_date(datetime_) -> Type[FakeDate]: # A pickle function for FakeDate return FakeDate - """) + """ script_helper.assert_python_ok('-c', script) def test_update_type_cache(self): # gh-120782 - script = textwrap.dedent(""" + script = d""" import sys for i in range(5): import _datetime @@ -7506,7 +7505,7 @@ def test_update_type_cache(self): assert isinstance(_datetime.timezone.max, _datetime.tzinfo) assert isinstance(_datetime.timezone.utc, _datetime.tzinfo) del sys.modules['_datetime'] - """) + """ script_helper.assert_python_ok('-c', script) def test_concurrent_initialization_subinterpreter(self): diff --git a/Lib/test/support/import_helper.py b/Lib/test/support/import_helper.py index e8a3d176ad6943..4989038743762d 100644 --- a/Lib/test/support/import_helper.py +++ b/Lib/test/support/import_helper.py @@ -7,7 +7,6 @@ import py_compile import shutil import sys -import textwrap import unittest import warnings @@ -329,8 +328,7 @@ def ensure_lazy_imports(imported_module, modules_to_block, *, additional_code=No """Test that when imported_module is imported, none of the modules in modules_to_block are imported as a side effect.""" modules_to_block = frozenset(modules_to_block) - script = textwrap.dedent( - f""" + script = fd""" import sys modules_to_block = {modules_to_block} if unexpected := modules_to_block & sys.modules.keys(): @@ -342,16 +340,13 @@ def ensure_lazy_imports(imported_module, modules_to_block, *, additional_code=No after = ", ".join(unexpected) raise AssertionError(f'unexpectedly imported after importing {imported_module}: {{after}}') """ - ) if additional_code: - script += additional_code - script += textwrap.dedent( - f""" + script += additional_code + "\n" + script += fd""" if unexpected := modules_to_block & sys.modules.keys(): after = ", ".join(unexpected) raise AssertionError(f'unexpectedly imported after additional code: {{after}}') """ - ) from .script_helper import assert_python_ok assert_python_ok("-S", "-c", script) diff --git a/Lib/test/test_annotationlib.py b/Lib/test/test_annotationlib.py index 5087c3ca425f1f..e7575166bceab7 100644 --- a/Lib/test/test_annotationlib.py +++ b/Lib/test/test_annotationlib.py @@ -1,6 +1,5 @@ """Tests for the annotations module.""" -import textwrap import annotationlib import builtins import collections @@ -1823,14 +1822,14 @@ class CustomAnnotate(metaclass=Meta): def __annotate__(format): return {} - code = """ + code = d""" from __future__ import annotations class HasFutureAnnotations(metaclass=Meta): expected_annotate = False a: int - """ - exec(textwrap.dedent(code), {"Meta": Meta}) + """ + exec(code, {"Meta": Meta}) class TestTypeRepr(unittest.TestCase): diff --git a/Lib/test/test_argparse.py b/Lib/test/test_argparse.py index 1dc3f538f4ad8b..0efe19b784702c 100644 --- a/Lib/test/test_argparse.py +++ b/Lib/test/test_argparse.py @@ -108,12 +108,10 @@ def test_create_parser(self): ) def test_add_subparser(self): - add_subparser = textwrap.dedent( - """ + add_subparser = d""" parser = argparse.ArgumentParser() parser.add_subparsers(dest='command', required=False) """ - ) imported_modules = {"shutil"} import_helper.ensure_lazy_imports( @@ -123,15 +121,13 @@ def test_add_subparser(self): ) def test_parse_args(self): - example_parser = textwrap.dedent( - """ + example_parser = d""" parser = argparse.ArgumentParser(prog='PROG') parser.add_argument('-f', '--foo') parser.add_argument('bar') parser.parse_args(['BAR']) parser.parse_args(['BAR', '--foo', 'FOO']) """ - ) imported_modules = {"shutil"} import_helper.ensure_lazy_imports( "argparse", @@ -2905,7 +2901,7 @@ def test_subparser_help_with_parent_required_optional(self): def test_help(self): self.assertEqual(self.parser.format_usage(), 'usage: PROG [-h] [--foo] bar {1,2,3} ...\n') - self.assertEqual(self.parser.format_help(), textwrap.dedent('''\ + self.assertEqual(self.parser.format_help(), d''' usage: PROG [-h] [--foo] bar {1,2,3} ... main description @@ -2917,14 +2913,14 @@ def test_help(self): options: -h, --help show this help message and exit --foo foo help - ''')) + ''') def test_help_extra_prefix_chars(self): # Make sure - is still used for help if it is a non-first prefix char parser = self._get_parser(prefix_chars='+:-') self.assertEqual(parser.format_usage(), 'usage: PROG [-h] [++foo] bar {1,2,3} ...\n') - self.assertEqual(parser.format_help(), textwrap.dedent('''\ + self.assertEqual(parser.format_help(), d''' usage: PROG [-h] [++foo] bar {1,2,3} ... main description @@ -2936,7 +2932,7 @@ def test_help_extra_prefix_chars(self): options: -h, --help show this help message and exit ++foo foo help - ''')) + ''') def test_help_non_breaking_spaces(self): parser = ErrorRaisingArgumentParser( @@ -2945,7 +2941,7 @@ def test_help_non_breaking_spaces(self): "--non-breaking", action='store_false', help='help message containing non-breaking spaces shall not ' 'wrap\N{NO-BREAK SPACE}at non-breaking spaces') - self.assertEqual(parser.format_help(), textwrap.dedent('''\ + self.assertEqual(parser.format_help(), d''' usage: PROG [-h] [--non-breaking] main description @@ -2954,7 +2950,7 @@ def test_help_non_breaking_spaces(self): -h, --help show this help message and exit --non-breaking help message containing non-breaking spaces shall not wrap\N{NO-BREAK SPACE}at non-breaking spaces - ''')) + ''') def test_help_blank(self): # Issue 24444 @@ -2963,7 +2959,7 @@ def test_help_blank(self): parser.add_argument( 'foo', help=' ') - self.assertEqual(parser.format_help(), textwrap.dedent('''\ + self.assertEqual(parser.format_help(), d''' usage: PROG [-h] foo main description @@ -2972,14 +2968,14 @@ def test_help_blank(self): foo \n options: -h, --help show this help message and exit - ''')) + ''') parser = ErrorRaisingArgumentParser( prog='PROG', description='main description') parser.add_argument( 'foo', choices=[], help='%(choices)s') - self.assertEqual(parser.format_help(), textwrap.dedent('''\ + self.assertEqual(parser.format_help(), d''' usage: PROG [-h] {} main description @@ -2988,13 +2984,13 @@ def test_help_blank(self): {} \n options: -h, --help show this help message and exit - ''')) + ''') def test_help_alternate_prefix_chars(self): parser = self._get_parser(prefix_chars='+:/') self.assertEqual(parser.format_usage(), 'usage: PROG [+h] [++foo] bar {1,2,3} ...\n') - self.assertEqual(parser.format_help(), textwrap.dedent('''\ + self.assertEqual(parser.format_help(), d''' usage: PROG [+h] [++foo] bar {1,2,3} ... main description @@ -3006,13 +3002,13 @@ def test_help_alternate_prefix_chars(self): options: +h, ++help show this help message and exit ++foo foo help - ''')) + ''') def test_parser_command_help(self): self.assertEqual(self.command_help_parser.format_usage(), 'usage: PROG [-h] [--foo] bar {1,2,3} ...\n') self.assertEqual(self.command_help_parser.format_help(), - textwrap.dedent('''\ + d''' usage: PROG [-h] [--foo] bar {1,2,3} ... main description @@ -3027,7 +3023,7 @@ def test_parser_command_help(self): options: -h, --help show this help message and exit --foo foo help - ''')) + ''') def assert_bad_help(self, context_type, func, *args, **kwargs): with self.assertRaisesRegex(ValueError, 'badly formed help string') as cm: @@ -3064,7 +3060,7 @@ def test_subparser_title_help(self): parser2 = subparsers.add_parser('2') self.assertEqual(parser.format_usage(), 'usage: PROG [-h] [--foo] bar {1,2} ...\n') - self.assertEqual(parser.format_help(), textwrap.dedent('''\ + self.assertEqual(parser.format_help(), d''' usage: PROG [-h] [--foo] bar {1,2} ... main description @@ -3080,7 +3076,7 @@ def test_subparser_title_help(self): command help {1,2} additional text - ''')) + ''') def _test_subparser_help(self, args_str, expected_help): with self.assertRaises(ArgumentParserError) as cm: @@ -3088,7 +3084,7 @@ def _test_subparser_help(self, args_str, expected_help): self.assertEqual(expected_help, cm.exception.stdout) def test_subparser1_help(self): - self._test_subparser_help('5.0 1 -h', textwrap.dedent('''\ + self._test_subparser_help('5.0 1 -h', d''' usage: PROG bar 1 [-h] [-w W] {a,b,c} 1 description @@ -3099,10 +3095,10 @@ def test_subparser1_help(self): options: -h, --help show this help message and exit -w W w help - ''')) + ''') def test_subparser2_help(self): - self._test_subparser_help('5.0 2 -h', textwrap.dedent('''\ + self._test_subparser_help('5.0 2 -h', d''' usage: PROG bar 2 [-h] [-y {1,2,3}] [z ...] 2 description @@ -3113,7 +3109,7 @@ def test_subparser2_help(self): options: -h, --help show this help message and exit -y {1,2,3} y help - ''')) + ''') def test_alias_invocation(self): parser = self._get_parser(aliases=True) @@ -3134,7 +3130,7 @@ def test_error_alias_invocation(self): def test_alias_help(self): parser = self._get_parser(aliases=True, subparser_help=True) self.maxDiff = None - self.assertEqual(parser.format_help(), textwrap.dedent("""\ + self.assertEqual(parser.format_help(), d""" usage: PROG [-h] [--foo] bar COMMAND ... main description @@ -3152,7 +3148,7 @@ def test_alias_help(self): 1 help 2 2 help 3 3 help - """)) + """) # ============ # Groups tests @@ -3353,7 +3349,7 @@ def test_parent_help(self): parents = [self.abcd_parent, self.wxyz_parent] parser = ErrorRaisingArgumentParser(prog='PROG', parents=parents) parser_help = parser.format_help() - self.assertEqual(parser_help, textwrap.dedent('''\ + self.assertEqual(parser_help, d''' usage: PROG [-h] [-b B] [--d D] [--w W] [-y Y] a z positional arguments: @@ -3370,7 +3366,7 @@ def test_parent_help(self): x: -y Y - ''')) + ''') def test_groups_parents(self): parent = ErrorRaisingArgumentParser(add_help=False) @@ -3386,7 +3382,7 @@ def test_groups_parents(self): ['-y', 'Y', '-z', 'Z']) parser_help = parser.format_help() - self.assertEqual(parser_help, textwrap.dedent('''\ + self.assertEqual(parser_help, d''' usage: PROG [-h] [-w W] [-x X] [-y Y | -z Z] options: @@ -3399,7 +3395,7 @@ def test_groups_parents(self): -w W -x X - ''')) + ''') def test_wrong_type_parents(self): self.assertRaises(TypeError, ErrorRaisingArgumentParser, parents=[1]) @@ -3418,7 +3414,7 @@ def test_mutex_groups_parents(self): ['-y', 'Y', '-z', 'Z']) parser_help = parser.format_help() - self.assertEqual(parser_help, textwrap.dedent('''\ + self.assertEqual(parser_help, d''' usage: PROG [-h] [-w W] [-x X] [-y Y | -z Z] options: @@ -3431,7 +3427,7 @@ def test_mutex_groups_parents(self): -x X -y Y -z Z - ''')) + ''') # ============================== # Mutually exclusive group tests @@ -5036,10 +5032,10 @@ def test_all_suppressed_mutex_followed_by_long_arg(self): mutex = parser.add_mutually_exclusive_group() mutex.add_argument('--spam', help=argparse.SUPPRESS) parser.add_argument('--eggs-eggs-eggs-eggs-eggs-eggs') - usage = textwrap.dedent('''\ + usage = d''' usage: PROG [-h] [--eggs-eggs-eggs-eggs-eggs-eggs EGGS_EGGS_EGGS_EGGS_EGGS_EGGS] - ''') + ''' self.assertEqual(parser.format_usage(), usage) def test_newline_in_metavar(self): @@ -5052,7 +5048,7 @@ def test_newline_in_metavar(self): help='installation targets', nargs='+', metavar='\n'.join(mapping)) - usage = textwrap.dedent('''\ + usage = d''' usage: 11111111111111 [-h] [-v] 123456 12345 @@ -5061,7 +5057,7 @@ def test_newline_in_metavar(self): 12345 12345 123 ...] - ''') + ''' self.assertEqual(parser.format_usage(), usage) def test_empty_metavar_required_arg(self): @@ -5100,11 +5096,11 @@ def test_long_mutex_groups_wrap(self): g.add_argument('--op6', nargs=3) g.add_argument('--op7', metavar=('MET1', 'MET2', 'MET3'), nargs=3) - usage = textwrap.dedent('''\ + usage = d''' usage: PROG [-h] [--op1 [MET] | --op2 [MET1 [MET2 ...]] | --op3 [OP3 ...] | --op4 MET1 [MET2 ...] | --op5 OP5 [OP5 ...] | --op6 OP6 OP6 OP6 | --op7 MET1 MET2 MET3] - ''') + ''' self.assertEqual(parser.format_usage(), usage) def test_mutex_groups_with_mixed_optionals_positionals_wrap(self): @@ -5119,11 +5115,11 @@ def test_mutex_groups_with_mixed_optionals_positionals_wrap(self): g.add_argument('-y', '--yet-another-long-option', nargs='?') g.add_argument('positional', nargs='?') - usage = textwrap.dedent('''\ + usage = d''' usage: PROG [-h] [-v | -q | -x [EXTRA_LONG_OPTION_NAME] | -y [YET_ANOTHER_LONG_OPTION] | positional] - ''') + ''' self.assertEqual(parser.format_usage(), usage) @@ -5746,7 +5742,7 @@ def custom_formatter(prog): parser.add_argument('spam', help="spam help") parser_help = parser.format_help() - self.assertEqual(parser_help, textwrap.dedent('''\ + self.assertEqual(parser_help, d''' usage: PROG [-h] [+f FOO] spam positional arguments: @@ -5755,7 +5751,7 @@ def custom_formatter(prog): options: -h, --help show this help message and exit +f, ++foo FOO foo help - ''')) + ''') def test_custom_formatter_class(self): class CustomFormatter(argparse.RawTextHelpFormatter): @@ -5771,7 +5767,7 @@ def __init__(self, prog): parser.add_argument('spam', help="spam help") parser_help = parser.format_help() - self.assertEqual(parser_help, textwrap.dedent('''\ + self.assertEqual(parser_help, d''' usage: PROG [-h] [+f FOO] spam positional arguments: @@ -5780,7 +5776,7 @@ def __init__(self, prog): options: -h, --help show this help message and exit +f, ++foo FOO foo help - ''')) + ''') def test_usage_long_subparser_command(self): """Test that subparser commands are formatted correctly in help""" @@ -5805,7 +5801,7 @@ def custom_formatter(prog): help="command that does something") parser_help = parent_parser.format_help() - self.assertEqual(parser_help, textwrap.dedent('''\ + self.assertEqual(parser_help, d''' usage: PROG [-h] CMD ... options: @@ -5816,7 +5812,7 @@ def custom_formatter(prog): add add something remove remove something a-very-long-command command that does something - ''')) + ''') def test_direct_formatter_instantiation(self): formatter = argparse.HelpFormatter(prog="program") @@ -6040,24 +6036,24 @@ def test_resolve_error(self): parser.add_argument('-x', help='OLD X') parser.add_argument('-x', help='NEW X') - self.assertEqual(parser.format_help(), textwrap.dedent('''\ + self.assertEqual(parser.format_help(), d''' usage: PROG [-h] [-x X] options: -h, --help show this help message and exit -x X NEW X - ''')) + ''') parser.add_argument('--spam', metavar='OLD_SPAM') parser.add_argument('--spam', metavar='NEW_SPAM') - self.assertEqual(parser.format_help(), textwrap.dedent('''\ + self.assertEqual(parser.format_help(), d''' usage: PROG [-h] [-x X] [--spam NEW_SPAM] options: -h, --help show this help message and exit -x X NEW X --spam NEW_SPAM - ''')) + ''') def test_subparser_conflict(self): parser = argparse.ArgumentParser() @@ -7118,14 +7114,14 @@ def setUp(self): @force_not_colorized def test_help_with_metavar(self): help_text = self.parser.format_help() - self.assertEqual(help_text, textwrap.dedent('''\ + self.assertEqual(help_text, d''' usage: this_is_spammy_prog_with_a_long_name_sorry_about_the_name [-h] [--proxy ] options: -h, --help show this help message and exit --proxy - ''')) + ''') class TestExitOnError(TestCase): @@ -7283,11 +7279,11 @@ def test_os_error(self): @force_not_colorized_test_class class TestProgName(TestCase): - source = textwrap.dedent('''\ + source = d''' import argparse parser = argparse.ArgumentParser() parser.parse_args() - ''') + ''' def setUp(self): self.dirname = 'package' + os_helper.FS_NONASCII @@ -7485,8 +7481,7 @@ def test_argparse_color(self): # Assert self.assertEqual( help_text, - textwrap.dedent( - f"""\ + fd""" {heading}usage: {reset}{prog}PROG{reset} [{short}-h{reset}] [{short}-v{reset} | {short}-q{reset}] [{short}-o{reset}] [{long}--optional2 {label}OPTIONAL2{reset}] [{long}--optional3 {label}{{X,Y,Z}}{reset}] [{long}--optional4 {label}{{X,Y,Z}}{reset}] [{long}--optional5 {label}{{X,Y,Z}}{reset}] [{long}--optional6 {label}{{X,Y,Z}}{reset}] [{short}-p {label}{{Aaaaa,Bbbbb,Ccccc,Ddddd}}{reset}] [{long}--optional8 {label}X{reset}] [{short}+f {label}F{reset}] [{long}++bar {label}BAR{reset}] @@ -7526,8 +7521,7 @@ def test_argparse_color(self): {pos_b}{{sub1,sub2}}{reset} additional help {pos_b}sub1{reset} sub1 help {pos_b}sub2{reset} sub2 help - """ - ), + """, ) def test_argparse_color_mutually_exclusive_group_usage(self): @@ -7571,13 +7565,11 @@ def test_argparse_color_custom_usage(self): # Assert self.assertEqual( help_text, - textwrap.dedent( - f"""\ - {heading}usage: {reset}{usage}[prefix] {prog}PROG{reset}{usage} [suffix]{reset} + fd""" + {heading}usage: {reset}{usage}[prefix] {prog}PROG{reset}{usage} [suffix]{reset} - Test prog and usage colors - """ - ), + Test prog and usage colors + """, ) def test_custom_formatter_function(self): @@ -7605,7 +7597,7 @@ def custom_formatter(prog): reset = self.theme.reset parser_help = parser.format_help() - self.assertEqual(parser_help, textwrap.dedent(f'''\ + self.assertEqual(parser_help, fd''' {heading}usage: {reset}{prog}PROG{reset} [{short}-h{reset}] [{short}+f {label}FOO{reset}] {pos}spam{reset} {heading}positional arguments:{reset} @@ -7614,7 +7606,7 @@ def custom_formatter(prog): {heading}options:{reset} {short_b}-h{reset}, {long_b}--help{reset} show this help message and exit {short_b}+f{reset}, {long_b}++foo{reset} {label_b}FOO{reset} foo help - ''')) + ''') def test_custom_formatter_class(self): class CustomFormatter(argparse.RawTextHelpFormatter): @@ -7642,7 +7634,7 @@ def __init__(self, prog): reset = self.theme.reset parser_help = parser.format_help() - self.assertEqual(parser_help, textwrap.dedent(f'''\ + self.assertEqual(parser_help, fd''' {heading}usage: {reset}{prog}PROG{reset} [{short}-h{reset}] [{short}+f {label}FOO{reset}] {pos}spam{reset} {heading}positional arguments:{reset} @@ -7651,7 +7643,7 @@ def __init__(self, prog): {heading}options:{reset} {short_b}-h{reset}, {long_b}--help{reset} show this help message and exit {short_b}+f{reset}, {long_b}++foo{reset} {label_b}FOO{reset} foo help - ''')) + ''') def test_subparser_prog_is_stored_without_color(self): parser = argparse.ArgumentParser(prog='complex', color=True) diff --git a/Lib/test/test_ast/test_ast.py b/Lib/test/test_ast/test_ast.py index fd3b33bab7f833..648acc65852015 100644 --- a/Lib/test/test_ast/test_ast.py +++ b/Lib/test/test_ast/test_ast.py @@ -232,34 +232,34 @@ def test_negative_locations_for_compile(self): def test_docstring_optimization_single_node(self): # https://github.com/python/cpython/issues/137308 - class_example1 = textwrap.dedent(''' + class_example1 = d''' class A: """Docstring""" - ''') - class_example2 = textwrap.dedent(''' + ''' + class_example2 = d''' class A: """ Docstring""" - ''') - def_example1 = textwrap.dedent(''' + ''' + def_example1 = d''' def some(): """Docstring""" - ''') - def_example2 = textwrap.dedent(''' + ''' + def_example2 = d''' def some(): """Docstring """ - ''') - async_def_example1 = textwrap.dedent(''' + ''' + async_def_example1 = d''' async def some(): """Docstring""" - ''') - async_def_example2 = textwrap.dedent(''' + ''' + async_def_example2 = d''' async def some(): """ Docstring """ - ''') + ''' for code in [ class_example1, class_example2, @@ -278,9 +278,9 @@ async def some(): self.assertEqual( vars(pass_stmt), { - 'lineno': 3, + 'lineno': 2, 'col_offset': 4, - 'end_lineno': 3, + 'end_lineno': 2, 'end_col_offset': 8, }, ) @@ -298,18 +298,15 @@ async def some(): def test_docstring_optimization_multiple_nodes(self): # https://github.com/python/cpython/issues/137308 - class_example = textwrap.dedent( - """ + class_example = d""" class A: ''' Docstring ''' x = 1 """ - ) - def_example = textwrap.dedent( - """ + def_example = d""" def some(): ''' Docstring @@ -317,10 +314,8 @@ def some(): ''' x = 1 """ - ) - async_def_example = textwrap.dedent( - """ + async_def_example = d""" async def some(): '''Docstring @@ -328,7 +323,6 @@ async def some(): ''' x = 1 """ - ) for code in [ class_example, @@ -853,58 +847,58 @@ def test_pep750_tstring(self): ast.parse(code, feature_version=(3, 13)) def test_pep758_except_without_parens(self): - code = textwrap.dedent(""" + code = d""" try: ... except ValueError, TypeError: ... - """) + """ ast.parse(code, feature_version=(3, 14)) with self.assertRaises(SyntaxError): ast.parse(code, feature_version=(3, 13)) def test_pep758_except_with_single_expr(self): - single_expr = textwrap.dedent(""" + single_expr = d""" try: ... except{0} TypeError: ... - """) + """ - single_expr_with_as = textwrap.dedent(""" + single_expr_with_as = d""" try: ... except{0} TypeError as exc: ... - """) + """ - single_tuple_expr = textwrap.dedent(""" + single_tuple_expr = d""" try: ... except{0} (TypeError,): ... - """) + """ - single_tuple_expr_with_as = textwrap.dedent(""" + single_tuple_expr_with_as = d""" try: ... except{0} (TypeError,) as exc: ... - """) + """ - single_parens_expr = textwrap.dedent(""" + single_parens_expr = d""" try: ... except{0} (TypeError): ... - """) + """ - single_parens_expr_with_as = textwrap.dedent(""" + single_parens_expr_with_as = d""" try: ... except{0} (TypeError) as exc: ... - """) + """ for code in [ single_expr, @@ -921,12 +915,12 @@ def test_pep758_except_with_single_expr(self): ast.parse(code, feature_version=(3, 13)) def test_pep758_except_star_without_parens(self): - code = textwrap.dedent(""" + code = d""" try: ... except* ValueError, TypeError: ... - """) + """ ast.parse(code, feature_version=(3, 14)) with self.assertRaises(SyntaxError): ast.parse(code, feature_version=(3, 13)) @@ -1227,7 +1221,7 @@ def test_pickling(self): @skip_if_unlimited_stack_size def test_copy_with_parents(self): # gh-120108 - code = """ + code = d""" ('',) while i < n: if ch == '': @@ -2197,11 +2191,11 @@ def matcher(node): case _: return False - code = """ + code = d""" @capybara def foo(bar) -> pacarana: pass - """ + """ source = ast.parse(textwrap.dedent(code)) funcdef = source.body[0] self.assertIsInstance(funcdef, ast.FunctionDef) @@ -3201,12 +3195,12 @@ def visit_Name(self, node: ast.Name): self.assertASTTransformation(SomeTypeRemover, code, expected) def test_node_remove_from_list(self): - code = """ + code = d""" def func(arg): print(arg) yield arg """ - expected = """ + expected = d""" def func(arg): print(arg) """ @@ -3223,10 +3217,10 @@ def visit_Expr(self, node: ast.Expr): self.assertASTTransformation(YieldRemover, code, expected) def test_node_return_list(self): - code = """ + code = d""" class DSL(Base, kw1=True): ... """ - expected = """ + expected = d""" class DSL(Base, kw1=True, kw2=True, kw3=False): ... """ @@ -3244,11 +3238,11 @@ def visit_keyword(self, node: ast.keyword): self.assertASTTransformation(ExtendKeywords, code, expected) def test_node_mutate(self): - code = """ + code = d""" def func(arg): print(arg) """ - expected = """ + expected = d""" def func(arg): log(arg) """ @@ -3263,11 +3257,11 @@ def visit_Call(self, node: ast.Call): self.assertASTTransformation(PrintToLog, code, expected) def test_node_replace(self): - code = """ + code = d""" def func(arg): print(arg) """ - expected = """ + expected = d""" def func(arg): logger.log(arg, debug=True) """ @@ -3683,11 +3677,11 @@ def test_indent_flag(self): def test_feature_version_flag(self): # test 'python -m ast --feature-version 3.9/3.10' - source = ''' + source = d''' match x: case 1: pass - ''' + ''' expect = ''' Module( body=[ @@ -3706,11 +3700,11 @@ def test_feature_version_flag(self): def test_no_optimize_flag(self): # test 'python -m ast -O/--optimize -1/0' - source = ''' + source = d''' match a: case 1+2j: pass - ''' + ''' expect = ''' Module( body=[ @@ -3732,11 +3726,11 @@ def test_no_optimize_flag(self): def test_optimize_flag(self): # test 'python -m ast -O/--optimize 1/2' - source = ''' + source = d''' match a: case 1+2j: pass - ''' + ''' expect = ''' Module( body=[ @@ -3885,11 +3879,11 @@ def get_match_case_values(node): self.assertListEqual(constants, values) def test_match_case_not_folded_in_unoptimized_ast(self): - src = textwrap.dedent(""" + src = d""" match a: case 1+2j: pass - """) + """ unfolded = "MatchValue(value=BinOp(left=Constant(value=1), op=Add(), right=Constant(value=2j))" folded = "MatchValue(value=Constant(value=(1+2j)))" diff --git a/Lib/test/test_asyncio/test_subprocess.py b/Lib/test/test_asyncio/test_subprocess.py index 4ac6b23b7120fc..dc3ab0c8edf66b 100644 --- a/Lib/test/test_asyncio/test_subprocess.py +++ b/Lib/test/test_asyncio/test_subprocess.py @@ -2,7 +2,6 @@ import shlex import signal import sys -import textwrap import unittest import warnings from unittest import mock @@ -319,12 +318,12 @@ def test_stdin_broken_pipe(self): if support.MS_WINDOWS: handle = msvcrt.get_osfhandle(rfd) os.set_handle_inheritable(handle, True) - code = textwrap.dedent(f''' + code = fd''' import os, msvcrt handle = {handle} fd = msvcrt.open_osfhandle(handle, os.O_RDONLY) os.read(fd, 1) - ''') + ''' from subprocess import STARTUPINFO startupinfo = STARTUPINFO() startupinfo.lpAttributeList = {"handle_list": [handle]} diff --git a/Lib/test/test_atexit.py b/Lib/test/test_atexit.py index 8256ff183f28c9..98bad8df641dde 100644 --- a/Lib/test/test_atexit.py +++ b/Lib/test/test_atexit.py @@ -17,7 +17,7 @@ def test_general(self): class FunctionalTest(unittest.TestCase): def test_shutdown(self): # Actually test the shutdown mechanism in a subprocess - code = textwrap.dedent(""" + code = d""" import atexit def f(msg): @@ -25,14 +25,14 @@ def f(msg): atexit.register(f, "one") atexit.register(f, "two") - """) + """ res = script_helper.assert_python_ok("-c", code) self.assertEqual(res.out.decode().splitlines(), ["two", "one"]) self.assertFalse(res.err) def test_atexit_instances(self): # bpo-42639: It is safe to have more than one atexit instance. - code = textwrap.dedent(""" + code = d""" import sys import atexit as atexit1 del sys.modules['atexit'] @@ -43,7 +43,7 @@ def test_atexit_instances(self): atexit1.register(print, "atexit1") atexit2.register(print, "atexit2") - """) + """ res = script_helper.assert_python_ok("-c", code) self.assertEqual(res.out.decode().splitlines(), ["atexit2", "atexit1"]) self.assertFalse(res.err) @@ -53,7 +53,7 @@ def test_atexit_instances(self): @unittest.skipUnless(support.Py_GIL_DISABLED, "only meaningful without the GIL") def test_atexit_thread_safety(self): # GH-126907: atexit was not thread safe on the free-threaded build - source = """ + source = d""" from threading import Thread def dummy(): @@ -146,13 +146,13 @@ def test_callbacks_leak(self): # take care to free callbacks in its per-subinterpreter module # state. n = atexit._ncallbacks() - code = textwrap.dedent(r""" + code = rd""" import atexit def f(): pass atexit.register(f) del atexit - """) + """ ret = support.run_in_subinterp(code) self.assertEqual(ret, 0) self.assertEqual(atexit._ncallbacks(), n) @@ -161,13 +161,13 @@ def test_callbacks_leak_refcycle(self): # Similar to the above, but with a refcycle through the atexit # module. n = atexit._ncallbacks() - code = textwrap.dedent(r""" + code = rd""" import atexit def f(): pass atexit.register(f) atexit.__atexit = atexit - """) + """ ret = support.run_in_subinterp(code) self.assertEqual(ret, 0) self.assertEqual(atexit._ncallbacks(), n) @@ -197,7 +197,7 @@ def callback(): def test_atexit_with_low_memory(self): # gh-140080: Test that setting low memory after registering an atexit # callback doesn't cause an infinite loop during finalization. - code = textwrap.dedent(""" + code = d""" import atexit import _testcapi @@ -207,7 +207,7 @@ def callback(): atexit.register(callback) # Simulate low memory condition _testcapi.set_nomemory(0) - """) + """ with os_helper.temp_dir() as temp_dir: script = script_helper.make_script(temp_dir, 'test_atexit_script', code) diff --git a/Lib/test/test_capi/test_exceptions.py b/Lib/test/test_capi/test_exceptions.py index 51ac41e33ac17a..a96fc029185449 100644 --- a/Lib/test/test_capi/test_exceptions.py +++ b/Lib/test/test_capi/test_exceptions.py @@ -3,7 +3,6 @@ import re import sys import unittest -import textwrap from test import support from test.support import import_helper, force_not_colorized @@ -71,7 +70,7 @@ def test_exc_info(self): self.assertTrue(False) def test_warn_with_stacklevel(self): - code = textwrap.dedent('''\ + code = d''' import _testcapi def foo(): @@ -81,7 +80,7 @@ def foo(): foo() # line 9 - ''') + ''' proc = assert_python_ok("-c", code) warnings = proc.err.splitlines() self.assertEqual(warnings, [ @@ -90,7 +89,7 @@ def foo(): ]) def test_warn_during_finalization(self): - code = textwrap.dedent('''\ + code = d''' import _testcapi class Foo: @@ -100,7 +99,7 @@ def __del__(self): self.foo() ref = Foo() - ''') + ''' proc = assert_python_ok("-c", code) warnings = proc.err.splitlines() # Due to the finalization of the interpreter, the source will be omitted diff --git a/Lib/test/test_capi/test_mem.py b/Lib/test/test_capi/test_mem.py index 5035b2b4829bf6..3363b7fa284722 100644 --- a/Lib/test/test_capi/test_mem.py +++ b/Lib/test/test_capi/test_mem.py @@ -1,5 +1,4 @@ import re -import textwrap import unittest @@ -90,7 +89,7 @@ def test_pyobject_malloc_without_gil(self): self.check_malloc_without_gil(code) def check_pyobject_is_freed(self, func_name): - code = textwrap.dedent(f''' + code = fd''' import gc, os, sys, _testinternalcapi # Disable the GC to avoid crash on GC collection gc.disable() @@ -98,7 +97,7 @@ def check_pyobject_is_freed(self, func_name): # Exit immediately to avoid a crash while deallocating # the invalid object os._exit(0) - ''') + ''' assert_python_ok( '-c', code, PYTHONMALLOC=self.PYTHONMALLOC, diff --git a/Lib/test/test_capi/test_misc.py b/Lib/test/test_capi/test_misc.py index 6d84f0b8c305df..781702f35bdc96 100644 --- a/Lib/test/test_capi/test_misc.py +++ b/Lib/test/test_capi/test_misc.py @@ -96,13 +96,13 @@ def test_instancemethod(self): @support.requires_subprocess() def test_no_FatalError_infinite_loop(self): - code = textwrap.dedent(""" + code = d""" import _testcapi from test import support with support.SuppressCrashReport(): _testcapi.crash_no_current_thread() - """) + """ run_result, _cmd_line = run_python_until_end('-c', code) _rc, out, err = run_result @@ -224,13 +224,13 @@ def test_return_null_without_error(self): # Issue #23571: A function must not return NULL without setting an # error if support.Py_DEBUG: - code = textwrap.dedent(""" + code = d""" import _testcapi from test import support with support.SuppressCrashReport(): _testcapi.return_null_without_error() - """) + """ rc, out, err = assert_python_failure('-c', code) err = decode_stderr(err) self.assertRegex(err, @@ -241,7 +241,7 @@ def test_return_null_without_error(self): r'returned NULL without setting an exception\n' r'\n' + CURRENT_THREAD_REGEX + - r' File .*", line 6 in \n') + r' File .*", line 5 in \n') else: with self.assertRaises(SystemError) as cm: _testcapi.return_null_without_error() @@ -252,13 +252,13 @@ def test_return_null_without_error(self): def test_return_result_with_error(self): # Issue #23571: A function must not return a result with an error set if support.Py_DEBUG: - code = textwrap.dedent(""" + code = d""" import _testcapi from test import support with support.SuppressCrashReport(): _testcapi.return_result_with_error() - """) + """ rc, out, err = assert_python_failure('-c', code) err = decode_stderr(err) self.assertRegex(err, @@ -275,7 +275,7 @@ def test_return_result_with_error(self): r'returned a result with an exception set\n' r'\n' + CURRENT_THREAD_REGEX + - r' File .*, line 6 in \n') + r' File .*, line 5 in \n') else: with self.assertRaises(SystemError) as cm: _testcapi.return_result_with_error() @@ -287,13 +287,13 @@ def test_getitem_with_error(self): # Test _Py_CheckSlotResult(). Raise an exception and then calls # PyObject_GetItem(): check that the assertion catches the bug. # PyObject_GetItem() must not be called with an exception set. - code = textwrap.dedent(""" + code = d""" import _testcapi from test import support with support.SuppressCrashReport(): _testcapi.getitem_with_error({1: 2}, 1) - """) + """ rc, out, err = assert_python_failure('-c', code) err = decode_stderr(err) if 'SystemError: ' not in err: @@ -305,7 +305,7 @@ def test_getitem_with_error(self): r'ValueError: bug\n' r'\n' + CURRENT_THREAD_REGEX + - r' File .*, line 6 in \n' + r' File .*, line 5 in \n' r'\n' r'Extension modules: ') else: @@ -1667,7 +1667,7 @@ def subthread(): @threading_helper.requires_working_threading() def test_pending_call_creates_thread(self): - source = """ + source = d""" import _testinternalcapi import threading import time @@ -1833,12 +1833,12 @@ def test_configured_settings(self): } with self.subTest(config): r, w = os.pipe() - script = textwrap.dedent(f''' + script = fd''' import _testinternalcapi, json, os settings = _testinternalcapi.get_interp_settings() with os.fdopen({w}, "w") as stdin: json.dump(settings, stdin) - ''') + ''' with os.fdopen(r) as stdout: ret = support.run_in_subinterp_with_config(script, **kwargs) self.assertEqual(ret, 0) @@ -1851,11 +1851,11 @@ def test_configured_settings(self): for config in expected_to_fail: kwargs = dict(zip(kwlist, config)) with self.subTest(config): - script = textwrap.dedent(f''' + script = fd''' import _testinternalcapi _testinternalcapi.get_interp_settings() raise NotImplementedError('unreachable') - ''') + ''' with self.assertRaises(_interpreters.InterpreterError): support.run_in_subinterp_with_config(script, **kwargs) @@ -1918,10 +1918,10 @@ def check(enabled, override): if Py_GIL_DISABLED: # gh-117649: The test fails before `w` is closed self.addCleanup(os.close, w) - script = textwrap.dedent(f''' + script = fd''' from test.test_capi.check_config import run_singlephase_check run_singlephase_check({override}, {w}) - ''') + ''' with os.fdopen(r) as stdout: ret = support.run_in_subinterp_with_config(script, **kwargs) self.assertEqual(ret, 0) @@ -1981,7 +1981,7 @@ def test_module_state_shared_in_global(self): else: loader = "ExtensionFileLoader" - script = textwrap.dedent(f""" + script = fd""" import importlib.machinery import importlib.util import os @@ -1994,7 +1994,7 @@ def test_module_state_shared_in_global(self): attr_id = str(id(module.Error)).encode() os.write({w}, attr_id) - """) + """ exec(script) main_attr_id = os.read(r, 100) @@ -2630,14 +2630,14 @@ def callback(): @threading_helper.requires_working_threading() def test_gilstate_ensure_no_deadlock(self): # See https://github.com/python/cpython/issues/96071 - code = textwrap.dedent(""" + code = d""" import _testcapi def callback(): print('callback called') _testcapi._test_thread_state(callback) - """) + """ ret = assert_python_ok('-X', 'tracemalloc', '-c', code) self.assertIn(b'callback called', ret.out) @@ -3064,7 +3064,7 @@ def test_pack_version_ctypes(self): class TestCEval(unittest.TestCase): def test_ceval_decref(self): - code = textwrap.dedent(""" + code = d""" import _testcapi _testcapi.toggle_reftrace_printer(True) l1 = [] @@ -3072,7 +3072,7 @@ def test_ceval_decref(self): del l1 del l2 _testcapi.toggle_reftrace_printer(False) - """) + """ _, out, _ = assert_python_ok("-c", code) lines = out.decode("utf-8").splitlines() self.assertEqual(lines.count("CREATE list"), 2) diff --git a/Lib/test/test_capi/test_object.py b/Lib/test/test_capi/test_object.py index 433afac875aa7b..1b34652589eb6d 100644 --- a/Lib/test/test_capi/test_object.py +++ b/Lib/test/test_capi/test_object.py @@ -238,13 +238,13 @@ def check_negative_refcount(self, code): @unittest.skipUnless(hasattr(_testcapi, 'negative_refcount'), 'need _testcapi.negative_refcount()') def test_negative_refcount(self): - code = """ + code = d""" import _testcapi from test import support with support.SuppressCrashReport(): _testcapi.negative_refcount() - """ + """ self.check_negative_refcount(code) @unittest.skipUnless(hasattr(_testcapi, 'decref_freed_object'), @@ -252,13 +252,13 @@ def test_negative_refcount(self): @support.skip_if_sanitizer("use after free on purpose", address=True, memory=True, ub=True) def test_decref_freed_object(self): - code = """ + code = d""" import _testcapi from test import support with support.SuppressCrashReport(): _testcapi.decref_freed_object() - """ + """ self.check_negative_refcount(code) @support.requires_resource('cpu') diff --git a/Lib/test/test_capi/test_opt.py b/Lib/test/test_capi/test_opt.py index 2248920c266aef..18efe06320d1d3 100644 --- a/Lib/test/test_capi/test_opt.py +++ b/Lib/test/test_capi/test_opt.py @@ -126,11 +126,11 @@ def f{n}(): def test_uop_optimizer_invalidation(self): # Generate a new function at each call ns = {} - exec(textwrap.dedent(f""" + exec(fd""" def f(): for i in range({TIER2_THRESHOLD}): pass - """), ns, ns) + """, ns, ns) f = ns['f'] f() exe = get_first_executor(f) @@ -203,7 +203,7 @@ def testfunc(x): def test_extended_arg(self): "Check EXTENDED_ARG handling in superblock creation" ns = {} - exec(textwrap.dedent(f""" + exec(fd""" def many_vars(): # 260 vars, so z9 should have index 259 a0 = a1 = a2 = a3 = a4 = a5 = a6 = a7 = a8 = a9 = 42 @@ -235,7 +235,7 @@ def many_vars(): while z9 > 0: z9 = z9 - 1 +z9 - """), ns, ns) + """, ns, ns) many_vars = ns["many_vars"] ex = get_first_executor(many_vars) @@ -786,7 +786,7 @@ def dummy(x): def test_promote_globals_to_constants(self): - result = script_helper.run_python_until_end('-c', textwrap.dedent(""" + result = script_helper.run_python_until_end('-c', d""" import _testinternalcapi import opcode import _opcode @@ -816,7 +816,7 @@ def testfunc(n): uops = get_opnames(ex) assert "_LOAD_GLOBAL_BUILTINS" not in uops assert "_LOAD_CONST_INLINE_BORROW" in uops - """), PYTHON_JIT="1") + """, PYTHON_JIT="1") self.assertEqual(result[0].rc, 0, result) def test_float_add_constant_propagation(self): @@ -1975,7 +1975,7 @@ def test_jit_error_pops(self): {item for item in items} def test_power_type_depends_on_input_values(self): - template = textwrap.dedent(""" + template = d""" import _testinternalcapi L, R, X, Y = {l}, {r}, {x}, {y} @@ -2002,7 +2002,7 @@ def f(l: complex, r: complex) -> None: f(L, R) # ...then run with another: f(X, Y) - """) + """ interesting = [ (1, 1), # int ** int -> int (1, -1), # int ** int -> float @@ -4888,7 +4888,7 @@ class A: def test_attr_promotion_failure(self): # We're not testing for any specific uops here, just # testing it doesn't crash. - script_helper.assert_python_ok('-c', textwrap.dedent(""" + script_helper.assert_python_ok('-c', d""" import _testinternalcapi import _opcode import email @@ -4911,7 +4911,7 @@ def testfunc(n): testfunc(_testinternalcapi.TIER2_THRESHOLD) - """)) + """) def test_pop_top_specialize_none(self): def testfunc(n): @@ -5105,7 +5105,7 @@ def f(): f" than expected _EXIT_TRACE") def test_enter_executor_valid_op_arg(self): - script_helper.assert_python_ok("-c", textwrap.dedent(""" + script_helper.assert_python_ok("-c", d""" import sys sys.setrecursionlimit(30) # reduce time of the run @@ -5135,11 +5135,11 @@ def recursive_wrapper_4569(): f1() except RecursionError: pass - """)) + """) def test_attribute_changes_are_watched(self): # Just running to make sure it doesn't crash. - script_helper.assert_python_ok("-c", textwrap.dedent(""" + script_helper.assert_python_ok("-c", d""" from concurrent.futures import ThreadPoolExecutor from unittest import TestCase NTHREADS = 6 @@ -5158,7 +5158,7 @@ def write(id0): with ThreadPoolExecutor(NTHREADS) as pool: pool.submit(read, (1,)) pool.submit(write, (1,)) - """)) + """) def test_handling_of_tos_cache_with_side_exits(self): # https://github.com/python/cpython/issues/142718 @@ -5182,7 +5182,7 @@ class Obj: obj.attr = EvilAttr(obj.__dict__) def test_promoted_global_refcount_eliminated(self): - result = script_helper.run_python_until_end('-c', textwrap.dedent(""" + result = script_helper.run_python_until_end('-c', d""" import _testinternalcapi import opcode import _opcode @@ -5217,7 +5217,7 @@ def testfunc(n): assert "_POP_TOP_NOP" in uops pop_top_count = len([opname for opname in ex if opname == "_POP_TOP" ]) assert pop_top_count <= 2 - """), PYTHON_JIT="1") + """, PYTHON_JIT="1") self.assertEqual(result[0].rc, 0, result) def test_constant_fold_tuple(self): @@ -5779,7 +5779,7 @@ def testfunc(n): def test_143026(self): # https://github.com/python/cpython/issues/143026 - result = script_helper.run_python_until_end('-c', textwrap.dedent(""" + result = script_helper.run_python_until_end('-c', d""" import gc thresholds = gc.get_threshold() try: @@ -5792,7 +5792,7 @@ def f1(): f1() finally: gc.set_threshold(*thresholds) - """), PYTHON_JIT="1") + """, PYTHON_JIT="1") self.assertEqual(result[0].rc, 0, result) def test_143092(self): @@ -5882,7 +5882,7 @@ async def async_for_driver(): def test_143358(self): # https://github.com/python/cpython/issues/143358 - result = script_helper.run_python_until_end('-c', textwrap.dedent(f""" + result = script_helper.run_python_until_end('-c', fd""" def f1(): class EvilIterator: @@ -5921,7 +5921,7 @@ def __next__(self): pass f1() - """), PYTHON_JIT="1", PYTHON_JIT_STRESS="1") + """, PYTHON_JIT="1", PYTHON_JIT_STRESS="1") self.assertEqual(result[0].rc, 0, result) def test_149335_trace_buffer_guard(self): @@ -5963,7 +5963,7 @@ def f1(): self.assertEqual(result[0].rc, 0, result) def test_144068_daemon_thread_jit_cleanup(self): - result = script_helper.run_python_until_end('-c', textwrap.dedent(""" + result = script_helper.run_python_until_end('-c', d""" import threading import time @@ -5977,7 +5977,7 @@ def hot_loop(): t.start() time.sleep(0.1) - """), PYTHON_JIT="1", ASAN_OPTIONS="detect_leaks=1") + """, PYTHON_JIT="1", ASAN_OPTIONS="detect_leaks=1") self.assertEqual(result[0].rc, 0, result) stderr = result[0].err.decode('utf-8', errors='replace') self.assertNotIn('LeakSanitizer', stderr, @@ -5987,7 +5987,7 @@ def hot_loop(): def test_cold_exit_on_init_cleanup_frame(self): - result = script_helper.run_python_until_end('-c', textwrap.dedent(""" + result = script_helper.run_python_until_end('-c', d""" class A: __slots__ = ('x', 'y', 'z', 'w') def __init__(self): @@ -6030,13 +6030,13 @@ def __init__(self, name): for f in funcs: for _ in range(10): f(names, info) - """), PYTHON_JIT="1", PYTHON_JIT_STRESS="1", + """, PYTHON_JIT="1", PYTHON_JIT_STRESS="1", PYTHON_JIT_SIDE_EXIT_INITIAL_VALUE="1") self.assertEqual(result[0].rc, 0, result) def test_for_iter_gen_cleared_frame_does_not_crash(self): # See: https://github.com/python/cpython/issues/145197 - result = script_helper.run_python_until_end('-c', textwrap.dedent(""" + result = script_helper.run_python_until_end('-c', d""" def g(): yield 1 yield 2 @@ -6052,7 +6052,7 @@ def g(): it.close() for _ in it: pass - """), + """, PYTHON_JIT="1", PYTHON_JIT_STRESS="1") self.assertEqual(result[0].rc, 0, result) @@ -6165,7 +6165,7 @@ def testfunc(n): self.assertEqual(uops.count("_GUARD_NOS_TYPE_VERSION"), 2) def test_settrace_then_polymorphic_call_does_not_crash(self): - script_helper.assert_python_ok("-c", textwrap.dedent(""" + script_helper.assert_python_ok("-c", d""" import sys sys.settrace(lambda *_: None) sys.settrace(None) @@ -6176,7 +6176,7 @@ def __init__(self, x): for i in 0, 1, 0, 1: C(0) if i else str(0) - """)) + """) def test_load_special_type_guard_deopt(self): script_helper.assert_python_ok("-s", "-c", textwrap.dedent(f""" diff --git a/Lib/test/test_cmd.py b/Lib/test/test_cmd.py index dbfec42fc21988..028c67cea3e24d 100644 --- a/Lib/test/test_cmd.py +++ b/Lib/test/test_cmd.py @@ -9,7 +9,6 @@ import doctest import unittest import io -import textwrap from test import support from test.support.import_helper import ensure_lazy_imports, import_module from test.support.pty_helper import run_pty @@ -277,7 +276,7 @@ def setUpClass(): readline = import_module('readline') def test_basic_completion(self): - script = textwrap.dedent(""" + script = d""" import cmd class simplecmd(cmd.Cmd): def do_tab_completion_test(self, args): @@ -285,7 +284,7 @@ def do_tab_completion_test(self, args): return True simplecmd().cmdloop() - """) + """ # 't' and complete 'ab_completion_test' to 'tab_completion_test' input = b"t\t\n" @@ -296,7 +295,7 @@ def do_tab_completion_test(self, args): self.assertIn(b'tab completion success', output) def test_bang_completion_without_do_shell(self): - script = textwrap.dedent(""" + script = d""" import cmd class simplecmd(cmd.Cmd): def completedefault(self, text, line, begidx, endidx): @@ -310,7 +309,7 @@ def default(self, line): return True simplecmd().cmdloop() - """) + """ # '! h' or '!h' and complete 'ello' to 'hello' for input in [b"! h\t\n", b"!h\t\n"]: diff --git a/Lib/test/test_cmd_line.py b/Lib/test/test_cmd_line.py index a8645af26b25d8..f5ebe43cb852d6 100644 --- a/Lib/test/test_cmd_line.py +++ b/Lib/test/test_cmd_line.py @@ -401,13 +401,13 @@ def test_osx_android_utf8(self): @unittest.skipIf(os.environ.get("PYTHONUNBUFFERED", "0") != "0", "Python stdio buffering is disabled.") def test_non_interactive_output_buffering(self): - code = textwrap.dedent(""" + code = d""" import sys out = sys.stdout print(out.isatty(), out.write_through, out.line_buffering) err = sys.stderr print(err.isatty(), err.write_through, err.line_buffering) - """) + """ args = [sys.executable, '-c', code] proc = subprocess.run(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, check=True) diff --git a/Lib/test/test_cmd_line_script.py b/Lib/test/test_cmd_line_script.py index 73b1f671c58555..f831933ad2a2cf 100644 --- a/Lib/test/test_cmd_line_script.py +++ b/Lib/test/test_cmd_line_script.py @@ -12,7 +12,6 @@ import subprocess import io -import textwrap from test import support from test.support import import_helper, is_apple, os_helper from test.support.script_helper import ( @@ -536,12 +535,12 @@ def test_dash_m_main_traceback(self): def test_pep_409_verbiage(self): # Make sure PEP 409 syntax properly suppresses # the context of an exception - script = textwrap.dedent("""\ + script = d""" try: raise ValueError except ValueError: raise NameError from None - """) + """ with os_helper.temp_dir() as script_dir: script_name = _make_test_script(script_dir, 'script', script) exitcode, stdout, stderr = assert_python_failure(script_name) @@ -581,7 +580,7 @@ def test_non_ascii(self): self.assertEqual(0, rc) def test_issue20500_exit_with_exception_value(self): - script = textwrap.dedent("""\ + script = d""" import sys error = None try: @@ -591,7 +590,7 @@ def test_issue20500_exit_with_exception_value(self): if error: sys.exit(error) - """) + """ with os_helper.temp_dir() as script_dir: script_name = _make_test_script(script_dir, 'script', script) exitcode, stdout, stderr = assert_python_failure(script_name) @@ -608,10 +607,10 @@ def test_syntaxerror_unindented_caret_position(self): self.assertIn("\n ^^^^^\n", text) def test_syntaxerror_indented_caret_position(self): - script = textwrap.dedent("""\ + script = d""" if True: 1 + 1 = 2 - """) + """ with os_helper.temp_dir() as script_dir: script_name = _make_test_script(script_dir, 'script', script) exitcode, stdout, stderr = assert_python_failure(script_name) @@ -712,11 +711,11 @@ def test_consistent_sys_path_for_direct_execution(self): # ./python -s script_dir/__main__.py # ./python -s script_dir # ./python -I script_dir - script = textwrap.dedent("""\ + script = d""" import sys for entry in sys.path: print(entry) - """) + """ # Always show full path diffs on errors self.maxDiff = None with os_helper.temp_dir() as work_dir, os_helper.temp_dir() as script_dir: @@ -744,11 +743,11 @@ def test_consistent_sys_path_for_module_execution(self): # # And that this fails as unable to find the package: # ./python -Im script_pkg - script = textwrap.dedent("""\ + script = d""" import sys for entry in sys.path: print(entry) - """) + """ # Always show full path diffs on errors self.maxDiff = None with os_helper.temp_dir() as work_dir: diff --git a/Lib/test/test_code.py b/Lib/test/test_code.py index 657e70a92f09b9..62a5ccfddac164 100644 --- a/Lib/test/test_code.py +++ b/Lib/test/test_code.py @@ -200,7 +200,6 @@ import threading import doctest import unittest -import textwrap import weakref import dis @@ -498,12 +497,12 @@ def test_co_positions_artificial_instructions(self): import dis namespace = {} - exec(textwrap.dedent("""\ + exec(d""" try: 1/0 except Exception as e: exc = e - """), namespace) + """, namespace) exc = namespace['exc'] traceback = exc.__traceback__ @@ -544,7 +543,7 @@ def test_co_positions_artificial_instructions(self): def test_endline_and_columntable_none_when_no_debug_ranges(self): # Make sure that if `-X no_debug_ranges` is used, there is # minimal debug info - code = textwrap.dedent(""" + code = d""" def f(): pass @@ -553,12 +552,12 @@ def f(): assert line == end_line assert column is None assert end_column is None - """) + """ assert_python_ok('-X', 'no_debug_ranges', '-c', code) def test_endline_and_columntable_none_when_no_debug_ranges_env(self): # Same as above but using the environment variable opt out. - code = textwrap.dedent(""" + code = d""" def f(): pass @@ -567,7 +566,7 @@ def f(): assert line == end_line assert column is None assert end_column is None - """) + """ assert_python_ok('-c', code, PYTHONNODEBUGRANGES='1') # co_positions behavior when info is missing. @@ -1226,15 +1225,15 @@ def test_interned_constants(self): # compile separately to avoid compile time de-duping globals = {} - exec(textwrap.dedent(""" + exec(d""" def func1(): return (0.0, (1, 2, "hello")) - """), globals) + """, globals) - exec(textwrap.dedent(""" + exec(d""" def func2(): return (0.0, (1, 2, "hello")) - """), globals) + """, globals) self.assertTrue(globals["func1"]() is globals["func2"]()) @@ -1463,7 +1462,7 @@ def f(): @cpython_only def test_docstring_under_o2(self): - code = textwrap.dedent(''' + code = d''' def has_docstring(x, y): """This is a first-line doc string""" """This is a second-line doc string""" @@ -1485,7 +1484,7 @@ async def async_func(): for func in [has_docstring, no_docstring(4), async_func]: assert(func.__doc__ is None) - ''') + ''' rc, out, err = assert_python_ok('-OO', '-c', code) diff --git a/Lib/test/test_compile.py b/Lib/test/test_compile.py index 9edbca3c383b43..dfca0a24b0d4e7 100644 --- a/Lib/test/test_compile.py +++ b/Lib/test/test_compile.py @@ -158,11 +158,11 @@ def test_float_literals(self): def test_indentation(self): # testing compile() of indented block w/o trailing newline" - s = textwrap.dedent(""" + s = d""" if 1: if 2: pass - """) + """ compile(s, "", "exec") # This test is probably specific to CPython and may not generalize @@ -476,17 +476,17 @@ def test_condition_expression_with_redundant_comparisons_compiles(self): compile(expr, '', 'exec') def test_dead_code_with_except_handler_compiles(self): - compile(textwrap.dedent(""" + compile(d""" if None: with CM: x = 1 else: x = 2 - """), '', 'exec') + """, '', 'exec') def test_try_except_in_while_with_chained_condition_compiles(self): # see gh-124871 - compile(textwrap.dedent(""" + compile(d""" name_1, name_2, name_3 = 1, 2, 3 while name_3 <= name_2 > name_1: try: @@ -495,7 +495,7 @@ def test_try_except_in_while_with_chained_condition_compiles(self): pass finally: pass - """), '', 'exec') + """, '', 'exec') def test_compile_invalid_namedexpr(self): # gh-109351 @@ -526,7 +526,7 @@ def test_compile_invalid_namedexpr(self): def test_compile_redundant_jumps_and_nops_after_moving_cold_blocks(self): # See gh-120367 - code=textwrap.dedent(""" + code=d""" try: pass except: @@ -537,7 +537,7 @@ def test_compile_redundant_jumps_and_nops_after_moving_cold_blocks(self): pass finally: something - """) + """ tree = ast.parse(code) @@ -553,7 +553,7 @@ def test_compile_redundant_jumps_and_nops_after_moving_cold_blocks(self): def test_compile_redundant_jump_after_convert_pseudo_ops(self): # See gh-120367 - code=textwrap.dedent(""" + code=d""" if name_2: pass else: @@ -562,7 +562,7 @@ def test_compile_redundant_jump_after_convert_pseudo_ops(self): except: pass ~name_5 - """) + """ tree = ast.parse(code) @@ -913,7 +913,7 @@ def unused_code_at_end(): @support.cpython_only def test_docstring(self): - src = textwrap.dedent(""" + src = d""" def with_docstring(): "docstring" @@ -929,7 +929,7 @@ def with_const_expression(): def multiple_const_strings(): "not docstring " * 3 - """) + """ for opt in [0, 1, 2]: with self.subTest(opt=opt): @@ -972,7 +972,7 @@ def test_docstring_interactive_mode(self): @support.cpython_only def test_docstring_omitted(self): # See gh-115347 - src = textwrap.dedent(""" + src = d""" def f(): "docstring1" def h(): @@ -984,7 +984,7 @@ class C: pass return h - """) + """ for opt in [-1, 0, 1, 2]: for mode in ["exec", "single"]: with self.subTest(opt=opt, mode=mode): @@ -1565,14 +1565,14 @@ def test_if_expression_expression_empty_block(self): def test_multi_line_lambda_as_argument(self): # See gh-101928 - code = textwrap.dedent(""" + code = d""" def foo(param, lambda_exp): pass foo(param=0, lambda_exp=lambda: 1) - """) + """ compile(code, "", "exec") def test_apply_static_swaps(self): @@ -1646,7 +1646,7 @@ def f(): def test_global_declaration_in_except_used_in_else(self): # See gh-111123 - code = textwrap.dedent("""\ + code = d""" def f(): try: pass @@ -1654,7 +1654,7 @@ def f(): global a else: print(a) - """) + """ g, l = {'a': 5}, {} for kw in ("except", "except*"): @@ -1684,26 +1684,26 @@ class WeirdDict(dict): def test_compile_warnings(self): # Each invocation of compile() emits compiler warnings, even if they # have the same message and line number. - source = textwrap.dedent(r""" + source = rd""" # tokenizer 1or 0 # line 3 # code generator 1 is 1 # line 5 - """) + """ with warnings.catch_warnings(record=True) as caught: warnings.simplefilter("default") for i in range(2): # Even if compile() is at the same line. compile(source, '', 'exec') - self.assertEqual([wm.lineno for wm in caught], [3, 5] * 2) + self.assertEqual([wm.lineno for wm in caught], [2, 4] * 2) def test_compile_warning_in_finally(self): # Ensure that warnings inside finally blocks are # only emitted once despite the block being # compiled twice (for normal execution and for # exception handling). - source = textwrap.dedent(""" + source = d""" try: pass finally: @@ -1712,19 +1712,19 @@ def test_compile_warning_in_finally(self): pass finally: # nested 1 is 1 # line 9 - """) + """ with warnings.catch_warnings(record=True) as caught: warnings.simplefilter("always") compile(source, '', 'exec') - self.assertEqual(sorted(wm.lineno for wm in caught), [5, 9]) + self.assertEqual(sorted(wm.lineno for wm in caught), [4, 8]) for wm in caught: self.assertEqual(wm.category, SyntaxWarning) self.assertIn("\"is\" with 'int' literal", str(wm.message)) # Other code path is used for "try" with "except*". - source = textwrap.dedent(""" + source = d""" try: pass except *Exception: @@ -1737,13 +1737,13 @@ def test_compile_warning_in_finally(self): pass finally: # nested 1 is 1 # line 13 - """) + """ with warnings.catch_warnings(record=True) as caught: warnings.simplefilter("always") compile(source, '', 'exec') - self.assertEqual(sorted(wm.lineno for wm in caught), [7, 13]) + self.assertEqual(sorted(wm.lineno for wm in caught), [6, 12]) for wm in caught: self.assertEqual(wm.category, SyntaxWarning) self.assertIn("\"is\" with 'int' literal", str(wm.message)) @@ -1773,27 +1773,27 @@ def test_filter_syntax_warnings_by_module(self): self.assertIs(wm.category, SyntaxWarning) @support.subTests('src', [ - textwrap.dedent(""" + d""" def f(): try: pass finally: return 42 - """), - textwrap.dedent(""" + """, + d""" for x in y: try: pass finally: break - """), - textwrap.dedent(""" + """, + d""" for x in y: try: pass finally: continue - """), + """, ]) def test_pep_765_warnings(self, src): with self.assertWarnsRegex(SyntaxWarning, 'finally'): @@ -1805,27 +1805,27 @@ def test_pep_765_warnings(self, src): compile(tree, '', 'exec') @support.subTests('src', [ - textwrap.dedent(""" + d""" try: pass finally: def f(): return 42 - """), - textwrap.dedent(""" + """, + d""" try: pass finally: for x in y: break - """), - textwrap.dedent(""" + """, + d""" try: pass finally: for x in y: continue - """), + """, ]) def test_pep_765_no_warnings(self, src): with warnings.catch_warnings(): @@ -1972,24 +1972,24 @@ def test_compiles_to_extended_op_arg(self): column=2, end_column=9, occurrence=2) def test_multiline_expression(self): - snippet = textwrap.dedent("""\ + snippet = d""" f( 1, 2, 3, 4 ) - """) + """ compiled_code, _ = self.check_positions_against_ast(snippet) self.assertOpcodeSourcePositionIs(compiled_code, 'CALL', line=1, end_line=3, column=0, end_column=1) @requires_specialization def test_multiline_boolean_expression(self): - snippet = textwrap.dedent("""\ + snippet = d""" if (a or (b and not c) or not ( d > 0)): x = 42 - """) + """ compiled_code, _ = self.check_positions_against_ast(snippet) # jump if a is true: self.assertOpcodeSourcePositionIs(compiled_code, 'POP_JUMP_IF_TRUE', @@ -2009,11 +2009,11 @@ def test_multiline_boolean_expression(self): @unittest.skipIf(sys.flags.optimize, "Assertions are disabled in optimized mode") def test_multiline_assert(self): - snippet = textwrap.dedent("""\ + snippet = d""" assert (a > 0 and bb > 0 and ccc == 1000000), "error msg" - """) + """ compiled_code, _ = self.check_positions_against_ast(snippet) self.assertOpcodeSourcePositionIs(compiled_code, 'LOAD_COMMON_CONSTANT', line=1, end_line=3, column=0, end_column=36, occurrence=1) @@ -2026,14 +2026,14 @@ def test_multiline_assert(self): line=1, end_line=3, column=8, end_column=22, occurrence=1) def test_multiline_generator_expression(self): - snippet = textwrap.dedent("""\ + snippet = d""" ((x, 2*x) for x in [1,2,3] if (x > 0 and x < 100 and x != 50)) - """) + """ compiled_code, _ = self.check_positions_against_ast(snippet) compiled_code = compiled_code.co_consts[0] self.assertIsInstance(compiled_code, types.CodeType) @@ -2045,14 +2045,14 @@ def test_multiline_generator_expression(self): line=4, end_line=4, column=7, end_column=14, occurrence=1) def test_multiline_async_generator_expression(self): - snippet = textwrap.dedent("""\ + snippet = d""" ((x, 2*x) async for x in [1,2,3] if (x > 0 and x < 100 and x != 50)) - """) + """ compiled_code, _ = self.check_positions_against_ast(snippet) compiled_code = compiled_code.co_consts[0] self.assertIsInstance(compiled_code, types.CodeType) @@ -2062,14 +2062,14 @@ def test_multiline_async_generator_expression(self): line=1, end_line=6, column=0, end_column=32, occurrence=1) def test_multiline_list_comprehension(self): - snippet = textwrap.dedent("""\ + snippet = d""" [(x, 2*x) for x in [1,2,3] if (x > 0 and x < 100 and x != 50)] - """) + """ compiled_code, _ = self.check_positions_against_ast(snippet) self.assertIsInstance(compiled_code, types.CodeType) self.assertOpcodeSourcePositionIs(compiled_code, 'LIST_APPEND', @@ -2078,7 +2078,7 @@ def test_multiline_list_comprehension(self): line=1, end_line=2, column=1, end_column=8, occurrence=1) def test_multiline_async_list_comprehension(self): - snippet = textwrap.dedent("""\ + snippet = d""" async def f(): [(x, 2*x) @@ -2086,7 +2086,7 @@ async def f(): in [1,2,3] if (x > 0 and x < 100 and x != 50)] - """) + """ compiled_code, _ = self.check_positions_against_ast(snippet) g = {} eval(compiled_code, g) @@ -2100,14 +2100,14 @@ async def f(): line=2, end_line=7, column=4, end_column=36, occurrence=1) def test_multiline_set_comprehension(self): - snippet = textwrap.dedent("""\ + snippet = d""" {(x, 2*x) for x in [1,2,3] if (x > 0 and x < 100 and x != 50)} - """) + """ compiled_code, _ = self.check_positions_against_ast(snippet) self.assertIsInstance(compiled_code, types.CodeType) self.assertOpcodeSourcePositionIs(compiled_code, 'SET_ADD', @@ -2116,7 +2116,7 @@ def test_multiline_set_comprehension(self): line=1, end_line=2, column=1, end_column=8, occurrence=1) def test_multiline_async_set_comprehension(self): - snippet = textwrap.dedent("""\ + snippet = d""" async def f(): {(x, 2*x) @@ -2124,7 +2124,7 @@ async def f(): in [1,2,3] if (x > 0 and x < 100 and x != 50)} - """) + """ compiled_code, _ = self.check_positions_against_ast(snippet) g = {} eval(compiled_code, g) @@ -2138,14 +2138,14 @@ async def f(): line=2, end_line=7, column=4, end_column=36, occurrence=1) def test_multiline_dict_comprehension(self): - snippet = textwrap.dedent("""\ + snippet = d""" {x: 2*x for x in [1,2,3] if (x > 0 and x < 100 and x != 50)} - """) + """ compiled_code, _ = self.check_positions_against_ast(snippet) self.assertIsInstance(compiled_code, types.CodeType) self.assertOpcodeSourcePositionIs(compiled_code, 'MAP_ADD', @@ -2154,7 +2154,7 @@ def test_multiline_dict_comprehension(self): line=1, end_line=2, column=1, end_column=7, occurrence=1) def test_multiline_async_dict_comprehension(self): - snippet = textwrap.dedent("""\ + snippet = d""" async def f(): {x: 2*x @@ -2162,7 +2162,7 @@ async def f(): in [1,2,3] if (x > 0 and x < 100 and x != 50)} - """) + """ compiled_code, _ = self.check_positions_against_ast(snippet) g = {} eval(compiled_code, g) @@ -2176,11 +2176,11 @@ async def f(): line=2, end_line=7, column=4, end_column=36, occurrence=1) def test_matchcase_sequence(self): - snippet = textwrap.dedent("""\ + snippet = d""" match x: case a, b: pass - """) + """ compiled_code, _ = self.check_positions_against_ast(snippet) self.assertOpcodeSourcePositionIs(compiled_code, 'MATCH_SEQUENCE', line=2, end_line=2, column=9, end_column=13, occurrence=1) @@ -2192,11 +2192,11 @@ def test_matchcase_sequence(self): line=2, end_line=2, column=9, end_column=13, occurrence=2) def test_matchcase_sequence_wildcard(self): - snippet = textwrap.dedent("""\ + snippet = d""" match x: case a, *b, c: pass - """) + """ compiled_code, _ = self.check_positions_against_ast(snippet) self.assertOpcodeSourcePositionIs(compiled_code, 'MATCH_SEQUENCE', line=2, end_line=2, column=9, end_column=17, occurrence=1) @@ -2210,11 +2210,11 @@ def test_matchcase_sequence_wildcard(self): line=2, end_line=2, column=9, end_column=17, occurrence=3) def test_matchcase_mapping(self): - snippet = textwrap.dedent("""\ + snippet = d""" match x: case {"a" : a, "b": b}: pass - """) + """ compiled_code, _ = self.check_positions_against_ast(snippet) self.assertOpcodeSourcePositionIs(compiled_code, 'MATCH_MAPPING', line=2, end_line=2, column=9, end_column=26, occurrence=1) @@ -2226,11 +2226,11 @@ def test_matchcase_mapping(self): line=2, end_line=2, column=9, end_column=26, occurrence=2) def test_matchcase_mapping_wildcard(self): - snippet = textwrap.dedent("""\ + snippet = d""" match x: case {"a" : a, "b": b, **c}: pass - """) + """ compiled_code, _ = self.check_positions_against_ast(snippet) self.assertOpcodeSourcePositionIs(compiled_code, 'MATCH_MAPPING', line=2, end_line=2, column=9, end_column=31, occurrence=1) @@ -2242,11 +2242,11 @@ def test_matchcase_mapping_wildcard(self): line=2, end_line=2, column=9, end_column=31, occurrence=2) def test_matchcase_class(self): - snippet = textwrap.dedent("""\ + snippet = d""" match x: case C(a, b): pass - """) + """ compiled_code, _ = self.check_positions_against_ast(snippet) self.assertOpcodeSourcePositionIs(compiled_code, 'MATCH_CLASS', line=2, end_line=2, column=9, end_column=16, occurrence=1) @@ -2258,11 +2258,11 @@ def test_matchcase_class(self): line=2, end_line=2, column=9, end_column=16, occurrence=2) def test_matchcase_or(self): - snippet = textwrap.dedent("""\ + snippet = d""" match x: case C(1) | C(2): pass - """) + """ compiled_code, _ = self.check_positions_against_ast(snippet) self.assertOpcodeSourcePositionIs(compiled_code, 'MATCH_CLASS', line=2, end_line=2, column=9, end_column=13, occurrence=1) @@ -2750,7 +2750,7 @@ def test_try_except_star_finally(self): b finally: c - """ + """ self.check_stack_size(snippet) def test_try_finally(self): @@ -2759,7 +2759,7 @@ def test_try_finally(self): a finally: b - """ + """ self.check_stack_size(snippet) def test_with(self): diff --git a/Lib/test/test_compiler_assemble.py b/Lib/test/test_compiler_assemble.py index 99a11e99d56485..858ea6908452cb 100644 --- a/Lib/test/test_compiler_assemble.py +++ b/Lib/test/test_compiler_assemble.py @@ -1,6 +1,5 @@ import dis import io -import textwrap import types from test.support.bytecode_helper import AssemblerTestCase @@ -141,9 +140,9 @@ def test_exception_table(self): co = self.insts_to_code_object(insts, metadata) output = io.StringIO() dis.dis(co, file=output) - exc_table = textwrap.dedent(""" + exc_table = d""" ExceptionTable: L1 to L2 -> L2 [0] L2 to L3 -> L3 [1] lasti - """) + """ self.assertEndsWith(output.getvalue(), exc_table) diff --git a/Lib/test/test_compiler_codegen.py b/Lib/test/test_compiler_codegen.py index 36058854a41d63..a3f428ed5c4697 100644 --- a/Lib/test/test_compiler_codegen.py +++ b/Lib/test/test_compiler_codegen.py @@ -1,5 +1,4 @@ -import textwrap from test.support.bytecode_helper import CodegenTestCase # Tests for the code-generation stage of the compiler. @@ -68,10 +67,10 @@ def test_for_loop(self): self.codegen_test(snippet, expected) def test_function(self): - snippet = textwrap.dedent(""" + snippet = d""" def f(x): return x + 42 - """) + """ expected = [ # Function definition ('RESUME', 0), @@ -95,7 +94,7 @@ def f(x): self.codegen_test(snippet, expected) def test_nested_functions(self): - snippet = textwrap.dedent(""" + snippet = d""" def f(): def h(): return 12 @@ -105,7 +104,7 @@ def g(): z = 3 u = 4 return 42 - """) + """ expected = [ # Function definition ('RESUME', 0), diff --git a/Lib/test/test_concurrent_futures/test_interpreter_pool.py b/Lib/test/test_concurrent_futures/test_interpreter_pool.py index 7241fcc4b1e74d..d77dd9f6c3236b 100644 --- a/Lib/test/test_concurrent_futures/test_interpreter_pool.py +++ b/Lib/test/test_concurrent_futures/test_interpreter_pool.py @@ -5,7 +5,6 @@ import os import subprocess import sys -import textwrap import time import unittest from concurrent.futures.interpreter import BrokenInterpreterPool @@ -463,7 +462,7 @@ def test_free_reference(self): @support.requires_subprocess() def test_import_interpreter_pool_executor(self): # Test the import behavior normally if _interpreters is unavailable. - code = textwrap.dedent(""" + code = d""" import sys # Set it to None to emulate the case when _interpreter is unavailable. sys.modules['_interpreters'] = None @@ -491,7 +490,7 @@ def test_import_interpreter_pool_executor(self): print('InterpreterPoolExecutor should not be imported!', file=sys.stderr) sys.exit(1) - """) + """ cmd = [sys.executable, '-c', code] p = subprocess.run(cmd, capture_output=True) diff --git a/Lib/test/test_configparser.py b/Lib/test/test_configparser.py index 4783943f71a109..a9ef8e307cc8ba 100644 --- a/Lib/test/test_configparser.py +++ b/Lib/test/test_configparser.py @@ -332,31 +332,31 @@ def test_basic(self): self.basic_test(cf) if self.strict: with self.assertRaises(configparser.DuplicateOptionError): - cf.read_string(textwrap.dedent("""\ + cf.read_string(d""" [Duplicate Options Here] option {0[0]} with a value option {0[1]} with another value - """.format(self.delimiters))) + """.format(self.delimiters)) with self.assertRaises(configparser.DuplicateSectionError): - cf.read_string(textwrap.dedent("""\ + cf.read_string(d""" [And Now For Something] completely different {0[0]} True [And Now For Something] the larch {0[1]} 1 - """.format(self.delimiters))) + """.format(self.delimiters)) else: - cf.read_string(textwrap.dedent("""\ + cf.read_string(d""" [Duplicate Options Here] option {0[0]} with a value option {0[1]} with another value - """.format(self.delimiters))) + """.format(self.delimiters)) - cf.read_string(textwrap.dedent("""\ + cf.read_string(d""" [And Now For Something] completely different {0[0]} True [And Now For Something] the larch {0[1]} 1 - """.format(self.delimiters))) + """.format(self.delimiters)) def test_basic_from_dict(self): config = { @@ -899,11 +899,10 @@ def test_invalid_multiline_value(self): if self.allow_no_value: self.skipTest('if no_value is allowed, ParsingError is not raised') - invalid = textwrap.dedent("""\ + invalid = d""" [DEFAULT] test {0} test invalid""".format(self.delimiters[0]) - ) cf = self.newconfig() with self.assertRaises(configparser.ParsingError): cf.read_string(invalid) @@ -1008,7 +1007,7 @@ def test_defaults_keyword(self): class ConfigParserTestCaseNoInterpolation(BasicTestCase, unittest.TestCase): config_class = configparser.ConfigParser interpolation = None - ini = textwrap.dedent(""" + ini = d""" [numbers] one = 1 two = %(one)s * 2 @@ -1016,7 +1015,7 @@ class ConfigParserTestCaseNoInterpolation(BasicTestCase, unittest.TestCase): [hexen] sixteen = ${numbers:two} * 8 - """).strip() + """.strip() def assertMatchesIni(self, cf): self.assertEqual(cf['numbers']['one'], '1') @@ -1178,7 +1177,7 @@ def fromstring(self, string, defaults=None, optionxform=None): return cf def test_extended_interpolation(self): - cf = self.fromstring(textwrap.dedent(""" + cf = self.fromstring(d""" [common] favourite Beatle = Paul favourite color = green @@ -1200,7 +1199,7 @@ def test_extended_interpolation(self): favourite state of mind = paranoid favourite movie = soylent ${common:favourite color} favourite song = ${favourite color} sabbath - ${favourite state of mind} - """).strip()) + """.strip()) eq = self.assertEqual eq(cf['common']['favourite Beatle'], 'Paul') @@ -1223,7 +1222,7 @@ def test_extended_interpolation(self): 'black sabbath - paranoid') def test_endless_loop(self): - cf = self.fromstring(textwrap.dedent(""" + cf = self.fromstring(d""" [one for you] ping = ${one for me:pong} @@ -1232,7 +1231,7 @@ def test_endless_loop(self): [selfish] me = ${me} - """).strip()) + """.strip()) with self.assertRaises(configparser.InterpolationDepthError): cf['one for you']['ping'] @@ -1261,7 +1260,7 @@ def test_strange_options(self): self.assertEqual(cm.exception.args[2], '${dollars:${sick}}') #rawval def test_case_sensitivity_basic(self): - ini = textwrap.dedent(""" + ini = d""" [common] optionlower = value OptionUpper = Value @@ -1273,7 +1272,7 @@ def test_case_sensitivity_basic(self): [random] foolower = ${common:optionlower} redefined FooUpper = ${Common:OptionUpper} Redefined - """).strip() + """.strip() cf = self.fromstring(ini) eq = self.assertEqual @@ -1285,7 +1284,7 @@ def test_case_sensitivity_basic(self): eq(cf['random']['FooUpper'], 'A Better Value Redefined') def test_case_sensitivity_conflicts(self): - ini = textwrap.dedent(""" + ini = d""" [common] option = value Option = Value @@ -1297,7 +1296,7 @@ def test_case_sensitivity_conflicts(self): [random] foo = ${common:option} redefined Foo = ${Common:Option} Redefined - """).strip() + """.strip() with self.assertRaises(configparser.DuplicateOptionError): cf = self.fromstring(ini) @@ -1344,22 +1343,22 @@ class NoValueAndExtendedInterpolation(CfgParserTestCaseClass): allow_no_value = True def test_interpolation_with_allow_no_value(self): - config = textwrap.dedent(""" + config = d""" [dummy] a b = ${a} - """) + """ cf = self.fromstring(config) self.assertIs(cf["dummy"]["a"], None) self.assertEqual(cf["dummy"]["b"], "") def test_explicit_none(self): - config = textwrap.dedent(""" + config = d""" [dummy] a = None b = ${a} - """) + """ cf = self.fromstring(config) self.assertEqual(cf["dummy"]["a"], "None") @@ -1483,7 +1482,7 @@ class CompatibleTestCase(CfgParserTestCaseClass, unittest.TestCase): inline_comment_prefixes = ';' def test_comment_handling(self): - config_string = textwrap.dedent("""\ + config_string = d""" [Commented Bar] baz=qwe ; a comment foo: bar # not a comment! @@ -1491,7 +1490,7 @@ def test_comment_handling(self): ; another comment quirk: this;is not a comment ; a space must precede an inline comment - """) + """ cf = self.fromstring(config_string) self.assertEqual(cf.get('Commented Bar', 'foo'), 'bar # not a comment!') @@ -1555,9 +1554,9 @@ def test_file(self): self.assertEqual(parser["Foo Bar"]["foo"], "newbar") def test_iterable(self): - lines = textwrap.dedent(""" + lines = d""" [Foo Bar] - foo=newbar""").strip().split('\n') + foo=newbar""".strip().split('\n') parser = configparser.ConfigParser() parser.read_file(lines) self.assertIn("Foo Bar", parser) @@ -1576,9 +1575,9 @@ def test_readline_generator(self): def test_source_as_bytes(self): """Issue #18260.""" - lines = textwrap.dedent(""" + lines = d""" [badbad] - [badbad]""").strip().split('\n') + [badbad]""".strip().split('\n') parser = configparser.ConfigParser() with self.assertRaises(configparser.DuplicateSectionError) as dse: parser.read_file(lines, source=b"badbad") @@ -1587,10 +1586,10 @@ def test_source_as_bytes(self): "While reading from b'badbad' [line 2]: section 'badbad' " "already exists" ) - lines = textwrap.dedent(""" + lines = d""" [badbad] bad = bad - bad = bad""").strip().split('\n') + bad = bad""".strip().split('\n') parser = configparser.ConfigParser() with self.assertRaises(configparser.DuplicateOptionError) as dse: parser.read_file(lines, source=b"badbad") @@ -1599,9 +1598,9 @@ def test_source_as_bytes(self): "While reading from b'badbad' [line 3]: option 'bad' in section " "'badbad' already exists" ) - lines = textwrap.dedent(""" + lines = d""" [badbad] - = bad""").strip().split('\n') + = bad""".strip().split('\n') parser = configparser.ConfigParser() with self.assertRaises(configparser.ParsingError) as dse: parser.read_file(lines, source=b"badbad") @@ -1609,9 +1608,9 @@ def test_source_as_bytes(self): str(dse.exception), "Source contains parsing errors: b'badbad'\n\t[line 2]: '= bad'" ) - lines = textwrap.dedent(""" + lines = d""" [badbad - bad = bad""").strip().split('\n') + bad = bad""".strip().split('\n') parser = configparser.ConfigParser() with self.assertRaises(configparser.MissingSectionHeaderError) as dse: parser.read_file(lines, source=b"badbad") @@ -1676,12 +1675,12 @@ def test_parsing_error(self): def test_interpolation_validation(self): parser = configparser.ConfigParser() - parser.read_string(""" + parser.read_string(d""" [section] invalid_percent = % invalid_reference = %(() invalid_variable = %(does_not_exist)s - """) + """) with self.assertRaises(configparser.InterpolationSyntaxError) as cm: parser['section']['invalid_percent'] self.assertEqual(str(cm.exception), "'%' must be followed by '%' or " @@ -1693,22 +1692,22 @@ def test_interpolation_validation(self): def test_sectionproxy_repr(self): parser = configparser.ConfigParser() - parser.read_string(""" + parser.read_string(d""" [section] key = value - """) + """) self.assertEqual(repr(parser['section']), '') def test_inconsistent_converters_state(self): parser = configparser.ConfigParser() import decimal parser.converters['decimal'] = decimal.Decimal - parser.read_string(""" + parser.read_string(d""" [s1] one = 1 [s2] two = 2 - """) + """) self.assertIn('decimal', parser.converters) self.assertEqual(parser.getdecimal('s1', 'one'), 1) self.assertEqual(parser.getdecimal('s2', 'two'), 2) @@ -1903,7 +1902,7 @@ class InlineCommentStrippingTestCase(unittest.TestCase): def test_stripping(self): cfg = configparser.ConfigParser(inline_comment_prefixes=(';', '#', '//')) - cfg.read_string(""" + cfg.read_string(d""" [section] k1 = v1;still v1 k2 = v2 ;a comment @@ -1938,7 +1937,7 @@ class ExceptionContextTestCase(unittest.TestCase): def test_get_basic_interpolation(self): parser = configparser.ConfigParser() - parser.read_string(""" + parser.read_string(d""" [Paths] home_dir: /Users my_dir: %(home_dir1)s/lumberjack @@ -1952,7 +1951,7 @@ def test_get_basic_interpolation(self): def test_get_extended_interpolation(self): parser = configparser.ConfigParser( interpolation=configparser.ExtendedInterpolation()) - parser.read_string(""" + parser.read_string(d""" [Paths] home_dir: /Users my_dir: ${home_dir1}/lumberjack @@ -1965,7 +1964,7 @@ def test_get_extended_interpolation(self): def test_missing_options(self): parser = configparser.ConfigParser() - parser.read_string(""" + parser.read_string(d""" [Paths] home_dir: /Users """) @@ -2010,7 +2009,7 @@ def test_converters(self): cfg.converters[''] = lambda v: v with self.assertRaises(ValueError): cfg.converters[None] = lambda v: v - cfg.read_string(""" + cfg.read_string(d""" [s] str = string int = 1 diff --git a/Lib/test/test_dataclasses/__init__.py b/Lib/test/test_dataclasses/__init__.py index 423247c92ce3c2..42e84172d0e2ea 100644 --- a/Lib/test/test_dataclasses/__init__.py +++ b/Lib/test/test_dataclasses/__init__.py @@ -14,7 +14,6 @@ import weakref import traceback import sys -import textwrap import unittest from unittest.mock import Mock from typing import ClassVar, Any, List, Union, Tuple, Dict, Generic, TypeVar, Optional, Protocol, DefaultDict @@ -2410,15 +2409,13 @@ def test_docstring_with_unsolvable_forward_ref_in_init(self): # See: https://github.com/python/cpython/issues/128184 ns = {} exec( - textwrap.dedent( - """ + d""" from dataclasses import dataclass @dataclass class C: def __init__(self, x: X, num: int) -> None: ... """, - ), ns, ) diff --git a/Lib/test/test_descr.py b/Lib/test/test_descr.py index 8a8e70214e27ae..bb88c465dce74c 100644 --- a/Lib/test/test_descr.py +++ b/Lib/test/test_descr.py @@ -7,7 +7,6 @@ import random import string import sys -import textwrap import types import unittest import warnings @@ -5503,7 +5502,7 @@ def test_type_lookup_mro_reference(self): # Issue #14199: _PyType_Lookup() has to keep a strong reference to # the type MRO because it may be modified during the lookup, if # __bases__ is set during the lookup for example. - code = textwrap.dedent(""" + code = d""" class MyKey(object): def __hash__(self): return hash('mykey') @@ -5534,7 +5533,7 @@ class Base2(object): # mykey2 is read from Base2 because MyKey.__eq__ has set __bases_ print(f"mykey2={X.mykey2}") - """) + """ _, out, err = assert_python_ok("-c", code) err = err.decode() self.assertRegex(err, "RuntimeWarning: .*X") diff --git a/Lib/test/test_email/test_contentmanager.py b/Lib/test/test_email/test_contentmanager.py index 3115941f870319..cc7b642a36f235 100644 --- a/Lib/test/test_email/test_contentmanager.py +++ b/Lib/test/test_email/test_contentmanager.py @@ -146,120 +146,120 @@ class TestRawDataManager(TestEmailBase): message = EmailMessage def test_get_text_plain(self): - m = self._str_msg(textwrap.dedent("""\ + m = self._str_msg(d""" Content-Type: text/plain Basic text. - """)) + """) self.assertEqual(raw_data_manager.get_content(m), "Basic text.\n") def test_get_text_html(self): - m = self._str_msg(textwrap.dedent("""\ + m = self._str_msg(d""" Content-Type: text/html

Basic text.

- """)) + """) self.assertEqual(raw_data_manager.get_content(m), "

Basic text.

\n") def test_get_text_plain_latin1(self): - m = self._bytes_msg(textwrap.dedent("""\ + m = self._bytes_msg(d""" Content-Type: text/plain; charset=latin1 Basìc tëxt. - """).encode('latin1')) + """.encode('latin1')) self.assertEqual(raw_data_manager.get_content(m), "Basìc tëxt.\n") def test_get_text_plain_latin1_quoted_printable(self): - m = self._str_msg(textwrap.dedent("""\ + m = self._str_msg(d""" Content-Type: text/plain; charset="latin-1" Content-Transfer-Encoding: quoted-printable Bas=ECc t=EBxt. - """)) + """) self.assertEqual(raw_data_manager.get_content(m), "Basìc tëxt.\n") def test_get_text_plain_utf8_base64(self): - m = self._str_msg(textwrap.dedent("""\ + m = self._str_msg(d""" Content-Type: text/plain; charset="utf8" Content-Transfer-Encoding: base64 QmFzw6xjIHTDq3h0Lgo= - """)) + """) self.assertEqual(raw_data_manager.get_content(m), "Basìc tëxt.\n") def test_get_text_plain_bad_utf8_quoted_printable(self): - m = self._str_msg(textwrap.dedent("""\ + m = self._str_msg(d""" Content-Type: text/plain; charset="utf8" Content-Transfer-Encoding: quoted-printable Bas=c3=acc t=c3=abxt=fd. - """)) + """) self.assertEqual(raw_data_manager.get_content(m), "Basìc tëxt�.\n") def test_get_text_plain_bad_utf8_quoted_printable_ignore_errors(self): - m = self._str_msg(textwrap.dedent("""\ + m = self._str_msg(d""" Content-Type: text/plain; charset="utf8" Content-Transfer-Encoding: quoted-printable Bas=c3=acc t=c3=abxt=fd. - """)) + """) self.assertEqual(raw_data_manager.get_content(m, errors='ignore'), "Basìc tëxt.\n") def test_get_text_plain_utf8_base64_recoverable_bad_CTE_data(self): - m = self._str_msg(textwrap.dedent("""\ + m = self._str_msg(d""" Content-Type: text/plain; charset="utf8" Content-Transfer-Encoding: base64 QmFzw6xjIHTDq3h0Lgo\xFF= - """)) + """) self.assertEqual(raw_data_manager.get_content(m, errors='ignore'), "Basìc tëxt.\n") def test_get_text_invalid_keyword(self): - m = self._str_msg(textwrap.dedent("""\ + m = self._str_msg(d""" Content-Type: text/plain Basic text. - """)) + """) with self.assertRaises(TypeError): raw_data_manager.get_content(m, foo='ignore') def test_get_non_text(self): - template = textwrap.dedent("""\ + template = d""" Content-Type: {} Content-Transfer-Encoding: base64 Ym9ndXMgZGF0YQ== - """) + """ for maintype in 'audio image video application'.split(): with self.subTest(maintype=maintype): m = self._str_msg(template.format(maintype+'/foo')) self.assertEqual(raw_data_manager.get_content(m), b"bogus data") def test_get_non_text_invalid_keyword(self): - m = self._str_msg(textwrap.dedent("""\ + m = self._str_msg(d""" Content-Type: image/jpg Content-Transfer-Encoding: base64 Ym9ndXMgZGF0YQ== - """)) + """) with self.assertRaises(TypeError): raw_data_manager.get_content(m, errors='ignore') def test_get_raises_on_multipart(self): - m = self._str_msg(textwrap.dedent("""\ + m = self._str_msg(d""" Content-Type: multipart/mixed; boundary="===" --=== --===-- - """)) + """) with self.assertRaises(KeyError): raw_data_manager.get_content(m) def test_get_message_rfc822_and_external_body(self): - template = textwrap.dedent("""\ + template = d""" Content-Type: message/{} To: foo@example.com @@ -267,7 +267,7 @@ def test_get_message_rfc822_and_external_body(self): Subject: example an example message - """) + """ for subtype in 'rfc822 external-body'.split(): with self.subTest(subtype=subtype): m = self._str_msg(template.format(subtype)) @@ -279,7 +279,7 @@ def test_get_message_rfc822_and_external_body(self): self.assertEqual(sub_msg['from'].addresses[0].username, 'bar') def test_get_message_non_rfc822_or_external_body_yields_bytes(self): - m = self._str_msg(textwrap.dedent("""\ + m = self._str_msg(d""" Content-Type: message/partial To: foo@example.com @@ -287,19 +287,19 @@ def test_get_message_non_rfc822_or_external_body_yields_bytes(self): Subject: example The real body is in another message. - """)) + """) self.assertStartsWith(raw_data_manager.get_content(m), b'To: foo@ex') def test_set_text_plain(self): m = self._make_message() content = "Simple message.\n" raw_data_manager.set_content(m, content) - self.assertEqual(str(m), textwrap.dedent("""\ + self.assertEqual(str(m), d""" Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: 7bit Simple message. - """)) + """) self.assertEqual(m.get_payload(decode=True).decode('utf-8'), content) self.assertEqual(m.get_content(), content) @@ -307,12 +307,12 @@ def test_set_text_plain_null(self): m = self._make_message() content = '' raw_data_manager.set_content(m, content) - self.assertEqual(str(m), textwrap.dedent("""\ + self.assertEqual(str(m), d""" Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: 7bit - """)) + """) self.assertEqual(m.get_payload(decode=True).decode('utf-8'), '\n') self.assertEqual(m.get_content(), '\n') @@ -320,12 +320,12 @@ def test_set_text_html(self): m = self._make_message() content = "

Simple message.

\n" raw_data_manager.set_content(m, content, subtype='html') - self.assertEqual(str(m), textwrap.dedent("""\ + self.assertEqual(str(m), d""" Content-Type: text/html; charset="utf-8" Content-Transfer-Encoding: 7bit

Simple message.

- """)) + """) self.assertEqual(m.get_payload(decode=True).decode('utf-8'), content) self.assertEqual(m.get_content(), content) @@ -333,12 +333,12 @@ def test_set_text_charset_latin_1(self): m = self._make_message() content = "Simple message.\n" raw_data_manager.set_content(m, content, charset='latin-1') - self.assertEqual(str(m), textwrap.dedent("""\ + self.assertEqual(str(m), d""" Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: 7bit Simple message. - """)) + """) self.assertEqual(m.get_payload(decode=True).decode('utf-8'), content) self.assertEqual(m.get_content(), content) @@ -346,19 +346,19 @@ def test_set_text_charset_cp949(self): m = self._make_message() content = "\ud55c\uad6d\uc5b4\n\uac02\n" raw_data_manager.set_content(m, content, charset='cp949') - self.assertEqual(str(m), textwrap.dedent("""\ + self.assertEqual(str(m), d""" Content-Type: text/plain; charset="ks_c_5601-1987" Content-Transfer-Encoding: base64 x9Gxub7uCoFBCg== - """)) - self.assertEqual(bytes(m), textwrap.dedent("""\ + """) + self.assertEqual(bytes(m), d""" Content-Type: text/plain; charset="ks_c_5601-1987" Content-Transfer-Encoding: 8bit \ud55c\uad6d\uc5b4 \uac02 - """).encode('ks_c_5601-1987')) + """.encode('ks_c_5601-1987')) self.assertEqual(m.get_payload(decode=True), content.encode('ks_c_5601-1987')) self.assertEqual(m.get_content(), content) @@ -369,18 +369,18 @@ def test_set_text_charset_shift_jis(self): self.assertEqual(m['Content-Type'], 'text/plain; charset="iso-2022-jp"') self.assertEqual(m.get_payload(decode=True), content.encode('iso-2022-jp')) self.assertEqual(m.get_content(), content) - self.assertEqual(str(m), textwrap.dedent("""\ + self.assertEqual(str(m), d""" Content-Type: text/plain; charset="iso-2022-jp" Content-Transfer-Encoding: 7bit \x1b$BF|K\\8l\x1b(B - """)) - self.assertEqual(bytes(m), textwrap.dedent("""\ + """) + self.assertEqual(bytes(m), d""" Content-Type: text/plain; charset="iso-2022-jp" Content-Transfer-Encoding: 7bit \u65e5\u672c\u8a9e - """).encode('iso-2022-jp')) + """.encode('iso-2022-jp')) def test_set_text_charset_euc_jp(self): m = self._make_message() @@ -389,31 +389,31 @@ def test_set_text_charset_euc_jp(self): self.assertEqual(m['Content-Type'], 'text/plain; charset="iso-2022-jp"') self.assertEqual(m.get_payload(decode=True), content.encode('iso-2022-jp')) self.assertEqual(m.get_content(), content) - self.assertEqual(str(m), textwrap.dedent("""\ + self.assertEqual(str(m), d""" Content-Type: text/plain; charset="iso-2022-jp" Content-Transfer-Encoding: 7bit \x1b$BF|K\\8l\x1b(B - """)) - self.assertEqual(bytes(m), textwrap.dedent("""\ + """) + self.assertEqual(bytes(m), d""" Content-Type: text/plain; charset="iso-2022-jp" Content-Transfer-Encoding: 7bit \u65e5\u672c\u8a9e - """).encode('iso-2022-jp')) + """.encode('iso-2022-jp')) def test_set_text_plain_long_line_heuristics(self): m = self._make_message() content = ("Simple but long message that is over 78 characters" " long to force transfer encoding.\n") raw_data_manager.set_content(m, content) - self.assertEqual(str(m), textwrap.dedent("""\ + self.assertEqual(str(m), d""" Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable Simple but long message that is over 78 characters long to = force transfer encoding. - """)) + """) self.assertEqual(m.get_payload(decode=True).decode('utf-8'), content) self.assertEqual(m.get_content(), content) @@ -421,12 +421,12 @@ def test_set_text_short_line_minimal_non_ascii_heuristics(self): m = self._make_message() content = "et là il est monté sur moi et il commence à m'éto.\n" raw_data_manager.set_content(m, content) - self.assertEqual(bytes(m), textwrap.dedent("""\ + self.assertEqual(bytes(m), d""" Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: 8bit et là il est monté sur moi et il commence à m'éto. - """).encode('utf-8')) + """.encode('utf-8')) self.assertEqual(m.get_payload(decode=True).decode('utf-8'), content) self.assertEqual(m.get_content(), content) @@ -436,14 +436,14 @@ def test_set_text_long_line_minimal_non_ascii_heuristics(self): " vivarium. et là il est monté sur moi et il commence" " à m'éto.\n") raw_data_manager.set_content(m, content) - self.assertEqual(bytes(m), textwrap.dedent("""\ + self.assertEqual(bytes(m), d""" Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable j'ai un probl=C3=A8me de python. il est sorti de son vivari= um. et l=C3=A0 il est mont=C3=A9 sur moi et il commence = =C3=A0 m'=C3=A9to. - """).encode('utf-8')) + """.encode('utf-8')) self.assertEqual(m.get_payload(decode=True).decode('utf-8'), content) self.assertEqual(m.get_content(), content) @@ -454,10 +454,11 @@ def test_set_text_11_lines_long_line_minimal_non_ascii_heuristics(self): " vivarium. et là il est monté sur moi et il commence" " à m'éto.\n") raw_data_manager.set_content(m, content) - self.assertEqual(bytes(m), textwrap.dedent("""\ + self.assertEqual(bytes(m), (d""" Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable - """ + '\n'*10 + """ + + """ + '\n'*10 + d""" j'ai un probl=C3=A8me de python. il est sorti de son vivari= um. et l=C3=A0 il est mont=C3=A9 sur moi et il commence = =C3=A0 m'=C3=A9to. @@ -469,12 +470,12 @@ def test_set_text_maximal_non_ascii_heuristics(self): m = self._make_message() content = "áàäéèęöő.\n" raw_data_manager.set_content(m, content) - self.assertEqual(bytes(m), textwrap.dedent("""\ + self.assertEqual(bytes(m), d""" Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: 8bit áàäéèęöő. - """).encode('utf-8')) + """.encode('utf-8')) self.assertEqual(m.get_payload(decode=True).decode('utf-8'), content) self.assertEqual(m.get_content(), content) @@ -497,7 +498,7 @@ def test_set_text_long_line_maximal_non_ascii_heuristics(self): "áàäéèęöőáàäéèęöőáàäéèęöőáàäéèęöő" "áàäéèęöőáàäéèęöőáàäéèęöőáàäéèęöő.\n") raw_data_manager.set_content(m, content) - self.assertEqual(bytes(m), textwrap.dedent("""\ + self.assertEqual(bytes(m), d""" Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: base64 @@ -506,7 +507,7 @@ def test_set_text_long_line_maximal_non_ascii_heuristics(self): xJnDtsWRw6HDoMOkw6nDqMSZw7bFkcOhw6DDpMOpw6jEmcO2xZHDocOgw6TD qcOoxJnDtsWRw6HDoMOkw6nDqMSZw7bFkcOhw6DDpMOpw6jEmcO2xZHDocOg w6TDqcOoxJnDtsWRLgo= - """).encode('utf-8')) + """.encode('utf-8')) self.assertEqual(m.get_payload(decode=True).decode('utf-8'), content) self.assertEqual(m.get_content(), content) @@ -565,7 +566,7 @@ def test_set_message(self): content['Subject'] = "get back in your box" content.set_content("Or face the comfy chair.") raw_data_manager.set_content(m, content) - self.assertEqual(str(m), textwrap.dedent("""\ + self.assertEqual(str(m), d""" Subject: Forwarded message Content-Type: message/rfc822 Content-Transfer-Encoding: 8bit @@ -578,7 +579,7 @@ def test_set_message(self): MIME-Version: 1.0 Or face the comfy chair. - """)) + """) payload = m.get_payload(0) self.assertIsInstance(payload, self.message) self.assertEqual(str(payload), str(content)) @@ -595,7 +596,7 @@ def test_set_message_with_non_ascii_and_coercion_to_7bit(self): content.set_content("j'ai un problème de python. il est sorti de son" " vivarium.") raw_data_manager.set_content(m, content) - self.assertEqual(bytes(m), textwrap.dedent("""\ + self.assertEqual(bytes(m), d""" Subject: Escape report Content-Type: message/rfc822 Content-Transfer-Encoding: 8bit @@ -608,14 +609,14 @@ def test_set_message_with_non_ascii_and_coercion_to_7bit(self): MIME-Version: 1.0 j'ai un problème de python. il est sorti de son vivarium. - """).encode('utf-8')) + """.encode('utf-8')) # The choice of base64 for the body encoding is because generator # doesn't bother with heuristics and uses it unconditionally for utf-8 # text. # XXX: the first cte should be 7bit, too...that's a generator bug. # XXX: the line length in the body also looks like a generator bug. self.assertEqual(m.as_string(maxheaderlen=self.policy.max_line_length), - textwrap.dedent("""\ + d""" Subject: Escape report Content-Type: message/rfc822 Content-Transfer-Encoding: 8bit @@ -629,7 +630,7 @@ def test_set_message_with_non_ascii_and_coercion_to_7bit(self): aidhaSB1biBwcm9ibMOobWUgZGUgcHl0aG9uLiBpbCBlc3Qgc29ydGkgZGUgc29uIHZpdmFyaXVt Lgo= - """)) + """) self.assertIsInstance(m.get_content(), self.message) self.assertEqual(str(m.get_content()), str(content)) @@ -660,12 +661,12 @@ def test_set_image_jpg(self): with self.subTest(content=content): m = self._make_message() raw_data_manager.set_content(m, content, 'image', 'jpeg') - self.assertEqual(str(m), textwrap.dedent("""\ + self.assertEqual(str(m), d""" Content-Type: image/jpeg Content-Transfer-Encoding: base64 Ym9ndXMgY29udGVudA== - """)) + """) self.assertEqual(m.get_payload(decode=True), content) self.assertEqual(m.get_content(), content) @@ -681,13 +682,13 @@ def test_set_audio_aif_with_quoted_printable_cte(self): m = self._make_message() content = b'b\xFFgus\tcon\nt\rent ' + b'z'*100 m.set_content(content, 'audio', 'aif', cte='quoted-printable') - self.assertEqual(bytes(m), textwrap.dedent("""\ + self.assertEqual(bytes(m), d""" Content-Type: audio/aif Content-Transfer-Encoding: quoted-printable MIME-Version: 1.0 b=FFgus=09con=0At=0Dent=20zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz= - zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz""").encode('latin-1')) + zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz""".encode('latin-1')) self.assertEqual(m.get_payload(decode=True), content) self.assertEqual(m.get_content(), content) @@ -695,12 +696,12 @@ def test_set_video_mpeg_with_binary_cte(self): m = self._make_message() content = b'b\xFFgus\tcon\nt\rent ' + b'z'*100 m.set_content(content, 'video', 'mpeg', cte='binary') - self.assertEqual(bytes(m), textwrap.dedent("""\ + self.assertEqual(bytes(m), d""" Content-Type: video/mpeg Content-Transfer-Encoding: binary MIME-Version: 1.0 - """).encode('ascii') + + """.encode('ascii') + # XXX: the second \n ought to be a \r, but generator gets it wrong. # THIS MEANS WE DON'T ACTUALLY SUPPORT THE 'binary' CTE. b'b\xFFgus\tcon\nt\nent zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz' + @@ -714,12 +715,12 @@ def test_set_application_octet_stream_with_8bit_cte(self): m = self._make_message() content = b'b\xFFgus\tcon\nt\rent\n' + b'z'*60 + b'\n' m.set_content(content, 'application', 'octet-stream', cte='8bit') - self.assertEqual(bytes(m), textwrap.dedent("""\ + self.assertEqual(bytes(m), d""" Content-Type: application/octet-stream Content-Transfer-Encoding: 8bit MIME-Version: 1.0 - """).encode('ascii') + + """.encode('ascii') + b'b\xFFgus\tcon\nt\nent\n' + b'zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz\n') self.assertEqual(m.get_payload(decode=True), content) @@ -733,7 +734,7 @@ def test_set_headers_from_header_objects(self): header_factory("To", "foo@example.com"), header_factory("From", "foo@example.com"), header_factory("Subject", "I'm talking to myself."))) - self.assertEqual(str(m), textwrap.dedent("""\ + self.assertEqual(str(m), d""" Content-Type: text/plain; charset="utf-8" To: foo@example.com From: foo@example.com @@ -741,7 +742,7 @@ def test_set_headers_from_header_objects(self): Content-Transfer-Encoding: 7bit Simple message. - """)) + """) def test_set_headers_from_strings(self): m = self._make_message() @@ -749,14 +750,14 @@ def test_set_headers_from_strings(self): raw_data_manager.set_content(m, content, headers=( "X-Foo-Header: foo", "X-Bar-Header: bar",)) - self.assertEqual(str(m), textwrap.dedent("""\ + self.assertEqual(str(m), d""" Content-Type: text/plain; charset="utf-8" X-Foo-Header: foo X-Bar-Header: bar Content-Transfer-Encoding: 7bit Simple message. - """)) + """) def test_set_headers_with_invalid_duplicate_string_header_raises(self): m = self._make_message() @@ -826,7 +827,7 @@ def test_set_filename_and_disposition_inline(self): def test_set_non_ascii_filename(self): m = self._make_message() m.set_content('foo', filename='ábárî.txt') - self.assertEqual(bytes(m), textwrap.dedent("""\ + self.assertEqual(bytes(m), d""" Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: 7bit Content-Disposition: attachment; @@ -834,19 +835,19 @@ def test_set_non_ascii_filename(self): MIME-Version: 1.0 foo - """).encode('ascii')) + """.encode('ascii')) def test_set_content_bytes_cte_7bit(self): m = self._make_message() m.set_content(b'ASCII-only message.\n', maintype='application', subtype='octet-stream', cte='7bit') - self.assertEqual(str(m), textwrap.dedent("""\ + self.assertEqual(str(m), d""" Content-Type: application/octet-stream Content-Transfer-Encoding: 7bit MIME-Version: 1.0 ASCII-only message. - """)) + """) content_object_params = { 'text_plain': ('content', ()), diff --git a/Lib/test/test_email/test_defect_handling.py b/Lib/test/test_email/test_defect_handling.py index acc4accccac756..fd793fdff7c2e8 100644 --- a/Lib/test/test_email/test_defect_handling.py +++ b/Lib/test/test_email/test_defect_handling.py @@ -1,4 +1,3 @@ -import textwrap import unittest import contextlib from email import policy @@ -16,7 +15,7 @@ def _raise_point(self, defect): yield def test_same_boundary_inner_outer(self): - source = textwrap.dedent("""\ + source = d""" Subject: XX From: xx@xx.dk To: XX @@ -51,7 +50,7 @@ def test_same_boundary_inner_outer(self): --MS_Mac_OE_3071477847_720252_MIME_Part-- - """) + """ # XXX better would be to actually detect the duplicate. with self._raise_point(errors.StartBoundaryNotFoundDefect): msg = self._str_msg(source) @@ -63,7 +62,7 @@ def test_same_boundary_inner_outer(self): errors.StartBoundaryNotFoundDefect) def test_multipart_no_boundary(self): - source = textwrap.dedent("""\ + source = d""" Date: Fri, 6 Apr 2001 09:23:06 -0800 (GMT-0800) From: foobar Subject: broken mail @@ -80,7 +79,7 @@ def test_multipart_no_boundary(self): Header: Another part --JAB03225.986577786/zinfandel.lacita.com-- - """) + """ with self._raise_point(errors.NoBoundaryInMultipartDefect): msg = self._str_msg(source) if self.raise_expected: return @@ -91,7 +90,7 @@ def test_multipart_no_boundary(self): self.assertIsInstance(self.get_defects(msg)[1], errors.MultipartInvariantViolationDefect) - multipart_msg = textwrap.dedent("""\ + multipart_msg = d""" Date: Wed, 14 Nov 2007 12:56:23 GMT From: foo@bar.invalid To: foo@bar.invalid @@ -112,7 +111,7 @@ def test_multipart_no_boundary(self): YWJj --===============3344438784458119861==-- - """) + """ def test_multipart_invalid_cte(self): with self._raise_point( @@ -136,7 +135,7 @@ def test_multipart_valid_cte_no_defect(self): self.assertEqual(len(self.get_defects(msg)), 0, "cte="+cte) def test_lying_multipart(self): - source = textwrap.dedent("""\ + source = d""" From: "Allison Dunlap" To: yyy@example.com Subject: 64423 @@ -145,7 +144,7 @@ def test_lying_multipart(self): Content-Type: multipart/alternative; Blah blah blah - """) + """ with self._raise_point(errors.NoBoundaryInMultipartDefect): msg = self._str_msg(source) if self.raise_expected: return @@ -157,7 +156,7 @@ def test_lying_multipart(self): errors.MultipartInvariantViolationDefect) def test_missing_start_boundary(self): - source = textwrap.dedent("""\ + source = d""" Content-Type: multipart/mixed; boundary="AAA" From: Mail Delivery Subsystem To: yyy@example.com @@ -177,7 +176,7 @@ def test_missing_start_boundary(self): --AAA-- - """) + """ # The message structure is: # # multipart/mixed @@ -219,14 +218,14 @@ def test_missing_header_body_separator(self): [errors.MissingHeaderBodySeparatorDefect]) def test_bad_padding_in_base64_payload(self): - source = textwrap.dedent("""\ + source = d""" Subject: test MIME-Version: 1.0 Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: base64 dmk - """) + """ msg = self._str_msg(source) with self._raise_point(errors.InvalidBase64PaddingDefect): payload = msg.get_payload(decode=True) @@ -236,14 +235,14 @@ def test_bad_padding_in_base64_payload(self): [errors.InvalidBase64PaddingDefect]) def test_invalid_chars_in_base64_payload(self): - source = textwrap.dedent("""\ + source = d""" Subject: test MIME-Version: 1.0 Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: base64 dm\x01k=== - """) + """ msg = self._str_msg(source) with self._raise_point(errors.InvalidBase64CharactersDefect): payload = msg.get_payload(decode=True) @@ -253,14 +252,14 @@ def test_invalid_chars_in_base64_payload(self): [errors.InvalidBase64CharactersDefect]) def test_invalid_length_of_base64_payload(self): - source = textwrap.dedent("""\ + source = d""" Subject: test MIME-Version: 1.0 Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: base64 abcde - """) + """ msg = self._str_msg(source) with self._raise_point(errors.InvalidBase64LengthDefect): payload = msg.get_payload(decode=True) @@ -270,7 +269,7 @@ def test_invalid_length_of_base64_payload(self): [errors.InvalidBase64LengthDefect]) def test_missing_ending_boundary(self): - source = textwrap.dedent("""\ + source = d""" To: 1@harrydomain4.com Subject: Fwd: 1 MIME-Version: 1.0 @@ -289,7 +288,7 @@ def test_missing_ending_boundary(self): Alternative 2 - """) + """ with self._raise_point(errors.CloseBoundaryNotFoundDefect): msg = self._str_msg(source) if self.raise_expected: return diff --git a/Lib/test/test_email/test_email.py b/Lib/test/test_email/test_email.py index 19555d87085e17..1d97f147f90bed 100644 --- a/Lib/test/test_email/test_email.py +++ b/Lib/test/test_email/test_email.py @@ -6,7 +6,6 @@ import time import base64 import unittest -import textwrap from io import StringIO, BytesIO from itertools import chain @@ -317,16 +316,16 @@ def test_as_string_policy(self): self.assertEqual(fullrepr, s.getvalue()) def test_nonascii_as_string_without_cte(self): - m = textwrap.dedent("""\ + m = d""" MIME-Version: 1.0 Content-type: text/plain; charset="iso-8859-1" Test if non-ascii messages with no Content-Transfer-Encoding set can be as_string'd: Föö bär - """) + """ source = m.encode('iso-8859-1') - expected = textwrap.dedent("""\ + expected = d""" MIME-Version: 1.0 Content-type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable @@ -334,12 +333,12 @@ def test_nonascii_as_string_without_cte(self): Test if non-ascii messages with no Content-Transfer-Encoding set can be as_string'd: F=F6=F6 b=E4r - """) + """ msg = email.message_from_bytes(source) self.assertEqual(msg.as_string(), expected) def test_nonascii_as_string_with_ascii_charset(self): - m = textwrap.dedent("""\ + m = d""" MIME-Version: 1.0 Content-type: text/plain; charset="us-ascii" Content-Transfer-Encoding: 8bit @@ -347,20 +346,20 @@ def test_nonascii_as_string_with_ascii_charset(self): Test if non-ascii messages with no Content-Transfer-Encoding set can be as_string'd: Föö bär - """) + """ source = m.encode('iso-8859-1') expected = source.decode('ascii', 'replace') msg = email.message_from_bytes(source) self.assertEqual(msg.as_string(), expected) def test_nonascii_as_string_without_content_type_and_cte(self): - m = textwrap.dedent("""\ + m = d""" MIME-Version: 1.0 Test if non-ascii messages with no Content-Type nor Content-Transfer-Encoding set can be as_string'd: Föö bär - """) + """ source = m.encode('iso-8859-1') expected = source.decode('ascii', 'replace') msg = email.message_from_bytes(source) @@ -855,32 +854,32 @@ def test_unicode_header_defaults_to_utf8_encoding(self): # Issue 14291 m = MIMEText('abc\n') m['Subject'] = 'É test' - self.assertEqual(str(m),textwrap.dedent("""\ + self.assertEqual(str(m),d""" Content-Type: text/plain; charset="us-ascii" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit Subject: =?utf-8?q?=C3=89_test?= abc - """)) + """) def test_unicode_body_defaults_to_utf8_encoding(self): # Issue 14291 m = MIMEText('É testabc\n') - self.assertEqual(str(m),textwrap.dedent("""\ + self.assertEqual(str(m),d""" Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: base64 w4kgdGVzdGFiYwo= - """)) + """) def test_string_payload_with_base64_cte(self): - msg = email.message_from_string(textwrap.dedent("""\ + msg = email.message_from_string(d""" Content-Transfer-Encoding: base64 SGVsbG8uIFRlc3Rpbmc= - """), policy=email.policy.default) + """, policy=email.policy.default) self.assertEqual(msg.get_payload(decode=True), b"Hello. Testing") self.assertDefectsEqual(msg['content-transfer-encoding'].defects, []) @@ -923,34 +922,34 @@ def test_encode7or8bit(self): eq = self.assertEqual msg = MIMEText('文\n', _charset='euc-jp') eq(msg['content-transfer-encoding'], '7bit') - eq(msg.as_string(), textwrap.dedent("""\ + eq(msg.as_string(), d""" MIME-Version: 1.0 Content-Type: text/plain; charset="iso-2022-jp" Content-Transfer-Encoding: 7bit \x1b$BJ8\x1b(B - """)) + """) def test_qp_encode_latin1(self): msg = MIMEText('\xe1\xf6\n', 'text', 'ISO-8859-1') - self.assertEqual(str(msg), textwrap.dedent("""\ + self.assertEqual(str(msg), d""" MIME-Version: 1.0 Content-Type: text/text; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable =E1=F6 - """)) + """) def test_qp_encode_non_latin1(self): # Issue 16948 msg = MIMEText('\u017c\n', 'text', 'ISO-8859-2') - self.assertEqual(str(msg), textwrap.dedent("""\ + self.assertEqual(str(msg), d""" MIME-Version: 1.0 Content-Type: text/text; charset="iso-8859-2" Content-Transfer-Encoding: quoted-printable =BF - """)) + """) # Test long header wrapping @@ -1512,17 +1511,17 @@ def test_long_lines_with_different_header(self): """) def test_long_rfc2047_header_with_embedded_fws(self): - h = Header(textwrap.dedent("""\ + h = Header(d""" We're going to pretend this header is in a non-ascii character set \tto see if line wrapping with encoded words and embedded - folding white space works"""), + folding white space works""", charset='utf-8', header_name='Test') - self.assertEqual(h.encode()+'\n', textwrap.dedent("""\ + self.assertEqual(h.encode()+'\n', d""" =?utf-8?q?We=27re_going_to_pretend_this_header_is_in_a_non-ascii_chara?= =?utf-8?q?cter_set?= =?utf-8?q?_to_see_if_line_wrapping_with_encoded_words_and_embedded?= - =?utf-8?q?_folding_white_space_works?=""")+'\n') + =?utf-8?q?_folding_white_space_works?="""+'\n') @@ -1561,7 +1560,7 @@ def test_dont_mangle_from(self): def test_mangle_from_in_preamble_and_epilog(self): s = StringIO() g = Generator(s, mangle_from_=True) - msg = email.message_from_string(textwrap.dedent("""\ + msg = email.message_from_string(d""" From: foo@bar.com Mime-Version: 1.0 Content-Type: multipart/mixed; boundary=XXX @@ -1576,19 +1575,19 @@ def test_mangle_from_in_preamble_and_epilog(self): --XXX-- From somewhere unknowable - """)) + """) g.flatten(msg) self.assertEqual(len([1 for x in s.getvalue().split('\n') if x.startswith('>From ')]), 2) def test_mangled_from_with_bad_bytes(self): - source = textwrap.dedent("""\ + source = d""" Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 8bit From: aaa@bbb.org - """).encode('utf-8') + """.encode('utf-8') msg = email.message_from_bytes(source + b'From R\xc3\xb6lli\n') b = BytesIO() g = BytesGenerator(b, mangle_from_=True) @@ -1597,11 +1596,11 @@ def test_mangled_from_with_bad_bytes(self): def test_multipart_with_bad_bytes_in_cte(self): # bpo30835 - source = textwrap.dedent("""\ + source = d""" From: aperson@example.com Content-Type: multipart/mixed; boundary="1" Content-Transfer-Encoding: \xc8 - """).encode('utf-8') + """.encode('utf-8') msg = email.message_from_bytes(source) @@ -2342,31 +2341,31 @@ def test_missing_start_boundary(self): def test_string_payload_with_extra_space_after_cte(self): # https://github.com/python/cpython/issues/98188 cte = "base64 " - msg = email.message_from_string(textwrap.dedent(f"""\ + msg = email.message_from_string(fd""" Content-Transfer-Encoding: {cte} SGVsbG8uIFRlc3Rpbmc= - """), policy=email.policy.default) + """, policy=email.policy.default) self.assertEqual(msg.get_payload(decode=True), b"Hello. Testing") self.assertDefectsEqual(msg['content-transfer-encoding'].defects, []) def test_string_payload_with_extra_text_after_cte(self): - msg = email.message_from_string(textwrap.dedent("""\ + msg = email.message_from_string(d""" Content-Transfer-Encoding: base64 some text SGVsbG8uIFRlc3Rpbmc= - """), policy=email.policy.default) + """, policy=email.policy.default) self.assertEqual(msg.get_payload(decode=True), b"Hello. Testing") cte = msg['content-transfer-encoding'] self.assertDefectsEqual(cte.defects, [email.errors.InvalidHeaderDefect]) def test_string_payload_with_extra_space_after_cte_compat32(self): cte = "base64 " - msg = email.message_from_string(textwrap.dedent(f"""\ + msg = email.message_from_string(fd""" Content-Transfer-Encoding: {cte} SGVsbG8uIFRlc3Rpbmc= - """), policy=email.policy.compat32) + """, policy=email.policy.compat32) pasted_cte = msg['content-transfer-encoding'] self.assertEqual(pasted_cte, cte) self.assertEqual(msg.get_payload(decode=True), b"Hello. Testing") @@ -4127,7 +4126,7 @@ class Test8BitBytesHandling(TestEmailBase): # but it does allow us to parse and preserve them, and to decode body # parts that use an 8bit CTE. - bodytest_msg = textwrap.dedent("""\ + bodytest_msg = d""" From: foo@bar.com To: baz Mime-Version: 1.0 @@ -4135,7 +4134,7 @@ class Test8BitBytesHandling(TestEmailBase): Content-Transfer-Encoding: {cte} {bodyline} - """) + """ def test_known_8bit_CTE(self): m = self.bodytest_msg.format(charset='utf-8', @@ -4213,7 +4212,7 @@ def test_8bit_in_uuencode_body(self): '<,.V @@ -4513,7 +4509,7 @@ def test_8bit_multipart(self): --b1_76a486bee62b0d200f33dc2ca08220ad-- - """).encode('utf-8') + """.encode('utf-8') msg = email.message_from_bytes(source) s = BytesIO() g = email.generator.BytesGenerator(s) @@ -5597,13 +5593,13 @@ def test_rfc2231_get_content_charset(self): # test_headerregistry.TestContentTypeHeader.rfc2231_encoded_no_double_quotes def test_rfc2231_parse_rfc_quoting(self): - m = textwrap.dedent('''\ + m = d''' Content-Disposition: inline; \tfilename*0*=''This%20is%20even%20more%20; \tfilename*1*=%2A%2A%2Afun%2A%2A%2A%20; \tfilename*2="is it not.pdf" - ''') + ''' msg = email.message_from_string(m) self.assertEqual(msg.get_filename(), 'This is even more ***fun*** is it not.pdf') @@ -5611,13 +5607,13 @@ def test_rfc2231_parse_rfc_quoting(self): # test_headerregistry.TestContentTypeHeader.rfc2231_encoded_with_double_quotes def test_rfc2231_parse_extra_quoting(self): - m = textwrap.dedent('''\ + m = d''' Content-Disposition: inline; \tfilename*0*="''This%20is%20even%20more%20"; \tfilename*1*="%2A%2A%2Afun%2A%2A%2A%20"; \tfilename*2="is it not.pdf" - ''') + ''' msg = email.message_from_string(m) self.assertEqual(msg.get_filename(), 'This is even more ***fun*** is it not.pdf') diff --git a/Lib/test/test_email/test_generator.py b/Lib/test/test_email/test_generator.py index 8d912738029f78..531f2f5851a853 100644 --- a/Lib/test/test_email/test_generator.py +++ b/Lib/test/test_email/test_generator.py @@ -1,6 +1,5 @@ import io import re -import textwrap import unittest import random import sys @@ -28,7 +27,7 @@ def msgmaker(self, msg, policy=None): return self.msgfunc(msg, policy=policy) refold_long_expected = { - 0: textwrap.dedent("""\ + 0: d""" To: whom_it_may_concern@example.com From: nobody_you_want_to_know@example.com Subject: We the willing led by the unknowing are doing the @@ -36,8 +35,8 @@ def msgmaker(self, msg, policy=None): we are now qualified to do anything with nothing. None - """), - 40: textwrap.dedent("""\ + """, + 40: d""" To: whom_it_may_concern@example.com From: nobody_you_want_to_know@example.com @@ -48,8 +47,8 @@ def msgmaker(self, msg, policy=None): qualified to do anything with nothing. None - """), - 20: textwrap.dedent("""\ + """, + 20: d""" To: whom_it_may_concern@example.com From: @@ -67,7 +66,7 @@ def msgmaker(self, msg, policy=None): nothing. None - """), + """, } refold_long_expected[100] = refold_long_expected[0] @@ -183,12 +182,12 @@ def test_flatten_control_linesep(self): self.assertEqual(s.getvalue(), self.typ(expected)) def test_set_mangle_from_via_policy(self): - source = textwrap.dedent("""\ + source = d""" Subject: test that from is mangled in the body! From time to time I write a rhyme. - """) + """ variants = ( (None, True), (policy.compat32, True), @@ -214,21 +213,21 @@ def test_compat32_max_line_length_does_not_fold_when_none(self): def test_rfc2231_wrapping(self): # This is pretty much just to make sure we don't have an infinite # loop; I don't expect anyone to hit this in the field. - msg = self.msgmaker(self.typ(textwrap.dedent("""\ + msg = self.msgmaker(self.typ(d""" To: nobody Content-Disposition: attachment; filename="afilenamelongenoghtowraphere" None - """))) - expected = textwrap.dedent("""\ + """)) + expected = d""" To: nobody Content-Disposition: attachment; filename*0*=us-ascii''afilename; filename*1*=longenoghtowraphere None - """) + """ s = self.ioclass() g = self.genclass(s, policy=self.policy.clone(max_line_length=33)) g.flatten(msg) @@ -238,59 +237,59 @@ def test_rfc2231_wrapping_switches_to_default_len_if_too_narrow(self): # This is just to make sure we don't have an infinite loop; I don't # expect anyone to hit this in the field, so I'm not bothering to make # the result optimal (the encoding isn't needed). - msg = self.msgmaker(self.typ(textwrap.dedent("""\ + msg = self.msgmaker(self.typ(d""" To: nobody Content-Disposition: attachment; filename="afilenamelongenoghtowraphere" None - """))) - expected = textwrap.dedent("""\ + """)) + expected = d""" To: nobody Content-Disposition: attachment; filename*0*=us-ascii''afilenamelongenoghtowraphere None - """) + """ s = self.ioclass() g = self.genclass(s, policy=self.policy.clone(max_line_length=20)) g.flatten(msg) self.assertEqual(s.getvalue(), self.typ(expected)) def test_keep_encoded_newlines(self): - msg = self.msgmaker(self.typ(textwrap.dedent("""\ + msg = self.msgmaker(self.typ(d""" To: nobody Subject: Bad subject=?UTF-8?Q?=0A?=Bcc: injection@example.com None - """))) - expected = textwrap.dedent("""\ + """)) + expected = d""" To: nobody Subject: Bad subject=?UTF-8?Q?=0A?=Bcc: injection@example.com None - """) + """ s = self.ioclass() g = self.genclass(s, policy=self.policy.clone(max_line_length=80)) g.flatten(msg) self.assertEqual(s.getvalue(), self.typ(expected)) def test_keep_long_encoded_newlines(self): - msg = self.msgmaker(self.typ(textwrap.dedent("""\ + msg = self.msgmaker(self.typ(d""" To: nobody Subject: Bad subject=?UTF-8?Q?=0A?=Bcc: injection@example.com None - """))) - expected = textwrap.dedent("""\ + """)) + expected = d""" To: nobody Subject: Bad subject =?utf-8?q?=0A?=Bcc: injection@example.com None - """) + """ s = self.ioclass() g = self.genclass(s, policy=self.policy.clone(max_line_length=30)) g.flatten(msg) @@ -341,19 +340,19 @@ def test_non_ascii_addr_spec_raises(self): g.flatten(msg) def test_local_part_quoted_string_wrapped_correctly(self): - msg = self.msgmaker(self.typ(textwrap.dedent("""\ + msg = self.msgmaker(self.typ(d""" To: <"a long local part in a quoted string"@example.com> Subject: test None - """)), policy=self.policy.clone(max_line_length=20)) - expected = textwrap.dedent("""\ + """), policy=self.policy.clone(max_line_length=20)) + expected = d""" To: <"a long local part in a quoted string"@example.com> Subject: test None - """) + """ s = self.ioclass() g = self.genclass(s, policy=self.policy.clone(max_line_length=30)) g.flatten(msg) @@ -550,7 +549,7 @@ def test_cte_type_7bit_handles_unknown_8bit(self): self.assertEqual(s.getvalue(), expected) def test_cte_type_7bit_transforms_8bit_cte(self): - source = textwrap.dedent("""\ + source = d""" From: foo@bar.com To: Dinsdale Subject: Nudge nudge, wink, wink @@ -559,9 +558,9 @@ def test_cte_type_7bit_transforms_8bit_cte(self): Content-Transfer-Encoding: 8bit oh là là, know what I mean, know what I mean? - """).encode('latin1') + """.encode('latin1') msg = message_from_bytes(source) - expected = textwrap.dedent("""\ + expected = d""" From: foo@bar.com To: Dinsdale Subject: Nudge nudge, wink, wink @@ -570,7 +569,7 @@ def test_cte_type_7bit_transforms_8bit_cte(self): Content-Transfer-Encoding: quoted-printable oh l=E0 l=E0, know what I mean, know what I mean? - """).encode('ascii') + """.encode('ascii') s = io.BytesIO() g = BytesGenerator(s, policy=self.policy.clone(cte_type='7bit', linesep='\n')) @@ -583,7 +582,7 @@ def test_smtputf8_policy(self): msg['To'] = 'Dinsdale' msg['Subject'] = 'Nudge nudge, wink, wink \u1F609' msg.set_content("oh là là, know what I mean, know what I mean?") - expected = textwrap.dedent("""\ + expected = d""" From: Páolo To: Dinsdale Subject: Nudge nudge, wink, wink \u1F609 @@ -592,7 +591,7 @@ def test_smtputf8_policy(self): MIME-Version: 1.0 oh là là, know what I mean, know what I mean? - """).encode('utf-8').replace(b'\n', b'\r\n') + """.encode('utf-8').replace(b'\n', b'\r\n') s = io.BytesIO() g = BytesGenerator(s, policy=policy.SMTPUTF8) g.flatten(msg) @@ -604,7 +603,7 @@ def test_smtp_policy(self): msg["To"] = Address(addr_spec="bar@foo.com", display_name="Dinsdale") msg["Subject"] = "Nudge nudge, wink, wink" msg.set_content("oh boy, know what I mean, know what I mean?") - expected = textwrap.dedent("""\ + expected = d""" From: =?utf-8?q?P=C3=A1olo?= To: Dinsdale Subject: Nudge nudge, wink, wink @@ -613,7 +612,7 @@ def test_smtp_policy(self): MIME-Version: 1.0 oh boy, know what I mean, know what I mean? - """).encode().replace(b"\n", b"\r\n") + """.encode().replace(b"\n", b"\r\n") s = io.BytesIO() g = BytesGenerator(s, policy=policy.SMTP) g.flatten(msg) diff --git a/Lib/test/test_email/test_headerregistry.py b/Lib/test/test_email/test_headerregistry.py index aa918255d15c37..93cbd2d77e73c4 100644 --- a/Lib/test/test_email/test_headerregistry.py +++ b/Lib/test/test_email/test_headerregistry.py @@ -1,5 +1,4 @@ import datetime -import textwrap import unittest from email import errors from email import policy @@ -1725,12 +1724,12 @@ def test_unstructured_short_max_line_length(self): 'that will be folded anyway') self.assertEqual( h.fold(policy=policy.default.clone(max_line_length=20)), - textwrap.dedent("""\ + d""" Subject: this is a short header that will be folded anyway - """)) + """) def test_fold_unstructured_single_word(self): h = self.make_header('Subject', 'test') @@ -1793,21 +1792,21 @@ def test_fold_unstructured_with_commas(self): "not give a , special treatment in unstructured headers.") self.assertEqual( h.fold(policy=policy.default.clone(max_line_length=60)), - textwrap.dedent("""\ - Subject: This header is intended to demonstrate, in a fairly - succinct way, that we now do not give a , special treatment - in unstructured headers. - """)) + d""" + Subject: This header is intended to demonstrate, in a fairly + succinct way, that we now do not give a , special treatment + in unstructured headers. + """) def test_fold_address_list(self): h = self.make_header('To', '"Theodore H. Perfect" , ' '"My address is very long because my name is long" , ' '"Only A. Friend" ') - self.assertEqual(h.fold(policy=policy.default), textwrap.dedent("""\ + self.assertEqual(h.fold(policy=policy.default), d""" To: "Theodore H. Perfect" , "My address is very long because my name is long" , "Only A. Friend" - """)) + """) def test_fold_date_header(self): h = self.make_header('Date', 'Sat, 2 Feb 2002 17:00:06 -0800') diff --git a/Lib/test/test_email/test_inversion.py b/Lib/test/test_email/test_inversion.py index 7bd7f2a72067ad..9d9ace1d268068 100644 --- a/Lib/test/test_email/test_inversion.py +++ b/Lib/test/test_email/test_inversion.py @@ -1,3 +1,4 @@ +from textwrap import dedent """Test the parser and generator are inverses. Note that this is only strictly true if we are parsing RFC valid messages and diff --git a/Lib/test/test_email/test_message.py b/Lib/test/test_email/test_message.py index 56ad446694d1f8..a9a39a117387eb 100644 --- a/Lib/test/test_email/test_message.py +++ b/Lib/test/test_email/test_message.py @@ -1,4 +1,3 @@ -import textwrap import unittest from email import message_from_bytes, message_from_string, policy from email.message import EmailMessage, MIMEPart @@ -21,7 +20,7 @@ def test_error_on_setitem_if_max_count_exceeded(self): m['To'] = 'xyz@abc' def test_rfc2043_auto_decoded_and_emailmessage_used(self): - m = message_from_string(textwrap.dedent("""\ + m = message_from_string(d""" Subject: Ayons asperges pour le =?utf-8?q?d=C3=A9jeuner?= From: =?utf-8?q?Pep=C3=A9?= Le Pew To: "Penelope Pussycat" <"penelope@example.com"> @@ -29,7 +28,7 @@ def test_rfc2043_auto_decoded_and_emailmessage_used(self): Content-Type: text/plain; charset="utf-8" sample text - """), policy=policy.default) + """, policy=policy.default) self.assertEqual(m['subject'], "Ayons asperges pour le déjeuner") self.assertEqual(m['from'], "Pepé Le Pew ") self.assertIsInstance(m, EmailMessage) @@ -62,29 +61,29 @@ class TestEmailMessageBase: (None, None, 0), (), (), - textwrap.dedent("""\ + d""" To: foo@example.com simple text body - """)), + """), 'mime_non_text': ( (None, None, None), (), (), - textwrap.dedent("""\ + d""" To: foo@example.com MIME-Version: 1.0 Content-Type: image/jpg bogus body. - """)), + """), 'plain_html_alternative': ( (None, 2, 1), (), (1, 2), - textwrap.dedent("""\ + d""" To: foo@example.com MIME-Version: 1.0 Content-Type: multipart/alternative; boundary="===" @@ -101,13 +100,13 @@ class TestEmailMessageBase:

simple body

--===-- - """)), + """), 'plain_html_mixed': ( (None, 2, 1), (), (1, 2), - textwrap.dedent("""\ + d""" To: foo@example.com MIME-Version: 1.0 Content-Type: multipart/mixed; boundary="===" @@ -125,13 +124,13 @@ class TestEmailMessageBase:

simple body

--===-- - """)), + """), 'plain_html_attachment_mixed': ( (None, None, 1), (2,), (1, 2), - textwrap.dedent("""\ + d""" To: foo@example.com MIME-Version: 1.0 Content-Type: multipart/mixed; boundary="===" @@ -148,13 +147,13 @@ class TestEmailMessageBase:

simple body

--===-- - """)), + """), 'html_text_attachment_mixed': ( (None, 2, None), (1,), (1, 2), - textwrap.dedent("""\ + d""" To: foo@example.com MIME-Version: 1.0 Content-Type: multipart/mixed; boundary="===" @@ -171,13 +170,13 @@ class TestEmailMessageBase:

simple body

--===-- - """)), + """), 'html_text_attachment_inline_mixed': ( (None, 2, 1), (), (1, 2), - textwrap.dedent("""\ + d""" To: foo@example.com MIME-Version: 1.0 Content-Type: multipart/mixed; boundary="===" @@ -195,14 +194,14 @@ class TestEmailMessageBase:

simple body

--===-- - """)), + """), # RFC 2387 'related': ( (0, 1, None), (2,), (1, 2), - textwrap.dedent("""\ + d""" To: foo@example.com MIME-Version: 1.0 Content-Type: multipart/related; boundary="==="; type=text/html @@ -219,7 +218,7 @@ class TestEmailMessageBase: bogus data --===-- - """)), + """), # This message structure will probably never be seen in the wild, but # it proves we distinguish between text parts based on 'start'. The @@ -228,7 +227,7 @@ class TestEmailMessageBase: (0, 2, None), (1,), (1, 2), - textwrap.dedent("""\ + d""" To: foo@example.com MIME-Version: 1.0 Content-Type: multipart/related; boundary="==="; type=text/html; @@ -248,14 +247,14 @@ class TestEmailMessageBase: --===-- - """)), + """), 'mixed_alternative_plain_related': ( (3, 4, 2), (6, 7), (1, 6, 7), - textwrap.dedent("""\ + d""" To: foo@example.com MIME-Version: 1.0 Content-Type: multipart/mixed; boundary="===" @@ -299,7 +298,7 @@ class TestEmailMessageBase: another bogus jpg body --===-- - """)), + """), # This structure suggested by Stephen J. Turnbull...may not exist/be # supported in the wild, but we want to support it. @@ -307,7 +306,7 @@ class TestEmailMessageBase: (1, 4, 3), (6, 7), (1, 6, 7), - textwrap.dedent("""\ + d""" To: foo@example.com MIME-Version: 1.0 Content-Type: multipart/mixed; boundary="===" @@ -351,7 +350,7 @@ class TestEmailMessageBase: another bogus jpg body --===-- - """)), + """), # Same thing, but proving we only look at the root part, which is the # first one if there isn't any start parameter. That is, this is a @@ -360,7 +359,7 @@ class TestEmailMessageBase: (1, None, None), (6, 7), (1, 6, 7), - textwrap.dedent("""\ + d""" To: foo@example.com MIME-Version: 1.0 Content-Type: multipart/mixed; boundary="===" @@ -404,13 +403,13 @@ class TestEmailMessageBase: another bogus jpg body --===-- - """)), + """), 'message_rfc822': ( (None, None, None), (), (), - textwrap.dedent("""\ + d""" To: foo@example.com MIME-Version: 1.0 Content-Type: message/rfc822 @@ -419,13 +418,13 @@ class TestEmailMessageBase: From: robot@examp.com this is a message body. - """)), + """), 'mixed_text_message_rfc822': ( (None, None, 1), (2,), (1, 2), - textwrap.dedent("""\ + d""" To: foo@example.com MIME-Version: 1.0 Content-Type: multipart/mixed; boundary="===" @@ -444,7 +443,7 @@ class TestEmailMessageBase: this is a message body. --===-- - """)), + """), } @@ -1056,7 +1055,7 @@ def do_test_invalid_header_names(self, policy, setter, name, value): def test_get_body_malformed(self): """test for bpo-42892""" - msg = textwrap.dedent("""\ + msg = d""" Message-ID: <674392CA.4347091@email.au> Date: Wed, 08 Nov 2017 08:50:22 +0700 From: Foo Bar @@ -1075,7 +1074,7 @@ def test_get_body_malformed(self): Your message is ready to be sent with the following file or link attachments: XU89 - 08.11.2017 - """) + """ m = self._str_msg(msg) # In bpo-42892, this would raise # AttributeError: 'str' object has no attribute 'is_attachment' @@ -1105,11 +1104,11 @@ def test_set_content_does_not_add_MIME_Version(self): self.assertNotIn('MIME-Version', m) def test_string_payload_with_multipart_content_type(self): - msg = message_from_string(textwrap.dedent("""\ + msg = message_from_string(d""" Content-Type: multipart/mixed; charset="utf-8" sample text - """), policy=policy.default) + """, policy=policy.default) attachments = msg.iter_attachments() self.assertEqual(list(attachments), []) diff --git a/Lib/test/test_email/test_pickleable.py b/Lib/test/test_email/test_pickleable.py index 16b4467114635f..474a5c2a9b3a63 100644 --- a/Lib/test/test_email/test_pickleable.py +++ b/Lib/test/test_email/test_pickleable.py @@ -1,5 +1,4 @@ import unittest -import textwrap import copy import pickle import email @@ -45,14 +44,14 @@ class TestPickleCopyMessage(TestEmailBase): msg_params = {} # Note: there will be no custom header objects in the parsed message. - msg_params['parsed'] = (email.message_from_string(textwrap.dedent("""\ + msg_params['parsed'] = (email.message_from_string(d""" Date: Tue, 29 May 2012 09:24:26 +1000 From: frodo@mordor.net To: bilbo@underhill.org Subject: help I think I forgot the ring. - """), policy=policy.default),) + """, policy=policy.default),) msg_params['created'] = (email.message.Message(policy=policy.default),) msg_params['created'][0]['Date'] = 'Tue, 29 May 2012 09:24:26 +1000' diff --git a/Lib/test/test_email/test_policy.py b/Lib/test/test_email/test_policy.py index 90e8e5580295f9..68ca75ffbeab96 100644 --- a/Lib/test/test_email/test_policy.py +++ b/Lib/test/test_email/test_policy.py @@ -1,6 +1,5 @@ import io import types -import textwrap import unittest import email.errors import email.policy @@ -388,7 +387,7 @@ def test_parser_propagates_policy_to_message(self): self.assertIs(msg.policy, self.policy) def test_parser_propagates_policy_to_sub_messages(self): - msg = self._make_msg(textwrap.dedent("""\ + msg = self._make_msg(d""" Subject: mime test MIME-Version: 1.0 Content-Type: multipart/mixed, boundary="XXX" @@ -402,7 +401,7 @@ def test_parser_propagates_policy_to_sub_messages(self): test2 --XXX-- - """)) + """) for part in msg.walk(): self.assertIs(part.policy, self.policy) diff --git a/Lib/test/test_embed.py b/Lib/test/test_embed.py index 2d1533c46b98f3..40fda2d57456e2 100644 --- a/Lib/test/test_embed.py +++ b/Lib/test/test_embed.py @@ -497,7 +497,7 @@ def test_datetime_reset_strptime(self): self.assertEqual(out, '20000101\n' * INIT_LOOPS) def test_static_types_inherited_slots(self): - script = textwrap.dedent(""" + script = d""" import test.support results = [] for cls in test.support.iter_builtin_types(): @@ -506,7 +506,7 @@ def test_static_types_inherited_slots(self): res = (cls, attr, wrapper) results.append(res) results = ((repr(c), a, repr(w)) for c, a, w in results) - """) + """ def collate_results(raw): results = {} for cls, attr, wrapper in raw: @@ -520,12 +520,12 @@ def collate_results(raw): main_results = collate_results(ns['results']) del ns - script += textwrap.dedent(""" + script += d""" import json import sys text = json.dumps(list(results)) print(text, file=sys.stderr) - """) + """ out, err = self.run_embedded_interpreter( "test_repeated_init_exec", script, script) _results = err.split('--- Loop #')[1:] @@ -552,7 +552,7 @@ def collate_results(raw): def test_getargs_reset_static_parser(self): # Test _PyArg_Parser initializations via _PyArg_UnpackKeywords() # https://github.com/python/cpython/issues/122334 - code = textwrap.dedent(""" + code = d""" try: import _ssl except ModuleNotFoundError: @@ -568,7 +568,7 @@ def test_getargs_reset_static_parser(self): import _zoneinfo _zoneinfo.ZoneInfo.clear_cache(only_keys=['Foo/Bar']) print('3') - """) + """ out, err = self.run_embedded_interpreter("test_repeated_init_exec", code) self.assertEqual(out, '1\n2\n3\n' * INIT_LOOPS) @@ -820,7 +820,7 @@ def main_xoptions(self, xoptions_list): def _get_expected_config_impl(self): env = remove_python_envvars() - code = textwrap.dedent(''' + code = d''' import json import sys import _testinternalcapi @@ -831,7 +831,7 @@ def _get_expected_config_impl(self): data = data.encode('utf-8') sys.stdout.buffer.write(data) sys.stdout.buffer.flush() - ''') + ''' # Use -S to not import the site module: get the proper configuration # when test_embed is run from a venv (bpo-35313) @@ -2060,7 +2060,7 @@ def test_frozenmain(self): env['PYTHONUNBUFFERED'] = '1' out, err = self.run_embedded_interpreter("test_frozenmain", env=env) executable = os.path.realpath('./argv0') - expected = textwrap.dedent(f""" + expected = fd""" Frozen Hello World sys.argv ['./argv0', '-E', 'arg1', 'arg2'] config program_name: ./argv0 @@ -2068,7 +2068,7 @@ def test_frozenmain(self): config use_environment: True config configure_c_stdio: True config buffered_stdio: False - """).lstrip() + """.lstrip() self.assertEqual(out, expected) @unittest.skipUnless(support.Py_DEBUG, diff --git a/Lib/test/test_external_inspection.py b/Lib/test/test_external_inspection.py index 6b1529aa173f01..e799d628e75f2b 100644 --- a/Lib/test/test_external_inspection.py +++ b/Lib/test/test_external_inspection.py @@ -535,7 +535,7 @@ def test_self_trace_after_ctypes_import(self): import_module("_ctypes") # Run the test in a subprocess to avoid side effects - script = textwrap.dedent("""\ + script = d""" import os import _remote_debugging @@ -546,7 +546,7 @@ def test_self_trace_after_ctypes_import(self): # Should still work after _ctypes import (gh-144563) unwinder = _remote_debugging.RemoteUnwinder(os.getpid()) - """) + """ result = subprocess.run( [sys.executable, "-c", script], @@ -575,8 +575,7 @@ def test_remote_stack_trace_non_ascii_names(self): script_basename = f"mod_{latin1}_{bmp}_{astral}" port = find_unused_port() - script = textwrap.dedent( - f"""\ + script = fd""" import socket import time @@ -589,7 +588,6 @@ def {func_name}(): {func_name}() """ - ) with os_helper.temp_dir() as work_dir: script_dir = os.path.join(work_dir, "script_pkg") os.mkdir(script_dir) @@ -635,8 +633,7 @@ def {func_name}(): ) def test_async_remote_stack_trace(self): port = find_unused_port() - script = textwrap.dedent( - f"""\ + script = fd""" import asyncio import time import sys @@ -676,7 +673,6 @@ def new_eager_loop(): asyncio.run(main(), loop_factory={{TASK_FACTORY}}) """ - ) for task_factory_variant in "asyncio.new_event_loop", "new_eager_loop": with ( @@ -839,8 +835,7 @@ def new_eager_loop(): ) def test_asyncgen_remote_stack_trace(self): port = find_unused_port() - script = textwrap.dedent( - f"""\ + script = fd""" import asyncio import time import sys @@ -864,7 +859,6 @@ async def main(): asyncio.run(main()) """ - ) with os_helper.temp_dir() as work_dir: script_dir = os.path.join(work_dir, "script_pkg") @@ -920,8 +914,7 @@ async def main(): ) def test_async_gather_remote_stack_trace(self): port = find_unused_port() - script = textwrap.dedent( - f"""\ + script = fd""" import asyncio import time import sys @@ -946,7 +939,6 @@ async def main(): asyncio.run(main()) """ - ) with os_helper.temp_dir() as work_dir: script_dir = os.path.join(work_dir, "script_pkg") @@ -1038,8 +1030,7 @@ async def main(): ) def test_async_staggered_race_remote_stack_trace(self): port = find_unused_port() - script = textwrap.dedent( - f"""\ + script = fd""" import asyncio.staggered import time import sys @@ -1067,7 +1058,6 @@ async def main(): asyncio.run(main()) """ - ) with os_helper.temp_dir() as work_dir: script_dir = os.path.join(work_dir, "script_pkg") @@ -1175,8 +1165,7 @@ def test_async_global_awaited_by(self): NUM_TASKS = 100 port = find_unused_port() - script = textwrap.dedent( - f"""\ + script = fd""" import asyncio import os import random @@ -1234,7 +1223,6 @@ async def main(): asyncio.run(main()) """ - ) with os_helper.temp_dir() as work_dir: script_dir = os.path.join(work_dir, "script_pkg") @@ -2062,8 +2050,7 @@ def main_work(): ) def test_opcodes_collection(self): """Test that opcodes are collected when the opcodes flag is set.""" - script = textwrap.dedent( - """\ + script = d""" import time, sys, socket sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) @@ -2075,7 +2062,6 @@ def foo(): foo() """ - ) def get_trace_with_opcodes(pid): return RemoteUnwinder(pid, opcodes=True).get_stack_trace() @@ -2099,8 +2085,7 @@ def get_trace_with_opcodes(pid): ) def test_location_tuple_format(self): """Test that location is a 4-tuple (lineno, end_lineno, col_offset, end_col_offset).""" - script = textwrap.dedent( - """\ + script = d""" import time, sys, socket sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) @@ -2112,7 +2097,6 @@ def foo(): foo() """ - ) def get_trace_with_opcodes(pid): return RemoteUnwinder(pid, opcodes=True).get_stack_trace() @@ -2148,8 +2132,7 @@ def get_trace_with_opcodes(pid): ) def test_location_tuple_exact_values(self): """Test exact values of location tuple including column offsets.""" - script = textwrap.dedent( - """\ + script = d""" import time, sys, socket sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) @@ -2161,7 +2144,6 @@ def foo(): foo() """ - ) def get_trace_with_opcodes(pid): return RemoteUnwinder(pid, opcodes=True).get_stack_trace() @@ -2383,8 +2365,7 @@ def check_gil_status(statuses, sleeper_tid, busy_tid): ) def test_thread_status_all_mode_detection(self): port = find_unused_port() - script = textwrap.dedent( - f"""\ + script = fd""" import socket import threading import time @@ -2409,7 +2390,6 @@ def busy_thread(): t1.join() t2.join() """ - ) with os_helper.temp_dir() as tmp_dir: script_file = make_script(tmp_dir, "script", script) @@ -2507,8 +2487,7 @@ def busy_thread(): def _make_exception_test_script(self, port): """Create script with exception and normal threads for testing.""" - return textwrap.dedent( - f"""\ + return fd""" import socket import threading import time @@ -2535,7 +2514,6 @@ def normal_thread(): t1.join() t2.join() """ - ) @contextmanager def _run_exception_test_process(self): diff --git a/Lib/test/test_faulthandler.py b/Lib/test/test_faulthandler.py index 5a493a4fd95680..68c9feff9d81ad 100644 --- a/Lib/test/test_faulthandler.py +++ b/Lib/test/test_faulthandler.py @@ -9,6 +9,7 @@ from test import support from test.support import os_helper, script_helper, is_android, MS_WINDOWS, threading_helper import tempfile +import textwrap import unittest from textwrap import dedent @@ -378,7 +379,7 @@ def test_enable_without_c_stack(self): @skip_segfault_on_android def test_disable(self): - code = """ + code = d""" import faulthandler faulthandler.enable() faulthandler.disable() @@ -394,7 +395,7 @@ def test_disable(self): @skip_segfault_on_android def test_dump_ext_modules(self): # Don't filter stdlib module names: disable sys.stdlib_module_names - code = """ + code = d""" import faulthandler import sys import math @@ -414,7 +415,7 @@ def test_dump_ext_modules(self): # Ignore "math.integer" sub-module if "math" package is # in sys.stdlib_module_names - code = """ + code = d""" import faulthandler import math.integer faulthandler.enable() @@ -492,7 +493,7 @@ def check_dump_traceback(self, *, filename=None, fd=None): Explicitly call dump_traceback() function and check its output. Raise an error if the output doesn't match the expected format. """ - code = """ + code = d""" import faulthandler filename = {filename!r} @@ -550,7 +551,7 @@ def test_truncate(self): maxlen = 500 func_name = 'x' * (maxlen + 50) truncated = 'x' * maxlen + '...' - code = """ + code = d""" import faulthandler def {func_name}(): @@ -575,7 +576,7 @@ def check_dump_traceback_threads(self, filename): Call explicitly dump_traceback(all_threads=True) and check the output. Raise an error if the output doesn't match the expected format. """ - code = """ + code = d""" import faulthandler from threading import Thread, Event import time @@ -616,7 +617,7 @@ def run(self): lineno = 10 # When the traceback is dumped, the waiter thread may be in the # `self.running.set()` call or in `self.stop.wait()`. - regex = fr""" + regex = dfr""" ^{THREAD_HEADER} (?: File ".*threading.py", line [0-9]+ in [_a-z]+ ){{1,3}} File "", line (?:22|23) in run @@ -626,8 +627,7 @@ def run(self): {CURRENT_THREAD_HEADER} File "", line {lineno} in dump File "", line 28 in $ - """ - regex = dedent(regex).strip() + """.strip() self.assertRegex(output, regex) self.assertEqual(exitcode, 0) @@ -648,7 +648,7 @@ def check_dump_traceback_later(self, repeat=False, cancel=False, loops=1, Raise an error if the output doesn't match the expect format. """ timeout_str = str(datetime.timedelta(seconds=TIMEOUT)) - code = """ + code = d""" import faulthandler import time import sys @@ -728,7 +728,7 @@ def test_dump_traceback_max_threads(self): # max_threads caps the dump and writes "...\n" when truncated. # Spawn N worker threads, dump with cap < N, and verify the # marker is present and exactly CAP thread headers are written. - code = dedent(""" + code = d""" import faulthandler import sys import threading @@ -753,7 +753,7 @@ def worker(): stop.set() for t in threads: t.join() - """).strip() + """ proc = script_helper.assert_python_ok('-c', code) output = proc.err # Truncation marker is written on its own line when the cap is hit. @@ -768,7 +768,7 @@ def worker(): def test_enable_max_threads(self): # enable(max_threads=N) caps the thread dump produced when a # fatal signal fires. - code = dedent(""" + code = d""" import faulthandler import threading @@ -787,7 +787,7 @@ def worker(): ready.wait() faulthandler.enable(max_threads=CAP) faulthandler._sigsegv() - """).strip() + """ output, exitcode = self.get_output(code) output = '\n'.join(output) # Cap of 3 means the dump is truncated with "..." on its own line. @@ -807,7 +807,7 @@ def check_register(self, filename=False, all_threads=False, Raise an error if the output doesn't match the expected format. """ signum = signal.SIGUSR1 - code = """ + code = d""" import faulthandler import os import signal @@ -905,7 +905,7 @@ def test_register_chain(self): def test_register_max_threads(self): # register(max_threads=N) caps the thread dump produced when # the registered signal fires. - code = dedent(""" + code = d""" import faulthandler import signal import threading @@ -932,7 +932,7 @@ def worker(): stop.set() for t in threads: t.join() - """).strip() + """ proc = script_helper.assert_python_ok('-c', code) output = proc.err # Cap of 3 means the dump is truncated with "..." on its own line. @@ -985,12 +985,11 @@ def test_ignore_exception(self): 0xE06D7363, # MSC exception ("Emsc") 0xE0434352, # COM Callable Runtime exception ("ECCR") ): - code = f""" - import faulthandler - faulthandler.enable() - faulthandler._raise_exception({exc_code}) - """ - code = dedent(code) + code = df""" + import faulthandler + faulthandler.enable() + faulthandler._raise_exception({exc_code}) + """ output, exitcode = self.get_output(code) self.assertEqual(output, []) self.assertEqual(exitcode, exc_code) @@ -1025,13 +1024,13 @@ def test_raise_nonfatal_exception(self): @unittest.skipUnless(MS_WINDOWS, 'specific to Windows') def test_disable_windows_exc_handler(self): - code = dedent(""" + code = d""" import faulthandler faulthandler.enable() faulthandler.disable() code = faulthandler._EXCEPTION_ACCESS_VIOLATION faulthandler._raise_exception(code) - """) + """ output, exitcode = self.get_output(code) self.assertEqual(output, []) self.assertEqual(exitcode, 0xC0000005) @@ -1039,10 +1038,10 @@ def test_disable_windows_exc_handler(self): def test_cancel_later_without_dump_traceback_later(self): # bpo-37933: Calling cancel_dump_traceback_later() # without dump_traceback_later() must not segfault. - code = dedent(""" + code = d""" import faulthandler faulthandler.cancel_dump_traceback_later() - """) + """ output, exitcode = self.get_output(code) self.assertEqual(output, []) self.assertEqual(exitcode, 0) @@ -1051,7 +1050,7 @@ def test_cancel_later_without_dump_traceback_later(self): @unittest.skipUnless(support.Py_GIL_DISABLED, "only meaningful if the GIL is disabled") def test_free_threaded_dump_traceback(self): # gh-128400: Other threads need to be paused to invoke faulthandler - code = dedent(""" + code = d""" import faulthandler from threading import Thread, Event @@ -1072,7 +1071,7 @@ def run(self): faulthandler.dump_traceback(all_threads=True) waiter.stop.set() waiter.join() - """) + """ _, exitcode = self.get_output(code) self.assertEqual(exitcode, 0) @@ -1088,10 +1087,10 @@ def check_c_stack(self, output): def test_dump_c_stack(self): - code = dedent(""" + code = d""" import faulthandler faulthandler.dump_c_stack() - """) + """ output, exitcode = self.get_output(code) self.assertEqual(exitcode, 0) self.check_c_stack(output) diff --git a/Lib/test/test_frame.py b/Lib/test/test_frame.py index 18ade18d1a1708..53a43320c2b77a 100644 --- a/Lib/test/test_frame.py +++ b/Lib/test/test_frame.py @@ -2,7 +2,6 @@ import operator import re import sys -import textwrap import threading import unittest import weakref @@ -714,7 +713,7 @@ class TestIncompleteFrameAreInvisible(unittest.TestCase): def test_issue95818(self): # See GH-95818 for details - code = textwrap.dedent(f""" + code = fd""" import gc gc.set_threshold(1,1,1) @@ -731,7 +730,7 @@ def gen(): del fd del l gen() - """) + """ assert_python_ok("-c", code) @support.cpython_only diff --git a/Lib/test/test_funcattrs.py b/Lib/test/test_funcattrs.py index fe14e7cb342c9e..a8487d9e3e775e 100644 --- a/Lib/test/test_funcattrs.py +++ b/Lib/test/test_funcattrs.py @@ -1,4 +1,3 @@ -import textwrap import types import typing import unittest @@ -122,10 +121,10 @@ def func(s): return len(s) # Define functions using exec() with different builtins, # and test inheritance when globals has no "__builtins__" key - code = textwrap.dedent(""" + code = d""" def func3(s): pass func4 = type(func3)(func3.__code__, {}) - """) + """ safe_builtins = {'None': None} ns = {'type': type, '__builtins__': safe_builtins} exec(code, ns) diff --git a/Lib/test/test_future_stmt/test_future.py b/Lib/test/test_future_stmt/test_future.py index faa3a2bfe121dc..a64727727d4de8 100644 --- a/Lib/test/test_future_stmt/test_future.py +++ b/Lib/test/test_future_stmt/test_future.py @@ -5,10 +5,10 @@ import unittest from test.support import import_helper from test.support.script_helper import spawn_python, kill_python -from textwrap import dedent import os import re import sys +from textwrap import dedent TOP_LEVEL_MSG = 'from __future__ imports must occur at the beginning of the file' @@ -82,41 +82,41 @@ def test_future_multiple_features(self): from test.test_future_stmt import test_future_multiple_features # noqa: F401 def test_unknown_future_flag(self): - code = """ + code = d""" from __future__ import nested_scopes from __future__ import rested_snopes # typo error here: nested => rested - """ + """ self.assertSyntaxError( code, lineno=2, message='future feature rested_snopes is not defined', offset=24, ) def test_future_import_not_on_top(self): - code = """ + code = d""" import some_module from __future__ import annotations - """ + """ self.assertSyntaxError(code, lineno=2) - code = """ + code = d""" import __future__ from __future__ import annotations - """ + """ self.assertSyntaxError(code, lineno=2) - code = """ + code = d""" from __future__ import absolute_import "spam, bar, blah" from __future__ import print_function - """ + """ self.assertSyntaxError(code, lineno=3) def test_future_import_with_extra_string(self): - code = """ + code = d""" '''Docstring''' "this isn't a doc string" from __future__ import nested_scopes - """ + """ self.assertSyntaxError(code, lineno=3, parametrize_docstring=False) def test_multiple_import_statements_on_same_line(self): @@ -128,27 +128,27 @@ def test_multiple_import_statements_on_same_line(self): self.assertSyntaxError(code, offset=54) # Without `\`: - code = """ + code = d""" from __future__ import nested_scopes; import string; from __future__ import nested_scopes - """ + """ self.assertSyntaxError(code, offset=54) def test_future_import_star(self): - code = """ + code = d""" from __future__ import * - """ + """ self.assertSyntaxError(code, message='future feature * is not defined', offset=24) def test_future_import_braces(self): - code = """ + code = d""" from __future__ import braces - """ + """ # Congrats, you found an easter egg! self.assertSyntaxError(code, message='not a chance', offset=24) - code = """ + code = d""" from __future__ import nested_scopes, braces - """ + """ self.assertSyntaxError(code, message='not a chance', offset=39) def test_module_with_future_import_not_on_top(self): @@ -196,10 +196,10 @@ def test_future_dotted_import(self): with self.assertRaises(ImportError): exec(code) - code = """ + code = d""" from .__future__ import nested_scopes from __future__ import barry_as_FLUFL - """ + """ self.assertSyntaxError(code, lineno=2) class AnnotationsFutureTestCase(unittest.TestCase): diff --git a/Lib/test/test_gc.py b/Lib/test/test_gc.py index 3fc084ea6e9c6e..ea5b38c6a3165b 100644 --- a/Lib/test/test_gc.py +++ b/Lib/test/test_gc.py @@ -1222,7 +1222,7 @@ def test_deferred_refcount_frozen(self): # trigger this normally, but it *does* if it's inside unittest for whatever # reason. We can't call unittest from inside a test, so it has to be # in a subprocess. - source = textwrap.dedent(""" + source = d""" import gc import unittest @@ -1236,7 +1236,7 @@ def test_something(self): if __name__ == "__main__": unittest.main() - """) + """ assert_python_ok("-c", source) def test_do_not_cleanup_type_subclasses_before_finalization(self): @@ -1245,7 +1245,8 @@ def test_do_not_cleanup_type_subclasses_before_finalization(self): # the finalizer (__del__) then the line `fail = BaseNode.next.next` # should fail because we are trying to access a subclass # attribute. But subclass type cache was not properly invalidated. - code = """ + code = d""" + class BaseNode: def __del__(self): BaseNode.next = BaseNode.next.next @@ -1256,17 +1257,17 @@ class Node(BaseNode): BaseNode.next = Node() BaseNode.next.next = Node() - """ + """ # this test checks garbage collection while interp # finalization - assert_python_ok("-c", textwrap.dedent(code)) + assert_python_ok("-c", code) - code_inside_function = textwrap.dedent(F""" + code_inside_function = df""" def test(): {textwrap.indent(code, ' ')} test() - """) + """ # this test checks regular garbage collection assert_python_ok("-c", code_inside_function) @@ -1432,7 +1433,7 @@ def test_refcount_errors(self): import_module("ctypes") import subprocess - code = textwrap.dedent(''' + code = d''' from test.support import gc_collect, SuppressCrashReport a = [1, 2, 3] @@ -1453,7 +1454,7 @@ def test_refcount_errors(self): # The garbage collector should now have a fatal error # when it reaches the broken object gc_collect() - ''') + ''' p = subprocess.Popen([sys.executable, "-c", code], stdout=subprocess.PIPE, stderr=subprocess.PIPE) @@ -1684,7 +1685,7 @@ def test_ast_fini(self): # not access the type memory after deallocating the instance, since # the type memory can be freed as well. The test is also related to # _PyAST_Fini() which clears references to AST types. - code = textwrap.dedent(""" + code = d""" import ast import codecs from test import support @@ -1694,19 +1695,19 @@ def test_ast_fini(self): # Store the tree somewhere to survive until the last GC collection support.late_deletion(tree) - """) + """ assert_python_ok("-c", code) def test_warnings_fini(self): # See https://github.com/python/cpython/issues/137384 - code = textwrap.dedent(''' + code = d''' import asyncio from contextvars import ContextVar context_loop = ContextVar("context_loop", default=None) loop = asyncio.new_event_loop() context_loop.set(loop) - ''') + ''' assert_python_ok("-c", code) diff --git a/Lib/test/test_gc_stats.py b/Lib/test/test_gc_stats.py index bd75924397e76e..e8d1dbecb98dd7 100644 --- a/Lib/test/test_gc_stats.py +++ b/Lib/test/test_gc_stats.py @@ -94,7 +94,7 @@ def test_module_get_gc_stats_fields(self): def test_all_interpreters_filter_for_local_process(self): interpreters = import_helper.import_module("concurrent.interpreters") - source = """ + source = d""" import gc objects = [] obj = [] @@ -103,7 +103,7 @@ def test_all_interpreters_filter_for_local_process(self): gc.collect(0) gc.collect(1) gc.collect(2) - """ + """ interp = interpreters.create() try: interp.exec(textwrap.dedent(source)) diff --git a/Lib/test/test_gdb/test_backtrace.py b/Lib/test/test_gdb/test_backtrace.py index 714853c7b4732d..f24caa84ce786b 100644 --- a/Lib/test/test_gdb/test_backtrace.py +++ b/Lib/test/test_gdb/test_backtrace.py @@ -1,4 +1,3 @@ -import textwrap import unittest from test import support from test.support import python_is_optimized @@ -112,14 +111,14 @@ def test_gc(self): @unittest.skipIf(python_is_optimized(), "Python was compiled with optimizations") def test_wrapper_call(self): - cmd = textwrap.dedent(''' + cmd = d''' class MyList(list): def __init__(self): super(*[]).__init__() # wrapper_call() id("first break point") l = MyList() - ''') + ''' cmds_after_breakpoint = ['break wrapper_call', 'continue'] if CET_PROTECTION: # bpo-32962: same case as in get_stack_trace(): diff --git a/Lib/test/test_gdb/test_cfunction.py b/Lib/test/test_gdb/test_cfunction.py index 0a62014923e61f..c0fb830f884997 100644 --- a/Lib/test/test_gdb/test_cfunction.py +++ b/Lib/test/test_gdb/test_cfunction.py @@ -1,4 +1,3 @@ -import textwrap import unittest from test import support @@ -53,14 +52,14 @@ def check_pycfunction(self, func_name, args): ): with self.subTest(f'{obj}.{func_name}'): call = f'{obj}.{func_name}({args})' - cmd = textwrap.dedent(f''' + cmd = fd''' import _testcapi def foo(): {call} def bar(): foo() bar() - ''') + ''' if support.verbose: print(f' test call: {call}', flush=True) diff --git a/Lib/test/test_generators.py b/Lib/test/test_generators.py index 6eb25960101a9e..480c2c625ba13c 100644 --- a/Lib/test/test_generators.py +++ b/Lib/test/test_generators.py @@ -6,7 +6,6 @@ import unittest import weakref import inspect -import textwrap import types from test import support @@ -118,7 +117,7 @@ def test_generator_resurrect(self): resurrected = [] # Resurrect a generator in a finalizer - exec(textwrap.dedent(""" + exec(d""" def gen(): try: yield @@ -127,7 +126,7 @@ def gen(): g = gen() next(g) - """), {"resurrected": resurrected}) + """, {"resurrected": resurrected}) support.gc_collect() diff --git a/Lib/test/test_import/__init__.py b/Lib/test/test_import/__init__.py index 9f3df8010d3233..7acc245f193b17 100644 --- a/Lib/test/test_import/__init__.py +++ b/Lib/test/test_import/__init__.py @@ -221,7 +221,7 @@ def from_module(cls, mod): cached_id=id(cached), ) - SCRIPT = textwrap.dedent(''' + SCRIPT = d''' {imports} name = {name!r} @@ -233,11 +233,11 @@ def from_module(cls, mod): {body} {postscript} - ''') - IMPORTS = textwrap.dedent(''' + ''' + IMPORTS = d''' import sys - ''').strip() - SCRIPT_BODY = textwrap.dedent(''' + '''.strip() + SCRIPT_BODY = d''' # Capture the snapshot data. cached = sys.modules.get(name) snapshot = dict( @@ -254,11 +254,11 @@ def from_module(cls, mod): cached=None, cached_id=id(cached) if cached else None, ) - ''').strip() - CLEANUP_SCRIPT = textwrap.dedent(''' + '''.strip() + CLEANUP_SCRIPT = d''' # Clean up the module. sys.modules.pop(name, None) - ''').strip() + '''.strip() @classmethod def build_script(cls, name, *, @@ -284,11 +284,11 @@ def build_script(cls, name, *, postscript = postcleanup if import_first: - prescript += textwrap.dedent(f''' + prescript += '\n' + fd''' # Now import the module. assert name not in sys.modules - import {name}''') + import {name}'''.lstrip('\n') return cls.SCRIPT.format( imports=cls.IMPORTS.strip(), @@ -323,17 +323,17 @@ def _from_subinterp(cls, name, interpid, pipe, script_kwargs): r, w = pipe # Build the script. - postscript = textwrap.dedent(f''' + postscript = fd''' # Send the result over the pipe. import json import os os.write({w}, json.dumps(snapshot).encode()) - ''') + ''' _postscript = script_kwargs.get('postscript') if _postscript: _postscript = textwrap.dedent(_postscript).lstrip() - postscript += _postscript + postscript += '\n' + _postscript script_kwargs['postscript'] = postscript.strip() script = cls.build_script(name, **script_kwargs) @@ -661,13 +661,13 @@ def test_import_by_filename(self): def test_import_in_del_does_not_crash(self): # Issue 4236 - testfn = script_helper.make_script('', TESTFN, textwrap.dedent("""\ + testfn = script_helper.make_script('', TESTFN, d""" import sys class C: def __del__(self): import importlib sys.argv.insert(0, C()) - """)) + """) script_helper.assert_python_ok(testfn) @skip_if_dont_write_bytecode @@ -2191,7 +2191,7 @@ def pipe(self): def import_script(self, name, fd, filename=None, check_override=None): override_text = '' if check_override is not None: - override_text = f''' + override_text = fd''' import _imp _imp._override_multi_interp_extensions_check({check_override}) ''' @@ -2203,7 +2203,7 @@ def import_script(self, name, fd, filename=None, check_override=None): else: loader = "ExtensionFileLoader" - return textwrap.dedent(f''' + return fd''' from importlib.util import spec_from_loader, module_from_spec from importlib.machinery import {loader} import os, sys @@ -2218,9 +2218,9 @@ def import_script(self, name, fd, filename=None, check_override=None): else: text = 'okay' os.write({fd}, text.encode('utf-8')) - ''') + ''' else: - return textwrap.dedent(f''' + return fd''' import os, sys {override_text} try: @@ -2230,7 +2230,7 @@ def import_script(self, name, fd, filename=None, check_override=None): else: text = 'okay' os.write({fd}, text.encode('utf-8')) - ''') + ''' def run_here(self, name, filename=None, *, check_singlephase_setting=False, @@ -2522,10 +2522,10 @@ def test_isolated_config(self): @requires_singlephase_init def test_disallowed_reimport(self): # See https://github.com/python/cpython/issues/104621. - script = textwrap.dedent(''' + script = d''' import _testsinglephase print(_testsinglephase) - ''') + ''' interpid = _interpreters.create() self.addCleanup(lambda: _interpreters.destroy(interpid)) @@ -2676,7 +2676,7 @@ def from_module(cls, mod): self.init_count = mod.initialized_count() return self - SCRIPT_BODY = ModuleSnapshot.SCRIPT_BODY + textwrap.dedent(''' + SCRIPT_BODY = ModuleSnapshot.SCRIPT_BODY + '\n' + d''' snapshot['module'].update(dict( int_const=mod.int_const, str_const=mod.str_const, @@ -2690,7 +2690,7 @@ def from_module(cls, mod): has_spam=hasattr(mod, 'spam'), spam=getattr(mod, 'spam', None), )) - ''').rstrip() + '''.rstrip() @classmethod def parse(cls, text): @@ -2804,10 +2804,10 @@ def ensure_destroyed(): except _interpreters.InterpreterNotFoundError: pass self.addCleanup(ensure_destroyed) - _interpreters.exec(interpid, textwrap.dedent(''' + _interpreters.exec(interpid, d''' import sys import _testinternalcapi - ''')) + ''') def clean_up(): _interpreters.exec(interpid, textwrap.dedent(f''' name = {self.NAME!r} diff --git a/Lib/test/test_importlib/metadata/test_api.py b/Lib/test/test_importlib/metadata/test_api.py index 5449f0484492fb..bac2ab0b1845d0 100644 --- a/Lib/test/test_importlib/metadata/test_api.py +++ b/Lib/test/test_importlib/metadata/test_api.py @@ -1,6 +1,5 @@ import importlib import re -import textwrap import unittest from importlib.metadata import ( @@ -224,8 +223,7 @@ def test_requires_dist_info(self): assert "pytest; extra == 'test'" in deps def test_more_complex_deps_requires_text(self): - requires = textwrap.dedent( - """ + requires = d""" dep1 dep2 @@ -239,7 +237,6 @@ def test_more_complex_deps_requires_text(self): [extra2:python_version < "3"] dep5 """ - ) deps = sorted(Distribution._deps_from_requires_text(requires)) expected = [ 'dep1', diff --git a/Lib/test/test_importlib/test_util.py b/Lib/test/test_importlib/test_util.py index a926a7a4d408af..bb403a560bb660 100644 --- a/Lib/test/test_importlib/test_util.py +++ b/Lib/test/test_importlib/test_util.py @@ -688,21 +688,21 @@ def ensure_destroyed(): # subinterpreters in the free-threaded build @support.expected_failure_if_gil_disabled() def test_single_phase_init_module(self): - script = textwrap.dedent(''' + script = d''' from importlib.util import _incompatible_extension_module_restrictions with _incompatible_extension_module_restrictions(disable_check=True): import _testsinglephase - ''') + ''' with self.subTest('check disabled, shared GIL'): self.run_with_shared_gil(script) with self.subTest('check disabled, per-interpreter GIL'): self.run_with_own_gil(script) - script = textwrap.dedent(f''' + script = fd''' from importlib.util import _incompatible_extension_module_restrictions with _incompatible_extension_module_restrictions(disable_check=False): import _testsinglephase - ''') + ''' with self.subTest('check enabled, shared GIL'): with self.assertRaises(ImportError): self.run_with_shared_gil(script) @@ -731,23 +731,23 @@ def test_incomplete_multi_phase_init_module(self): ''') - script = prescript + textwrap.dedent(''' + script = prescript + d''' from importlib.util import _incompatible_extension_module_restrictions with _incompatible_extension_module_restrictions(disable_check=True): module = module_from_spec(spec) loader.exec_module(module) - ''') + ''' with self.subTest('check disabled, shared GIL'): self.run_with_shared_gil(script) with self.subTest('check disabled, per-interpreter GIL'): self.run_with_own_gil(script) - script = prescript + textwrap.dedent(''' + script = prescript + d''' from importlib.util import _incompatible_extension_module_restrictions with _incompatible_extension_module_restrictions(disable_check=False): module = module_from_spec(spec) loader.exec_module(module) - ''') + ''' with self.subTest('check enabled, shared GIL'): self.run_with_shared_gil(script) with self.subTest('check enabled, per-interpreter GIL'): @@ -756,21 +756,21 @@ def test_incomplete_multi_phase_init_module(self): @unittest.skipIf(_testmultiphase is None, "test requires _testmultiphase module") def test_complete_multi_phase_init_module(self): - script = textwrap.dedent(''' + script = d''' from importlib.util import _incompatible_extension_module_restrictions with _incompatible_extension_module_restrictions(disable_check=True): import _testmultiphase - ''') + ''' with self.subTest('check disabled, shared GIL'): self.run_with_shared_gil(script) with self.subTest('check disabled, per-interpreter GIL'): self.run_with_own_gil(script) - script = textwrap.dedent(f''' + script = fd''' from importlib.util import _incompatible_extension_module_restrictions with _incompatible_extension_module_restrictions(disable_check=False): import _testmultiphase - ''') + ''' with self.subTest('check enabled, shared GIL'): self.run_with_shared_gil(script) with self.subTest('check enabled, per-interpreter GIL'): diff --git a/Lib/test/test_inspect/test_inspect.py b/Lib/test/test_inspect/test_inspect.py index 7351f97fd9a4b5..bfe7215fdf9d67 100644 --- a/Lib/test/test_inspect/test_inspect.py +++ b/Lib/test/test_inspect/test_inspect.py @@ -1237,7 +1237,7 @@ def test_class_with_method_from_other_module(self): with tempfile.TemporaryDirectory() as tempdir: with open(os.path.join(tempdir, 'inspect_actual%spy' % os.extsep), 'w', encoding='utf-8') as f: - f.write(textwrap.dedent(""" + f.write(d""" import inspect_other class A: def f(self): @@ -1246,15 +1246,15 @@ class A: def f(self): pass # correct one A.f = inspect_other.A.f - """)) + """) with open(os.path.join(tempdir, 'inspect_other%spy' % os.extsep), 'w', encoding='utf-8') as f: - f.write(textwrap.dedent(""" + f.write(d""" class A: def f(self): pass - """)) + """) with DirsOnSysPath(tempdir): import inspect_actual @@ -6766,15 +6766,15 @@ def test_get_cli_details_for_aliased_module(self): class TestReload(unittest.TestCase): - src_before = textwrap.dedent("""\ -def foo(): - print("Bla") - """) + src_before = d""" + def foo(): + print("Bla") + """ - src_after = textwrap.dedent("""\ -def foo(): - print("Oh no!") - """) + src_after = d""" + def foo(): + print("Oh no!") + """ def assertInspectEqual(self, path, source): inspected_src = inspect.getsource(source) @@ -6842,14 +6842,14 @@ def run_on_interactive_mode(self, source): @unittest.skipIf(not has_subprocess_support, "test requires subprocess") def test_getsource(self): - output = self.run_on_interactive_mode(textwrap.dedent("""\ + output = self.run_on_interactive_mode(d""" def f(): print(0) return 1 + 2 import inspect print(f"The source is: <<<{inspect.getsource(f)}>>>") - """)) + """) expected = "The source is: <<>>" self.assertIn(expected, output) diff --git a/Lib/test/test_interpreters/test_lifecycle.py b/Lib/test/test_interpreters/test_lifecycle.py index 39c1441b67c133..ec3cd7f2b75f48 100644 --- a/Lib/test/test_interpreters/test_lifecycle.py +++ b/Lib/test/test_interpreters/test_lifecycle.py @@ -3,12 +3,12 @@ import os import os.path import sys -from textwrap import dedent import unittest from test import support from test.support import import_helper from test.support import os_helper +from textwrap import dedent # Raise SkipTest if subinterpreters not supported. import_helper.import_module('_interpreters') from .utils import TestBase @@ -117,7 +117,7 @@ def run_python(self, argv, *, cwd=None): def test_sys_path_0(self): # The main interpreter's sys.path[0] should be used by subinterpreters. - script = ''' + script = d''' import sys from concurrent import interpreters diff --git a/Lib/test/test_io/test_general.py b/Lib/test/test_io/test_general.py index 085ed3ea6a95ee..cc948aebbb1124 100644 --- a/Lib/test/test_io/test_general.py +++ b/Lib/test/test_io/test_general.py @@ -9,7 +9,6 @@ import os import pickle import sys -import textwrap import threading import unittest import warnings @@ -144,8 +143,7 @@ def test_invalid_operations(self): def test_startup_optimization(self): # gh-132952: Test that `io` is not imported at startup and that the # __module__ of UnsupportedOperation is set to "io". - assert_python_ok("-S", "-c", textwrap.dedent( - """ + assert_python_ok("-S", "-c", d""" import sys assert "io" not in sys.modules try: @@ -156,8 +154,7 @@ def test_startup_optimization(self): assert typ.__name__ == "UnsupportedOperation", (typ, typ.__name__) else: raise AssertionError("Expected UnsupportedOperation") - """ - )) + """) @unittest.skipUnless(hasattr(os, "pipe"), "requires os.pipe()") def test_optional_abilities(self): @@ -1266,7 +1263,7 @@ def test_check_encoding_errors(self): mod = self.io.__name__ filename = __file__ invalid = 'Boom, Shaka Laka, Boom!' - code = textwrap.dedent(f''' + code = fd''' import sys from {mod} import open, TextIOWrapper @@ -1301,7 +1298,7 @@ def test_check_encoding_errors(self): sys.exit(24) sys.exit(10) - ''') + ''' proc = assert_python_failure('-X', 'dev', '-c', code) self.assertEqual(proc.rc, 10, proc) @@ -1310,7 +1307,7 @@ def test_check_encoding_warning(self): # and sys.flags.warn_default_encoding is set. mod = self.io.__name__ filename = __file__ - code = textwrap.dedent(f'''\ + code = fd''' import sys from {mod} import open, TextIOWrapper import pathlib @@ -1319,7 +1316,7 @@ def test_check_encoding_warning(self): pass pathlib.Path({filename!r}).read_text() # line 8 - ''') + ''' proc = assert_python_ok('-X', 'warn_default_encoding', '-c', code) warnings = proc.err.splitlines() self.assertEqual(len(warnings), 2) diff --git a/Lib/test/test_json/test_indent.py b/Lib/test/test_json/test_indent.py index e07856f33cbdac..8da75cac3f3321 100644 --- a/Lib/test/test_json/test_indent.py +++ b/Lib/test/test_json/test_indent.py @@ -1,4 +1,3 @@ -import textwrap from io import StringIO from test.test_json import PyTest, CTest @@ -8,7 +7,7 @@ def test_indent(self): h = [['blorpie'], ['whoops'], [], 'd-shtaeou', 'd-nthiouh', 'i-vhbjkhnth', {'nifty': 87}, {'field': 'yes', 'morefield': False} ] - expect = textwrap.dedent("""\ + expect = d""" [ \t[ \t\t"blorpie" @@ -27,7 +26,7 @@ def test_indent(self): \t\t"field": "yes", \t\t"morefield": false \t} - ]""") + ]""" d1 = self.dumps(h) d2 = self.dumps(h, indent=2, sort_keys=True, separators=(',', ': ')) diff --git a/Lib/test/test_json/test_separators.py b/Lib/test/test_json/test_separators.py index 8ca517405179e5..bba44cc54819bc 100644 --- a/Lib/test/test_json/test_separators.py +++ b/Lib/test/test_json/test_separators.py @@ -1,4 +1,3 @@ -import textwrap from test.test_json import PyTest, CTest @@ -7,7 +6,7 @@ def test_separators(self): h = [['blorpie'], ['whoops'], [], 'd-shtaeou', 'd-nthiouh', 'i-vhbjkhnth', {'nifty': 87}, {'field': 'yes', 'morefield': False} ] - expect = textwrap.dedent("""\ + expect = d""" [ [ "blorpie" @@ -26,7 +25,7 @@ def test_separators(self): "field" : "yes" , "morefield" : false } - ]""") + ]""" d1 = self.dumps(h) diff --git a/Lib/test/test_json/test_tool.py b/Lib/test/test_json/test_tool.py index 0a96b318b15b1c..630dcc82507211 100644 --- a/Lib/test/test_json/test_tool.py +++ b/Lib/test/test_json/test_tool.py @@ -2,7 +2,6 @@ import pathlib import os import sys -import textwrap import unittest import subprocess @@ -25,7 +24,7 @@ class TestMain(unittest.TestCase): """ module = 'json' - expect_without_sort_keys = textwrap.dedent("""\ + expect_without_sort_keys = d""" [ [ "blorpie" @@ -45,9 +44,9 @@ class TestMain(unittest.TestCase): "morefield": false } ] - """) + """ - expect = textwrap.dedent("""\ + expect = d""" [ [ "blorpie" @@ -67,14 +66,14 @@ class TestMain(unittest.TestCase): "field": "yes" } ] - """) + """ - jsonlines_raw = textwrap.dedent("""\ + jsonlines_raw = d""" {"ingredients":["frog", "water", "chocolate", "glucose"]} {"ingredients":["chocolate","steel bolts"]} - """) + """ - jsonlines_expect = textwrap.dedent("""\ + jsonlines_expect = d""" { "ingredients": [ "frog", @@ -89,7 +88,7 @@ class TestMain(unittest.TestCase): "steel bolts" ] } - """) + """ @force_not_colorized def test_stdin_stdout(self): @@ -115,11 +114,11 @@ def test_infile_stdout(self): def test_non_ascii_infile(self): data = '{"msg": "\u3053\u3093\u306b\u3061\u306f"}' - expect = textwrap.dedent('''\ + expect = d''' { "msg": "\\u3053\\u3093\\u306b\\u3061\\u306f" } - ''').encode() + '''.encode() infile = self._create_infile(data) rc, out, err = assert_python_ok('-m', self.module, infile, @@ -185,12 +184,12 @@ def test_sort_keys_flag(self): @force_not_colorized def test_indent(self): input_ = '[1, 2]' - expect = textwrap.dedent('''\ + expect = d''' [ 1, 2 ] - ''') + ''' args = sys.executable, '-m', self.module, '--indent', '2' process = subprocess.run(args, input=input_, capture_output=True, text=True, check=True) self.assertEqual(process.stdout, expect) diff --git a/Lib/test/test_lazy_import/__init__.py b/Lib/test/test_lazy_import/__init__.py index 4658882243d65f..f2b9660fcd7fa9 100644 --- a/Lib/test/test_lazy_import/__init__.py +++ b/Lib/test/test_lazy_import/__init__.py @@ -97,16 +97,16 @@ def test_basic_used(self): @support.requires_subprocess() def test_from_import_with_module_getattr(self): """Lazy from import should respect module-level __getattr__.""" - code = textwrap.dedent(""" + code = d""" lazy from test.test_lazy_import.data.module_with_getattr import dynamic_attr assert dynamic_attr == "from_getattr" - """) + """ assert_python_ok("-c", code) @support.requires_subprocess() def test_from_import_with_module_getattr_raising(self): """Lazy from import should respect module-level __getattr__.""" - code = textwrap.dedent(""" + code = d""" lazy from test.test_lazy_import.data.module_with_getattr import raising_attr try: @@ -115,7 +115,7 @@ def test_from_import_with_module_getattr_raising(self): assert str(exc) == 'from_getattr', exc else: assert False, f'ValueError is not raised: {raising_attr}' - """) + """ assert_python_ok("-c", code) @support.requires_subprocess() @@ -123,7 +123,7 @@ def test_from_import_with_module_getattr_missing(self): """Lazy from import should respect module-level __getattr__.""" for attr in ("missing_attr", "import_error_attr"): with self.subTest(attr=attr): - code = textwrap.dedent(f""" + code = fd""" lazy from test.test_lazy_import.data.module_with_getattr import {attr} try: @@ -133,13 +133,13 @@ def test_from_import_with_module_getattr_missing(self): assert exc.__cause__ is not None else: assert False, ('ImportError is not raised', {attr}) - """) + """ assert_python_ok("-c", code) @support.requires_subprocess() def test_from_import_with_module_getattr_warning(self): """Lazy from import should respect module-level __getattr__.""" - code = textwrap.dedent(""" + code = d""" import warnings with warnings.catch_warnings(record=True) as log: @@ -153,18 +153,18 @@ def test_from_import_with_module_getattr_warning(self): assert len(log) == 1, log assert isinstance(log[0].message, UserWarning), log assert str(log[0].message) == 'from_getattr', log - """) + """ assert_python_ok("-c", code) @support.requires_subprocess() def test_from_import_with_imported_module_getattr(self): """Lazy from import should not shadow an imported module's __getattr__.""" - code = textwrap.dedent(""" + code = d""" import test.test_lazy_import.data.module_with_getattr as mod lazy from test.test_lazy_import.data.module_with_getattr import dynamic_attr assert dynamic_attr == "from_getattr" assert mod.dynamic_attr == "from_getattr" - """) + """ assert_python_ok("-c", code) @@ -270,10 +270,10 @@ def test_lazy_import_type_cant_construct(self): @support.requires_subprocess() def test_lazy_import_type_attributes_accessible(self): """Check that static PyLazyImport_Type is initialized at startup.""" - code = textwrap.dedent(""" + code = d""" lazy import json print(globals()["json"].resolve) - """) + """ proc = assert_python_ok("-c", code) self.assertIn(b" initial_count print("OK") - """) + """ result = subprocess.run( [sys.executable, "-c", code], capture_output=True, @@ -659,7 +659,7 @@ class ErrorHandlingTests(LazyImportTestCase): def test_import_error_shows_chained_traceback(self): """Accessing a nonexistent lazy submodule via parent attr raises AttributeError.""" - code = textwrap.dedent(""" + code = d""" import sys lazy import test.test_lazy_import.data.nonexistent_module @@ -667,7 +667,7 @@ def test_import_error_shows_chained_traceback(self): x = test.test_lazy_import.data.nonexistent_module except AttributeError as e: print("OK") - """) + """ result = subprocess.run( [sys.executable, "-c", code], capture_output=True, @@ -679,7 +679,7 @@ def test_import_error_shows_chained_traceback(self): def test_attribute_error_on_from_import_shows_chained_traceback(self): """Accessing missing attribute from lazy from-import should chain errors.""" # Tests 'lazy from module import nonexistent' behavior - code = textwrap.dedent(""" + code = d""" import sys lazy from test.test_lazy_import.data.basic2 import nonexistent_name @@ -689,7 +689,7 @@ def test_attribute_error_on_from_import_shows_chained_traceback(self): # PEP 810: Enhanced error reporting through exception chaining assert e.__cause__ is not None, "Expected chained exception" print("OK") - """) + """ result = subprocess.run( [sys.executable, "-c", code], capture_output=True, @@ -704,7 +704,7 @@ def test_reification_retries_on_failure(self): PEP 810: "If reification fails, the lazy object is not reified or replaced. Subsequent uses of the lazy object will re-try the reification." """ - code = textwrap.dedent(""" + code = d""" import sys import types @@ -725,7 +725,7 @@ def test_reification_retries_on_failure(self): x = test.test_lazy_import.data.broken_module except AttributeError: print("OK - retry worked") - """) + """ result = subprocess.run( [sys.executable, "-c", code], capture_output=True, @@ -736,7 +736,7 @@ def test_reification_retries_on_failure(self): def test_error_during_module_execution_propagates(self): """Errors in module code during reification should propagate correctly.""" - code = textwrap.dedent(""" + code = d""" import sys lazy import test.test_lazy_import.data.broken_module @@ -745,7 +745,7 @@ def test_error_during_module_execution_propagates(self): print("FAIL - should have raised") except AttributeError: print("OK") - """) + """ result = subprocess.run( [sys.executable, "-c", code], capture_output=True, @@ -760,22 +760,22 @@ def test_circular_lazy_import_does_not_crash_for_gh_144727(self): b_path = os.path.join(tmpdir, "b.py") with open(a_path, "w") as f: - f.write(textwrap.dedent("""\ + f.write(d""" lazy import b def something(): b.hello() something() - """)) + """) with open(b_path, "w") as f: - f.write(textwrap.dedent("""\ + f.write(d""" lazy import a def hello(): print(a) - """)) + """) result = subprocess.run( [sys.executable, a_path], @@ -804,7 +804,7 @@ def test_globals_returns_lazy_proxy_when_accessed_from_function(self): automatically resolves lazy imports. Inside a function, accessing globals()['name'] uses BINARY_SUBSCR which returns the lazy proxy without resolution. """ - code = textwrap.dedent(""" + code = d""" import sys import types @@ -826,7 +826,7 @@ def check_lazy(): # Module should STILL not be loaded assert 'test.test_lazy_import.data.basic2' not in sys.modules print("OK") - """) + """ result = subprocess.run( [sys.executable, "-c", code], capture_output=True, @@ -841,7 +841,7 @@ def test_globals_dict_access_returns_lazy_proxy_inline(self): Note: Assigning g['name'] to a local variable at module level triggers reification due to STORE_NAME bytecode. Inline access preserves laziness. """ - code = textwrap.dedent(""" + code = d""" import sys import types lazy import json @@ -849,7 +849,7 @@ def test_globals_dict_access_returns_lazy_proxy_inline(self): assert type(globals()['json']) is types.LazyImportType assert 'json' not in sys.modules print("OK") - """) + """ result = subprocess.run( [sys.executable, "-c", code], capture_output=True, @@ -886,7 +886,7 @@ def test_resolve_method_forces_reification(self): Note: Must access lazy proxy from within a function to avoid automatic reification by LOAD_NAME at module level. """ - code = textwrap.dedent(""" + code = d""" import sys import types @@ -908,7 +908,7 @@ def test_resolve(): assert test_resolve() print("OK") - """) + """ result = subprocess.run( [sys.executable, "-c", code], capture_output=True, @@ -918,7 +918,7 @@ def test_resolve(): self.assertIn("OK", result.stdout) def test_add_lazy_to_globals(self): - code = textwrap.dedent(""" + code = d""" import sys import types @@ -940,7 +940,7 @@ def f(): globals()["sneaky"] = globals()["basic2"] assert f() == 210 print("OK") - """) + """ result = subprocess.run( [sys.executable, "-c", code], capture_output=True, @@ -962,7 +962,7 @@ class MultipleNameFromImportTests(LazyImportTestCase): def test_accessing_one_name_leaves_others_as_proxies(self): """Accessing one name from multi-name import should leave others lazy.""" - code = textwrap.dedent(""" + code = d""" import sys import types @@ -986,7 +986,7 @@ def test_accessing_one_name_leaves_others_as_proxies(self): assert type(g['x']) is int, f"Expected int, got {type(g['x'])}" assert type(g['f']) is types.LazyImportType, f"Expected LazyImportType, got {type(g['f'])}" print("OK") - """) + """ result = subprocess.run( [sys.executable, "-c", code], capture_output=True, @@ -997,7 +997,7 @@ def test_accessing_one_name_leaves_others_as_proxies(self): def test_all_names_reified_after_all_accessed(self): """All names should be reified after each is accessed.""" - code = textwrap.dedent(""" + code = d""" import sys import types @@ -1013,7 +1013,7 @@ def test_all_names_reified_after_all_accessed(self): assert type(g['x']) is int assert callable(g['f']) print("OK") - """) + """ result = subprocess.run( [sys.executable, "-c", code], capture_output=True, @@ -1035,7 +1035,7 @@ def test_module_added_to_lazy_modules_on_lazy_import(self): # PEP 810 states lazy_modules tracks modules that have been lazily imported # Note: The current implementation keeps modules in lazy_modules even after # reification (primarily for diagnostics and introspection) - code = textwrap.dedent(""" + code = d""" import sys initial_count = len(sys.lazy_modules) @@ -1052,7 +1052,7 @@ def test_module_added_to_lazy_modules_on_lazy_import(self): # Module should still be tracked (for diagnostics per PEP 810) assert "test.test_lazy_import.data.basic2" not in sys.lazy_modules print("OK") - """) + """ result = subprocess.run( [sys.executable, "-c", code], capture_output=True, @@ -1067,14 +1067,14 @@ def test_lazy_modules_is_per_interpreter(self): self.assertIsInstance(sys.lazy_modules, set) def test_lazy_module_without_children_is_tracked(self): - code = textwrap.dedent(""" + code = d""" import sys lazy import json assert "json" in sys.lazy_modules, ( f"expected 'json' in sys.lazy_modules, got {set(sys.lazy_modules)}" ) print("OK") - """) + """ assert_python_ok("-c", code) @@ -1089,7 +1089,7 @@ class CommandLineAndEnvVarTests(unittest.TestCase): def test_cli_lazy_imports_all_makes_regular_imports_lazy(self): """-X lazy_imports=all should make all imports potentially lazy.""" - code = textwrap.dedent(""" + code = d""" import sys # In 'all' mode, regular imports become lazy import json @@ -1099,7 +1099,7 @@ def test_cli_lazy_imports_all_makes_regular_imports_lazy(self): print("LAZY") else: print("EAGER") - """) + """ result = subprocess.run( [sys.executable, "-X", "lazy_imports=all", "-c", code], capture_output=True, @@ -1123,7 +1123,7 @@ def test_cli_lazy_imports_normal_respects_lazy_keyword_only(self): """-X lazy_imports=normal should respect lazy keyword only.""" # Note: Use test modules instead of stdlib modules to avoid # modules already loaded by the interpreter startup - code = textwrap.dedent(""" + code = d""" import sys import test.test_lazy_import.data.basic2 # Should be eager lazy import test.test_lazy_import.data.pkg.b # Should be lazy @@ -1135,7 +1135,7 @@ def test_cli_lazy_imports_normal_respects_lazy_keyword_only(self): print("OK") else: print(f"FAIL: eager={eager_loaded}, lazy={lazy_loaded}") - """) + """ result = subprocess.run( [sys.executable, "-X", "lazy_imports=normal", "-c", code], capture_output=True, @@ -1146,14 +1146,14 @@ def test_cli_lazy_imports_normal_respects_lazy_keyword_only(self): def test_env_var_lazy_imports_all_enables_global_lazy(self): """PYTHON_LAZY_IMPORTS=all should enable global lazy imports.""" - code = textwrap.dedent(""" + code = d""" import sys import json if 'json' not in sys.modules: print("LAZY") else: print("EAGER") - """) + """ import os env = os.environ.copy() env["PYTHON_LAZY_IMPORTS"] = "all" @@ -1184,14 +1184,14 @@ def test_env_var_lazy_imports_none_is_rejected(self): def test_cli_overrides_env_var(self): """Command-line option should take precedence over environment variable.""" # PEP 810: -X lazy_imports takes precedence over PYTHON_LAZY_IMPORTS - code = textwrap.dedent(""" + code = d""" import sys import json if 'json' in sys.modules: print("EAGER") else: print("LAZY") - """) + """ import os env = os.environ.copy() env["PYTHON_LAZY_IMPORTS"] = "all" # env says all imports are lazy @@ -1207,7 +1207,7 @@ def test_cli_overrides_env_var(self): def test_sys_set_lazy_imports_overrides_cli(self): """sys.set_lazy_imports() should take precedence over CLI option.""" - code = textwrap.dedent(""" + code = d""" import sys sys.set_lazy_imports("normal") # Override CLI import json @@ -1215,7 +1215,7 @@ def test_sys_set_lazy_imports_overrides_cli(self): print("EAGER") else: print("LAZY") - """) + """ result = subprocess.run( [sys.executable, "-X", "lazy_imports=all", "-c", code], capture_output=True, @@ -1264,7 +1264,7 @@ def _assert_subprocess_ok(self, code, files): def test_filter_receives_correct_arguments_for_import(self): """Filter should receive (importer, name, fromlist=None) for 'import x'.""" - code = textwrap.dedent(""" + code = d""" import sys received_args = [] @@ -1283,7 +1283,7 @@ def my_filter(importer, name, fromlist): assert fromlist is None, f"Expected fromlist=None, got {fromlist!r}" assert isinstance(importer, str), f"Expected str importer, got {type(importer)}" print("OK") - """) + """ result = subprocess.run( [sys.executable, "-c", code], capture_output=True, @@ -1294,7 +1294,7 @@ def my_filter(importer, name, fromlist): def test_filter_receives_fromlist_for_from_import(self): """Filter should receive fromlist tuple for 'from x import y, z'.""" - code = textwrap.dedent(""" + code = d""" import sys received_args = [] @@ -1312,7 +1312,7 @@ def my_filter(importer, name, fromlist): assert name == "json", f"Expected name='json', got {name!r}" assert fromlist == ("dumps", "loads"), f"Expected ('dumps', 'loads'), got {fromlist!r}" print("OK") - """) + """ result = subprocess.run( [sys.executable, "-c", code], capture_output=True, @@ -1323,7 +1323,7 @@ def my_filter(importer, name, fromlist): def test_filter_returning_false_forces_eager_import(self): """Filter returning False should make import eager.""" - code = textwrap.dedent(""" + code = d""" import sys def deny_filter(importer, name, fromlist): @@ -1338,7 +1338,7 @@ def deny_filter(importer, name, fromlist): print("EAGER") else: print("LAZY") - """) + """ result = subprocess.run( [sys.executable, "-c", code], capture_output=True, @@ -1523,7 +1523,7 @@ class MixedLazyEagerImportTests(LazyImportTestCase): def test_eager_import_before_lazy_resolves_to_same_module(self): """Eager import before lazy should make lazy resolve to same module.""" - code = textwrap.dedent(""" + code = d""" import sys import json # Eager import first @@ -1532,7 +1532,7 @@ def test_eager_import_before_lazy_resolves_to_same_module(self): # lazy_json should resolve to the same object assert json is lazy_json, "Lazy and eager imports should resolve to same module" print("OK") - """) + """ result = subprocess.run( [sys.executable, "-c", code], capture_output=True, @@ -1543,7 +1543,7 @@ def test_eager_import_before_lazy_resolves_to_same_module(self): def test_lazy_import_before_eager_resolves_to_same_module(self): """Lazy import followed by eager should both point to same module.""" - code = textwrap.dedent(""" + code = d""" import sys lazy import json as lazy_json @@ -1556,7 +1556,7 @@ def test_lazy_import_before_eager_resolves_to_same_module(self): # Both should be the same object assert json is lazy_json print("OK") - """) + """ result = subprocess.run( [sys.executable, "-c", code], capture_output=True, @@ -1625,7 +1625,7 @@ class ImportStateAtReificationTests(LazyImportTestCase): def test_sys_path_at_reification_time_is_used(self): """sys.path changes after lazy import should affect reification.""" - code = textwrap.dedent(""" + code = d""" import sys import tempfile import os @@ -1654,7 +1654,7 @@ def test_sys_path_at_reification_time_is_used(self): print("OK") sys.path.remove(tmpdir) - """) + """ result = subprocess.run( [sys.executable, "-c", code], capture_output=True, @@ -1703,7 +1703,7 @@ def access_lazy_import(idx): def test_concurrent_reification_multiple_modules(self): """Multiple threads reifying different lazy imports concurrently.""" - code = textwrap.dedent(""" + code = d""" import sys import threading @@ -1742,7 +1742,7 @@ def access_modules(idx): assert all(m == 'module' for m in mods), f"Thread {idx} got: {mods}" print("OK") - """) + """ result = subprocess.run( [sys.executable, "-c", code], @@ -1754,7 +1754,7 @@ def access_modules(idx): def test_concurrent_lazy_modules_dict_updates(self): """Multiple threads creating lazy imports should safely update sys.lazy_modules.""" - code = textwrap.dedent(""" + code = d""" import sys import threading @@ -1785,7 +1785,7 @@ def create_lazy_imports(idx): assert not errors, f"Errors: {errors}" assert isinstance(sys.lazy_modules, set), "sys.lazy_modules is not a dict" print("OK") - """) + """ result = subprocess.run( [sys.executable, "-c", code], @@ -1797,7 +1797,7 @@ def create_lazy_imports(idx): def test_concurrent_reification_same_module_high_contention(self): """High contention: many threads reifying the exact same lazy import.""" - code = textwrap.dedent(""" + code = d""" import sys import threading import types @@ -1837,7 +1837,7 @@ def access_json(idx): assert all(r is first for r in results), "Inconsistent module objects" assert not isinstance(first, types.LazyImportType), "Got lazy import instead of module" print("OK") - """) + """ result = subprocess.run( [sys.executable, "-c", code], @@ -1849,7 +1849,7 @@ def access_json(idx): def test_concurrent_reification_with_module_attribute_access(self): """Threads racing to reify and immediately access module attributes.""" - code = textwrap.dedent(""" + code = d""" import sys import threading @@ -1896,7 +1896,7 @@ def stress_lazy_imports(idx): for idx, types_tuple in results.items(): assert all(t == 'module' for t in types_tuple), f"Thread {idx}: {types_tuple}" print("OK") - """) + """ result = subprocess.run( [sys.executable, "-c", code], diff --git a/Lib/test/test_list.py b/Lib/test/test_list.py index 642b54d34849da..ab8b026f0182c0 100644 --- a/Lib/test/test_list.py +++ b/Lib/test/test_list.py @@ -1,6 +1,5 @@ import signal import sys -import textwrap from test import list_tests, support from test.support import cpython_only from test.support.import_helper import import_module @@ -330,14 +329,14 @@ def test_tier2_invalidates_iterator(self): def test_no_memory(self): # gh-118331: Make sure we don't crash if list allocation fails import_module("_testcapi") - code = textwrap.dedent(""" + code = d""" import _testcapi, sys # Prime the freelist l = [None] del l _testcapi.set_nomemory(0) l = [None] - """) + """ rc, _, _ = assert_python_failure("-c", code) if support.MS_WINDOWS: # STATUS_ACCESS_VIOLATION @@ -348,7 +347,7 @@ def test_no_memory(self): def test_deopt_from_append_list(self): # gh-132011: it used to crash, because # of `CALL_LIST_APPEND` specialization failure. - code = textwrap.dedent(""" + code = d""" import _testinternalcapi l = [] @@ -362,7 +361,7 @@ def lappend(l, x, y): pass else: raise AssertionError - """) + """ rc, _, _ = assert_python_ok("-c", code) self.assertEqual(rc, 0) diff --git a/Lib/test/test_listcomps.py b/Lib/test/test_listcomps.py index cf3796d9480801..056a2dab6dc285 100644 --- a/Lib/test/test_listcomps.py +++ b/Lib/test/test_listcomps.py @@ -103,19 +103,19 @@ def _check_in_scopes(self, code, outputs=None, ns=None, scopes=None, raises=(), for scope in scopes: with self.subTest(scope=scope): if scope == "class": - newcode = textwrap.dedent(""" + newcode = d""" class _C: - {code} - """).format(code=textwrap.indent(code, " ")) + {code} + """.format(code=textwrap.indent(code, " ")) def get_output(moddict, name): return getattr(moddict["_C"], name) elif scope == "function": - newcode = textwrap.dedent(""" + newcode = d""" def _f(): - {code} + {code} return locals() _out = _f() - """).format(code=textwrap.indent(code, " ")) + """.format(code=textwrap.indent(code, " ")) def get_output(moddict, name): return moddict["_out"][name] else: @@ -133,18 +133,18 @@ def get_output(moddict, name): self.assertEqual(get_output(newns, k), v, k) def test_lambdas_with_iteration_var_as_default(self): - code = """ + code = d""" items = [(lambda i=i: i) for i in range(5)] y = [x() for x in items] - """ + """ outputs = {"y": [0, 1, 2, 3, 4]} self._check_in_scopes(code, outputs) def test_lambdas_with_free_var(self): - code = """ + code = d""" items = [(lambda: i) for i in range(5)] y = [x() for x in items] - """ + """ outputs = {"y": [4, 4, 4, 4, 4]} self._check_in_scopes(code, outputs) @@ -160,21 +160,21 @@ def method(self): self.assertIs(C().method(), C) def test_references_super(self): - code = """ + code = d""" res = [super for x in [1]] - """ + """ self._check_in_scopes(code, outputs={"res": [super]}) def test_references___class__(self): - code = """ + code = d""" res = [__class__ for x in [1]] - """ + """ self._check_in_scopes(code, raises=NameError) def test_references___class___nested(self): - code = """ + code = d""" res = [(lambda: __class__)() for _ in [1]] - """ + """ self._check_in_scopes(code, raises=NameError) def test_references___class___nested_used(self): @@ -183,27 +183,27 @@ class _C: self.assertIs(_C.res[0](), _C) def test_references___class___defined(self): - code = """ + code = d""" __class__ = 2 res = [__class__ for x in [1]] - """ + """ self._check_in_scopes( code, outputs={"res": [2]}, scopes=["module", "function"]) self._check_in_scopes(code, raises=NameError, scopes=["class"]) def test_references___class___defined_nested(self): - code = """ + code = d""" __class__ = 2 res = [(lambda: __class__)() for x in [1]] - """ + """ self._check_in_scopes( code, outputs={"res": [2]}, scopes=["module", "function"]) self._check_in_scopes(code, raises=NameError, scopes=["class"]) def test_references___classdict__(self): - code = """ + code = d""" class i: [__classdict__ for x in y] - """ + """ self._check_in_scopes(code, raises=NameError) def test_references___classdict___nested(self): @@ -212,239 +212,239 @@ class _C: self.assertIn("res", _C.res[0]) def test_references___conditional_annotations__(self): - code = """ + code = d""" class i: [__conditional_annotations__ for x in y] - """ + """ self._check_in_scopes(code, raises=NameError) def test_references___conditional_annotations___nested(self): - code = """ + code = d""" class i: [lambda: __conditional_annotations__ for x in y] - """ + """ self._check_in_scopes(code, raises=NameError) def test_references___class___enclosing(self): - code = """ + code = d""" __class__ = 2 class C: res = [__class__ for x in [1]] res = C.res - """ + """ self._check_in_scopes(code, raises=NameError) def test_super_and_class_cell_in_sibling_comps(self): - code = """ + code = d""" [super for _ in [1]] [__class__ for _ in [1]] - """ + """ self._check_in_scopes(code, raises=NameError) def test_inner_cell_shadows_outer(self): - code = """ + code = d""" items = [(lambda: i) for i in range(5)] i = 20 y = [x() for x in items] - """ + """ outputs = {"y": [4, 4, 4, 4, 4], "i": 20} self._check_in_scopes(code, outputs) def test_inner_cell_shadows_outer_no_store(self): - code = """ + code = d""" def f(x): return [lambda: x for x in range(x)], x fns, x = f(2) y = [fn() for fn in fns] - """ + """ outputs = {"y": [1, 1], "x": 2} self._check_in_scopes(code, outputs) def test_closure_can_jump_over_comp_scope(self): - code = """ + code = d""" items = [(lambda: y) for i in range(5)] y = 2 z = [x() for x in items] - """ + """ outputs = {"z": [2, 2, 2, 2, 2]} self._check_in_scopes(code, outputs, scopes=["module", "function"]) def test_cell_inner_free_outer(self): - code = """ + code = d""" def f(): return [lambda: x for x in (x, [1])[1]] x = ... y = [fn() for fn in f()] - """ + """ outputs = {"y": [1]} self._check_in_scopes(code, outputs, scopes=["module", "function"]) def test_free_inner_cell_outer(self): - code = """ + code = d""" g = 2 def f(): return g y = [g for x in [1]] - """ + """ outputs = {"y": [2]} self._check_in_scopes(code, outputs, scopes=["module", "function"]) self._check_in_scopes(code, scopes=["class"], raises=NameError) def test_inner_cell_shadows_outer_redefined(self): - code = """ + code = d""" y = 10 items = [(lambda: y) for y in range(5)] x = y y = 20 out = [z() for z in items] - """ + """ outputs = {"x": 10, "out": [4, 4, 4, 4, 4]} self._check_in_scopes(code, outputs) def test_shadows_outer_cell(self): - code = """ + code = d""" def inner(): return g [g for g in range(5)] x = inner() - """ + """ outputs = {"x": -1} self._check_in_scopes(code, outputs, ns={"g": -1}) def test_explicit_global(self): - code = """ + code = d""" global g x = g g = 2 items = [g for g in [1]] y = g - """ + """ outputs = {"x": 1, "y": 2, "items": [1]} self._check_in_scopes(code, outputs, ns={"g": 1}) def test_explicit_global_2(self): - code = """ + code = d""" global g x = g g = 2 items = [g for x in [1]] y = g - """ + """ outputs = {"x": 1, "y": 2, "items": [2]} self._check_in_scopes(code, outputs, ns={"g": 1}) def test_explicit_global_3(self): - code = """ + code = d""" global g fns = [lambda: g for g in [2]] items = [fn() for fn in fns] - """ + """ outputs = {"items": [2]} self._check_in_scopes(code, outputs, ns={"g": 1}) def test_assignment_expression(self): - code = """ + code = d""" x = -1 items = [(x:=y) for y in range(3)] - """ + """ outputs = {"x": 2} # assignment expression in comprehension is disallowed in class scope self._check_in_scopes(code, outputs, scopes=["module", "function"]) def test_free_var_in_comp_child(self): - code = """ + code = d""" lst = range(3) funcs = [lambda: x for x in lst] inc = [x + 1 for x in lst] [x for x in inc] x = funcs[0]() - """ + """ outputs = {"x": 2} self._check_in_scopes(code, outputs) def test_shadow_with_free_and_local(self): - code = """ + code = d""" lst = range(3) x = -1 funcs = [lambda: x for x in lst] items = [x + 1 for x in lst] - """ + """ outputs = {"x": -1} self._check_in_scopes(code, outputs) def test_shadow_comp_iterable_name(self): - code = """ + code = d""" x = [1] y = [x for x in x] - """ + """ outputs = {"x": [1]} self._check_in_scopes(code, outputs) def test_nested_free(self): - code = """ + code = d""" x = 1 def g(): [x for x in range(3)] return x g() - """ + """ outputs = {"x": 1} self._check_in_scopes(code, outputs, scopes=["module", "function"]) def test_introspecting_frame_locals(self): - code = """ + code = d""" import sys [i for i in range(2)] i = 20 sys._getframe().f_locals - """ + """ outputs = {"i": 20} self._check_in_scopes(code, outputs) def test_nested(self): - code = """ + code = d""" l = [2, 3] y = [[x ** 2 for x in range(x)] for x in l] - """ + """ outputs = {"y": [[0, 1], [0, 1, 4]]} self._check_in_scopes(code, outputs) def test_nested_2(self): - code = """ + code = d""" l = [1, 2, 3] x = 3 y = [x for [x ** x for x in range(x)][x - 1] in l] - """ + """ outputs = {"y": [3, 3, 3]} self._check_in_scopes(code, outputs, scopes=["module", "function"]) self._check_in_scopes(code, scopes=["class"], raises=NameError) def test_nested_3(self): - code = """ + code = d""" l = [(1, 2), (3, 4), (5, 6)] y = [x for (x, [x ** x for x in range(x)][x - 1]) in l] - """ + """ outputs = {"y": [1, 3, 5]} self._check_in_scopes(code, outputs) def test_nested_4(self): - code = """ + code = d""" items = [([lambda: x for x in range(2)], lambda: x) for x in range(3)] out = [([fn() for fn in fns], fn()) for fns, fn in items] - """ + """ outputs = {"out": [([1, 1], 2), ([1, 1], 2), ([1, 1], 2)]} self._check_in_scopes(code, outputs) def test_nameerror(self): - code = """ + code = d""" [x for x in [1]] x - """ + """ self._check_in_scopes(code, raises=NameError) def test_dunder_name(self): - code = """ + code = d""" y = [__x for __x in [1]] - """ + """ outputs = {"y": [1]} self._check_in_scopes(code, outputs) @@ -467,69 +467,69 @@ def f(): f() def test_global_outside_cellvar_inside_plus_freevar(self): - code = """ + code = d""" a = 1 def f(): func, = [(lambda: b) for b in [a]] return b, func() x = f() - """ + """ self._check_in_scopes( code, {"x": (2, 1)}, ns={"b": 2}, scopes=["function", "module"]) # inside a class, the `a = 1` assignment is not visible self._check_in_scopes(code, raises=NameError, scopes=["class"]) def test_cell_in_nested_comprehension(self): - code = """ + code = d""" a = 1 def f(): (func, inner_b), = [[lambda: b for b in c] + [b] for c in [[a]]] return b, inner_b, func() x = f() - """ + """ self._check_in_scopes( code, {"x": (2, 2, 1)}, ns={"b": 2}, scopes=["function", "module"]) # inside a class, the `a = 1` assignment is not visible self._check_in_scopes(code, raises=NameError, scopes=["class"]) def test_name_error_in_class_scope(self): - code = """ + code = d""" y = 1 [x + y for x in range(2)] - """ + """ self._check_in_scopes(code, raises=NameError, scopes=["class"]) def test_global_in_class_scope(self): - code = """ + code = d""" y = 2 vals = [(x, y) for x in range(2)] - """ + """ outputs = {"vals": [(0, 1), (1, 1)]} self._check_in_scopes(code, outputs, ns={"y": 1}, scopes=["class"]) def test_in_class_scope_inside_function_1(self): - code = """ + code = d""" class C: y = 2 vals = [(x, y) for x in range(2)] vals = C.vals - """ + """ outputs = {"vals": [(0, 1), (1, 1)]} self._check_in_scopes(code, outputs, ns={"y": 1}, scopes=["function"]) def test_in_class_scope_inside_function_2(self): - code = """ + code = d""" y = 1 class C: y = 2 vals = [(x, y) for x in range(2)] vals = C.vals - """ + """ outputs = {"vals": [(0, 1), (1, 1)]} self._check_in_scopes(code, outputs, scopes=["function"]) def test_in_class_scope_with_global(self): - code = """ + code = d""" y = 1 class C: global y @@ -539,14 +539,14 @@ class C: locals()['y'] = 3 vals = [(x, y) for x in range(2)] vals = C.vals - """ + """ outputs = {"vals": [(0, 2), (1, 2)]} self._check_in_scopes(code, outputs, scopes=["module", "class"]) outputs = {"vals": [(0, 1), (1, 1)]} self._check_in_scopes(code, outputs, scopes=["function"]) def test_in_class_scope_with_nonlocal(self): - code = """ + code = d""" y = 1 class C: nonlocal y @@ -556,76 +556,76 @@ class C: locals()['y'] = 3 vals = [(x, y) for x in range(2)] vals = C.vals - """ + """ outputs = {"vals": [(0, 2), (1, 2)]} self._check_in_scopes(code, outputs, scopes=["function"]) def test_nested_has_free_var(self): - code = """ + code = d""" items = [a for a in [1] if [a for _ in [0]]] - """ + """ outputs = {"items": [1]} self._check_in_scopes(code, outputs, scopes=["class"]) def test_nested_free_var_not_bound_in_outer_comp(self): - code = """ + code = d""" z = 1 items = [a for a in [1] if [x for x in [1] if z]] - """ + """ self._check_in_scopes(code, {"items": [1]}, scopes=["module", "function"]) self._check_in_scopes(code, {"items": []}, ns={"z": 0}, scopes=["class"]) def test_nested_free_var_in_iter(self): - code = """ + code = d""" items = [_C for _C in [1] for [0, 1][[x for x in [1] if _C][0]] in [2]] - """ + """ self._check_in_scopes(code, {"items": [1]}) def test_nested_free_var_in_expr(self): - code = """ + code = d""" items = [(_C, [x for x in [1] if _C]) for _C in [0, 1]] - """ + """ self._check_in_scopes(code, {"items": [(0, []), (1, [1])]}) def test_nested_listcomp_in_lambda(self): - code = """ + code = d""" f = [(z, lambda y: [(x, y, z) for x in [3]]) for z in [1]] (z, func), = f out = func(2) - """ + """ self._check_in_scopes(code, {"z": 1, "out": [(3, 2, 1)]}) def test_lambda_in_iter(self): - code = """ + code = d""" (func, c), = [(a, b) for b in [1] for a in [lambda : a]] d = func() assert d is func # must use "a" in this scope e = a if False else None - """ + """ self._check_in_scopes(code, {"c": 1, "e": None}) def test_assign_to_comp_iter_var_in_outer_function(self): - code = """ + code = d""" a = [1 for a in [0]] - """ + """ self._check_in_scopes(code, {"a": [1]}, scopes=["function"]) def test_no_leakage_to_locals(self): - code = """ + code = d""" def b(): [a for b in [1] for _ in []] return b, locals() r, s = b() x = r is b y = list(s.keys()) - """ + """ self._check_in_scopes(code, {"x": True, "y": []}, scopes=["module"]) self._check_in_scopes(code, {"x": True, "y": ["b"]}, scopes=["function"]) self._check_in_scopes(code, raises=NameError, scopes=["class"]) def test_iter_var_available_in_locals(self): - code = """ + code = d""" l = [1, 2] y = 0 items = [locals()["x"] for x in l] @@ -634,7 +634,7 @@ def test_iter_var_available_in_locals(self): items4 = [eval("x") for x in l] # x is available, and does not overwrite y [exec("y = x") for x in l] - """ + """ self._check_in_scopes( code, { @@ -647,7 +647,7 @@ def test_iter_var_available_in_locals(self): ) def test_comp_in_try_except(self): - template = """ + template = d""" value = ["ab"] result = snapshot = None try: @@ -655,7 +655,7 @@ def test_comp_in_try_except(self): except ValueError: snapshot = value raise - """ + """ # No exception. code = template.format(func='len') self._check_in_scopes(code, {"value": ["ab"], "result": [2], "snapshot": None}) @@ -665,14 +665,14 @@ def test_comp_in_try_except(self): raises=ValueError) def test_comp_in_try_finally(self): - template = """ + template = d""" value = ["ab"] result = snapshot = None try: result = [{func}(value) for value in value] finally: snapshot = value - """ + """ # No exception. code = template.format(func='len') self._check_in_scopes(code, {"value": ["ab"], "result": [2], "snapshot": ["ab"]}) @@ -682,25 +682,25 @@ def test_comp_in_try_finally(self): raises=ValueError) def test_exception_in_post_comp_call(self): - code = """ + code = d""" value = [1, None] try: [v for v in value].sort() except TypeError: pass - """ + """ self._check_in_scopes(code, {"value": [1, None]}) def test_frame_locals(self): - code = """ + code = d""" val = "a" in [sys._getframe().f_locals for a in [0]][0] - """ + """ import sys self._check_in_scopes(code, {"val": False}, ns={"sys": sys}) - code = """ + code = d""" val = [sys._getframe().f_locals["a"] for a in [0]][0] - """ + """ self._check_in_scopes(code, {"val": 0}, ns={"sys": sys}) def _recursive_replace(self, maybe_code): @@ -716,12 +716,12 @@ def _replacing_exec(self, code_string, ns): exec(co, ns) def test_code_replace(self): - code = """ + code = d""" x = 3 [x for x in (1, 2)] dir() y = [x] - """ + """ self._check_in_scopes(code, {"y": [3], "x": 3}) self._check_in_scopes(code, {"y": [3], "x": 3}, exec_func=self._replacing_exec) @@ -743,17 +743,17 @@ def test_code_replace_extended_arg(self): self._check_in_scopes(code, expected, exec_func=self._replacing_exec) def test_multiple_comprehension_name_reuse(self): - code = """ + code = d""" [x for x in [1]] y = [x for _ in [1]] - """ + """ self._check_in_scopes(code, {"y": [3]}, ns={"x": 3}) - code = """ + code = d""" x = 2 [x for x in [1]] y = [x for _ in [1]] - """ + """ self._check_in_scopes(code, {"x": 2, "y": [3]}, ns={"x": 3}, scopes=["class"]) self._check_in_scopes(code, {"x": 2, "y": [2]}, ns={"x": 3}, scopes=["function", "module"]) diff --git a/Lib/test/test_logging.py b/Lib/test/test_logging.py index fcd3da61a078ae..9441e6655e441c 100644 --- a/Lib/test/test_logging.py +++ b/Lib/test/test_logging.py @@ -1806,7 +1806,7 @@ def test_exception_if_config_file_does_not_exist(self): def test_defaults_do_no_interpolation(self): """bpo-33802 defaults should not get interpolated""" - ini = textwrap.dedent(""" + ini = d""" [formatters] keys=default @@ -1825,7 +1825,7 @@ def test_defaults_do_no_interpolation(self): [logger_root] formatter=default handlers=console - """).strip() + """.strip() fd, fn = tempfile.mkstemp(prefix='test_logging_', suffix='.ini') try: os.write(fd, ini.encode('ascii')) @@ -4936,7 +4936,7 @@ def test_relativeCreated_has_higher_precision(self): # references leak). start_ns = 1_677_903_920_000_998_503 # approx. 2023-03-04 04:25:20 UTC offsets_ns = (200, 500, 12_354, 99_999, 1_677_903_456_999_123_456) - code = textwrap.dedent(f""" + code = fd""" start_ns = {start_ns!r} offsets_ns = {offsets_ns!r} start_monotonic_ns = start_ns - 1 @@ -4967,7 +4967,7 @@ def test_relativeCreated_has_higher_precision(self): time.time = old_time time.monotonic_ns = old_monotonic_ns time.monotonic = old_monotonic - """) + """ rc, out, err = assert_python_ok("-c", code) out = out.decode() for offset_ns, line in zip(offsets_ns, out.splitlines(), strict=True): @@ -5303,7 +5303,7 @@ def __init__(self, name='MyLogger', level=logging.NOTSET): def test_logging_at_shutdown(self): # bpo-20037: Doing text I/O late at interpreter shutdown must not crash - code = textwrap.dedent(""" + code = d""" import logging class A: @@ -5314,7 +5314,7 @@ def __del__(self): logging.exception("exception in __del__") a = A() - """) + """ rc, out, err = assert_python_ok("-c", code) err = err.decode() self.assertIn("exception in __del__", err) @@ -5327,7 +5327,7 @@ def test_logging_at_shutdown_open(self): filename = os_helper.TESTFN self.addCleanup(os_helper.unlink, filename) - code = textwrap.dedent(f""" + code = fd""" import builtins import logging @@ -5345,7 +5345,7 @@ def __del__(self): # Simulate the Python finalization which removes the builtin # open() function. del builtins.open - """) + """ assert_python_ok("-c", code) with open(filename, encoding="utf-8") as fp: @@ -5353,7 +5353,7 @@ def __del__(self): def test_recursion_error(self): # Issue 36272 - code = textwrap.dedent(""" + code = d""" import logging def rec(): @@ -5361,7 +5361,7 @@ def rec(): rec() rec() - """) + """ rc, out, err = assert_python_failure("-c", code) err = err.decode() self.assertNotIn("Cannot recover from stack overflow.", err) diff --git a/Lib/test/test_mailbox.py b/Lib/test/test_mailbox.py index 019c699bff55c4..3645466f4ae11f 100644 --- a/Lib/test/test_mailbox.py +++ b/Lib/test/test_mailbox.py @@ -14,7 +14,6 @@ from test.support import requires_root_user from test.support import socket_helper import unittest -import textwrap import mailbox import glob @@ -90,12 +89,12 @@ def test_add(self): for i in (1, 2, 3, 4, 5, 6): self._check_sample(self._box[keys[i]]) - _nonascii_msg = textwrap.dedent("""\ + _nonascii_msg = d""" From: foo Subject: Falinaptár házhozszállítással. Már rendeltél? 0 - """) + """ def test_add_invalid_8bit_bytes_header(self): key = self._box.add(self._nonascii_msg.encode('latin-1')) @@ -130,7 +129,7 @@ def raiser(*args, **kw): self._box.close() self.assertMailboxEmpty() - _non_latin_bin_msg = textwrap.dedent("""\ + _non_latin_bin_msg = d""" From: foo@bar.com To: báz Subject: Maintenant je vous présente mon collègue, le pouf célèbre @@ -140,7 +139,7 @@ def raiser(*args, **kw): Content-Transfer-Encoding: 8bit Да, они летят. - """).encode('utf-8') + """.encode('utf-8') def test_add_8bit_body(self): key = self._box.add(self._non_latin_bin_msg) diff --git a/Lib/test/test_marshal.py b/Lib/test/test_marshal.py index 9c4d91c456dc5d..9e7d7bdb00d34b 100644 --- a/Lib/test/test_marshal.py +++ b/Lib/test/test_marshal.py @@ -8,7 +8,6 @@ import unittest import os import types -import textwrap try: import _testcapi @@ -171,7 +170,7 @@ def test_minimal_linetable_with_no_debug_ranges(self): # Make sure when demarshalling objects with `-X no_debug_ranges` # that the columns are None. co = ExceptionTestCase.test_exceptions.__code__ - code = textwrap.dedent(""" + code = d""" import sys import marshal with open(sys.argv[1], 'rb') as f: @@ -179,7 +178,7 @@ def test_minimal_linetable_with_no_debug_ranges(self): positions = list(co.co_positions()) assert positions[0][2] is None assert positions[0][3] is None - """) + """ try: with open(os_helper.TESTFN, 'wb') as f: diff --git a/Lib/test/test_mmap.py b/Lib/test/test_mmap.py index 2e2ac147968dd4..8b4af4226b735f 100644 --- a/Lib/test/test_mmap.py +++ b/Lib/test/test_mmap.py @@ -15,7 +15,6 @@ import socket import string import sys -import textwrap import weakref # Skip test if we can't import mmap. @@ -1087,7 +1086,7 @@ def __exit__(self, exc_type, exc_value, traceback): def test_access_violations(self): from test.support.os_helper import TESTFN - code = textwrap.dedent(""" + code = d""" import faulthandler import mmap import os @@ -1151,7 +1150,7 @@ def test_access_violations(self): with suppress(OSError): m.rfind(b'A') assert False, 'mmap.rfind() did not raise' - """) + """ rt, stdout, stderr = assert_python_ok("-c", code, TESTFN) self.assertEqual(stdout.strip(), b'') self.assertEqual(stderr.strip(), b'') diff --git a/Lib/test/test_monitoring.py b/Lib/test/test_monitoring.py index b8861d09e1564b..32aade9cf46b2b 100644 --- a/Lib/test/test_monitoring.py +++ b/Lib/test/test_monitoring.py @@ -2200,7 +2200,7 @@ def _has_load_super_attr(self, co): return has def _super_method_call(self, optimized=False): - codestr = """ + codestr = d""" class A: def method(self, x): return x @@ -2215,7 +2215,7 @@ def method(self, x): b = B() def f(): return b.method(1) - """ + """ d = self._exec_super(codestr, optimized) expected = [ ('line', 'get_events', 10), @@ -2244,7 +2244,7 @@ def test_method_call(self): self.check_events(opt_func, recorders=self.RECORDERS, expected=opt_expected) def _super_method_call_error(self, optimized=False): - codestr = """ + codestr = d""" class A: def method(self, x): return x @@ -2266,7 +2266,7 @@ def f(): pass else: assert False, "should have raised TypeError" - """ + """ d = self._exec_super(codestr, optimized) expected = [ ('line', 'get_events', 10), @@ -2295,7 +2295,7 @@ def test_method_call_error(self): self.check_events(opt_func, recorders=self.RECORDERS, expected=opt_expected) def _super_attr(self, optimized=False): - codestr = """ + codestr = d""" class A: x = 1 @@ -2307,7 +2307,7 @@ def method(self): b = B() def f(): return b.method() - """ + """ d = self._exec_super(codestr, optimized) expected = [ ('line', 'get_events', 10), @@ -2332,14 +2332,14 @@ def test_attr(self): self.check_events(opt_func, recorders=self.RECORDERS, expected=opt_expected) def test_vs_other_type_call(self): - code_template = textwrap.dedent(""" + code_template = d""" class C: def method(self): return {cls}().__repr__{call} c = C() def f(): return c.method() - """) + """ def get_expected(name, call_method, ns): repr_arg = 0 if name == "int" else sys.monitoring.MISSING diff --git a/Lib/test/test_multibytecodec.py b/Lib/test/test_multibytecodec.py index d7a233377bdb02..4dff008438b0e6 100644 --- a/Lib/test/test_multibytecodec.py +++ b/Lib/test/test_multibytecodec.py @@ -7,7 +7,6 @@ import codecs import io import sys -import textwrap import unittest from test import support from test.support import os_helper @@ -216,7 +215,7 @@ def test_subinterp(self): _testcapi = import_module("_testcapi") encoding = 'cp932' text = "Python の開発は、1990 年ごろから開始されています。" - code = textwrap.dedent(""" + code = d""" import codecs encoding = %r text = %r @@ -224,7 +223,7 @@ def test_subinterp(self): text2 = encoder.encode(text).decode(encoding) if text2 != text: raise ValueError(f"encoding issue: {text2!a} != {text!a}") - """) % (encoding, text) + """ % (encoding, text) res = _testcapi.run_in_subinterp(code) self.assertEqual(res, 0) diff --git a/Lib/test/test_optparse.py b/Lib/test/test_optparse.py index fc8ef9520b3c0f..bdc24e1fd7cf54 100644 --- a/Lib/test/test_optparse.py +++ b/Lib/test/test_optparse.py @@ -542,10 +542,12 @@ def test_default_progname(self): self.assertUsage(parser, expected_usage) self.assertVersion(parser, "baz.py 1.2") self.assertHelp(parser, - expected_usage + "\n" + - "Options:\n" - " --version show program's version number and exit\n" - " -h, --help show this help message and exit\n") + expected_usage + d""" + + Options: + --version show program's version number and exit + -h, --help show this help message and exit + """) finally: sys.argv[:] = save_argv diff --git a/Lib/test/test_os/test_os.py b/Lib/test/test_os/test_os.py index b88388e091312a..71b83e42a7dcdf 100644 --- a/Lib/test/test_os/test_os.py +++ b/Lib/test/test_os/test_os.py @@ -23,7 +23,6 @@ import sys import sysconfig import tempfile -import textwrap import time import types import unittest @@ -4716,7 +4715,7 @@ def test_pipe_spawnl(self): self.addCleanup(os.close, fd) self.addCleanup(os.close, fd2) - code = textwrap.dedent(f""" + code = fd""" import errno import os import test.support @@ -4747,7 +4746,7 @@ def test_pipe_spawnl(self): else: os.close(fd3) raise Exception("dup must fail") - """) + """ filename = os_helper.TESTFN self.addCleanup(os_helper.unlink, os_helper.TESTFN) diff --git a/Lib/test/test_os/test_posix.py b/Lib/test/test_os/test_posix.py index 8e83fa21dae6e2..aebc51551efb71 100644 --- a/Lib/test/test_os/test_posix.py +++ b/Lib/test/test_os/test_posix.py @@ -2062,9 +2062,9 @@ def test_setpgroup_wrong_type(self): @unittest.skipUnless(hasattr(signal, 'pthread_sigmask'), 'need signal.pthread_sigmask()') def test_setsigmask(self): - code = textwrap.dedent("""\ + code = d""" import signal - signal.raise_signal(signal.SIGUSR1)""") + signal.raise_signal(signal.SIGUSR1)""" pid = self.spawn_func( sys.executable, @@ -2095,12 +2095,12 @@ def test_setsid(self): try: os.set_inheritable(wfd, True) - code = textwrap.dedent(f""" + code = fd""" import os fd = {wfd} sid = os.getsid(0) os.write(fd, str(sid).encode()) - """) + """ try: pid = self.spawn_func(sys.executable, @@ -2124,9 +2124,9 @@ def test_setsid(self): 'need signal.pthread_sigmask()') def test_setsigdef(self): original_handler = signal.signal(signal.SIGUSR1, signal.SIG_IGN) - code = textwrap.dedent("""\ + code = d""" import signal - signal.raise_signal(signal.SIGUSR1)""") + signal.raise_signal(signal.SIGUSR1)""" try: pid = self.spawn_func( sys.executable, @@ -2173,12 +2173,12 @@ def test_scheduler_wrong_type(self, scheduler): def test_setscheduler_only_param(self): policy = os.sched_getscheduler(0) priority = os.sched_get_priority_min(policy) - code = textwrap.dedent(f"""\ + code = fd""" import os, sys if os.sched_getscheduler(0) != {policy}: sys.exit(101) if os.sched_getparam(0).sched_priority != {priority}: - sys.exit(102)""") + sys.exit(102)""" pid = self.spawn_func( sys.executable, [sys.executable, '-c', code], @@ -2199,12 +2199,12 @@ def test_setscheduler_only_param(self): def test_setscheduler_with_policy(self): policy = os.sched_getscheduler(0) priority = os.sched_get_priority_min(policy) - code = textwrap.dedent(f"""\ + code = fd""" import os, sys if os.sched_getscheduler(0) != {policy}: sys.exit(101) if os.sched_getparam(0).sched_priority != {priority}: - sys.exit(102)""") + sys.exit(102)""" pid = self.spawn_func( sys.executable, [sys.executable, '-c', code], diff --git a/Lib/test/test_os/test_windows.py b/Lib/test/test_os/test_windows.py index f1c6283f60d35e..5f0ef5621edb80 100644 --- a/Lib/test/test_os/test_windows.py +++ b/Lib/test/test_os/test_windows.py @@ -12,7 +12,6 @@ import signal import stat import subprocess -import textwrap import time import uuid from test import support @@ -511,7 +510,7 @@ def test_stat_unlink_race(self): filename = os_helper.TESTFN self.addCleanup(os_helper.unlink, filename) deadline = time.time() + 5 - command = textwrap.dedent("""\ + command = d""" import os import sys import time @@ -529,7 +528,7 @@ def test_stat_unlink_race(self): os.remove(filename) except OSError: pass - """) + """ with subprocess.Popen([sys.executable, '-c', command, filename, str(deadline)]) as proc: while time.time() < deadline: diff --git a/Lib/test/test_peepholer.py b/Lib/test/test_peepholer.py index 28748009f731bc..a3ecebd2f50e46 100644 --- a/Lib/test/test_peepholer.py +++ b/Lib/test/test_peepholer.py @@ -17,14 +17,12 @@ def compile_pattern_with_fast_locals(pattern): - source = textwrap.dedent( - f""" + source = fd""" def f(x): match x: case {pattern}: pass """ - ) namespace = {} exec(source, namespace) return namespace["f"].__code__ @@ -980,7 +978,7 @@ def f(): self.assertInBytecode(f, 'LOAD_FAST_BORROW', "a73") def test_setting_lineno_no_undefined(self): - code = textwrap.dedent("""\ + code = d""" def f(): x = y = 2 if not x: @@ -991,7 +989,7 @@ def f(): L = 8 L = 9 L = 10 - """) + """ ns = {} exec(code, ns) f = ns['f'] @@ -1012,7 +1010,7 @@ def trace(frame, event, arg): self.assertEqual(f.__code__.co_code, co_code) def test_setting_lineno_one_undefined(self): - code = textwrap.dedent("""\ + code = d""" def f(): x = y = 2 if not x: @@ -1023,7 +1021,7 @@ def f(): L = 8 L = 9 L = 10 - """) + """ ns = {} exec(code, ns) f = ns['f'] @@ -1046,7 +1044,7 @@ def trace(frame, event, arg): self.assertEqual(f.__code__.co_code, co_code) def test_setting_lineno_two_undefined(self): - code = textwrap.dedent("""\ + code = d""" def f(): x = y = 2 if not x: @@ -1057,7 +1055,7 @@ def f(): L = 8 L = 9 L = 10 - """) + """ ns = {} exec(code, ns) f = ns['f'] @@ -1080,7 +1078,7 @@ def trace(frame, event, arg): self.assertEqual(f.__code__.co_code, co_code) def make_function_with_no_checks(self): - code = textwrap.dedent("""\ + code = d""" def f(): x = 2 L = 3 @@ -1089,7 +1087,7 @@ def f(): if not L: x + 7 y = 2 - """) + """ ns = {} exec(code, ns) f = ns['f'] diff --git a/Lib/test/test_peg_generator/test_pegen.py b/Lib/test/test_peg_generator/test_pegen.py index f39fcc2e0d8daf..895622d58fd888 100644 --- a/Lib/test/test_peg_generator/test_pegen.py +++ b/Lib/test/test_peg_generator/test_pegen.py @@ -21,12 +21,12 @@ class TestPegen(unittest.TestCase): def test_parse_grammar(self) -> None: - grammar_source = """ + grammar_source = d""" start: sum NEWLINE sum: t1=term '+' t2=term { action } | term term: NUMBER """ - expected = """ + expected = d""" start: sum NEWLINE sum: term '+' term | term term: NUMBER @@ -43,7 +43,7 @@ def test_parse_grammar(self) -> None: self.assertEqual(repr(rules["term"]), expected_repr) def test_repeated_rules(self) -> None: - grammar_source = """ + grammar_source = d""" start: the_rule NEWLINE the_rule: 'b' NEWLINE the_rule: 'a' NEWLINE @@ -52,10 +52,10 @@ def test_repeated_rules(self) -> None: parse_string(grammar_source, GrammarParser) def test_long_rule_str(self) -> None: - grammar_source = """ + grammar_source = d""" start: zero | one | one zero | one one | one zero zero | one zero one | one one zero | one one one """ - expected = """ + expected = d""" start: | zero | one @@ -426,7 +426,7 @@ def test_repeat_with_sep_simple(self) -> None: ) def test_left_recursive(self) -> None: - grammar_source = """ + grammar_source = d""" start: expr NEWLINE expr: ('-' term | expr '+' term | term) term: NUMBER @@ -513,7 +513,7 @@ def test_f_string_in_action(self) -> None: self.assertEqual(node.strip(), "name -> a") def test_nullable(self) -> None: - grammar_source = """ + grammar_source = d""" start: sign NUMBER sign: ['-' | '+'] """ @@ -524,7 +524,7 @@ def test_nullable(self) -> None: self.assertIn(rules["sign"], nullables) def test_advanced_left_recursive(self) -> None: - grammar_source = """ + grammar_source = d""" start: NUMBER | sign start sign: ['-'] """ @@ -538,7 +538,7 @@ def test_advanced_left_recursive(self) -> None: self.assertFalse(rules["sign"].left_recursive) def test_mutually_left_recursive(self) -> None: - grammar_source = """ + grammar_source = d""" start: foo 'E' foo: bar 'A' | 'B' bar: foo 'C' | 'D' @@ -639,7 +639,7 @@ def test_nasty_mutually_left_recursive(self) -> None: # which fails, so it retreats to NAME, # which succeeds, so we end up just recognizing 'x', # and then start fails because there's no '=' after that. - grammar_source = """ + grammar_source = d""" start: target '=' target: maybe '+' | NAME maybe: maybe '-' | target @@ -871,7 +871,7 @@ def test_forced_with_group(self) -> None: self.assertIn("expected (':' | ';')", e.exception.args[0]) def test_unreachable_explicit(self) -> None: - source = """ + source = d""" start: NAME { UNREACHABLE } """ grammar = parse_string(source, GrammarParser) @@ -883,7 +883,7 @@ def test_unreachable_explicit(self) -> None: self.assertIn("This is a test", out.getvalue()) def test_unreachable_implicit1(self) -> None: - source = """ + source = d""" start: NAME | invalid_input invalid_input: NUMBER { None } """ @@ -896,7 +896,7 @@ def test_unreachable_implicit1(self) -> None: self.assertIn("This is a test", out.getvalue()) def test_unreachable_implicit2(self) -> None: - source = """ + source = d""" start: NAME | '(' invalid_input ')' invalid_input: NUMBER { None } """ @@ -909,7 +909,7 @@ def test_unreachable_implicit2(self) -> None: self.assertIn("This is a test", out.getvalue()) def test_unreachable_implicit3(self) -> None: - source = """ + source = d""" start: NAME | invalid_input { None } invalid_input: NUMBER """ @@ -1037,8 +1037,7 @@ def test_simple_rule(self) -> None: printer.print_grammar_ast(rules, printer=lines.append) output = "\n".join(lines) - expected_output = textwrap.dedent( - """\ + expected_output = d""" └──Rule └──Rhs └──Alt @@ -1047,7 +1046,6 @@ def test_simple_rule(self) -> None: └──NamedItem └──StringLeaf("'b'") """ - ) self.assertEqual(output, expected_output) @@ -1064,8 +1062,7 @@ def test_multiple_rules(self) -> None: printer.print_grammar_ast(rules, printer=lines.append) output = "\n".join(lines) - expected_output = textwrap.dedent( - """\ + expected_output = d""" └──Rule └──Rhs └──Alt @@ -1086,7 +1083,6 @@ def test_multiple_rules(self) -> None: └──NamedItem └──StringLeaf("'b'") """ - ) self.assertEqual(output, expected_output) @@ -1101,8 +1097,7 @@ def test_deep_nested_rule(self) -> None: printer.print_grammar_ast(rules, printer=lines.append) output = "\n".join(lines) - expected_output = textwrap.dedent( - """\ + expected_output = d""" └──Rule └──Rhs └──Alt @@ -1127,14 +1122,13 @@ def test_deep_nested_rule(self) -> None: └──NamedItem └──StringLeaf("'d'") """ - ) self.assertEqual(output, expected_output) def test_rule_flags(self) -> None: """Test the new rule flags syntax that accepts arbitrary lists of flags.""" # Test grammar with various flag combinations - grammar_source = """ + grammar_source = d""" start: simple_rule simple_rule (memo): diff --git a/Lib/test/test_profiling/test_sampling_profiler/test_blocking.py b/Lib/test/test_profiling/test_sampling_profiler/test_blocking.py index 1f4b6da3281056..c3a0b21d177d5c 100644 --- a/Lib/test/test_profiling/test_sampling_profiler/test_blocking.py +++ b/Lib/test/test_profiling/test_sampling_profiler/test_blocking.py @@ -1,7 +1,6 @@ """Tests for blocking mode sampling profiler.""" import io -import textwrap import unittest from unittest import mock @@ -43,7 +42,7 @@ def setUpClass(cls): # lines (temp1, temp2, etc.), fibonacci_generator should NOT be in the # stack at all. # Line numbers are important here - see ARITHMETIC_LINES below. - cls.generator_script = textwrap.dedent(''' + cls.generator_script = d''' def fibonacci_generator(n): a, b = 0, 1 for _ in range(n): @@ -64,7 +63,7 @@ def main(): _test_sock.sendall(b"working") main() - ''') + ''' # Line numbers of the arithmetic operations in consume_generator. # These are the lines where fibonacci_generator should NOT be in the # stack when consume_generator is the executing leaf frame. They account diff --git a/Lib/test/test_profiling/test_tracing_profiler.py b/Lib/test/test_profiling/test_tracing_profiler.py index 3668e24e073ce4..d745a758b1ba53 100644 --- a/Lib/test/test_profiling/test_tracing_profiler.py +++ b/Lib/test/test_profiling/test_tracing_profiler.py @@ -6,7 +6,6 @@ # rip off all interesting stuff from test_profile import profiling.tracing as cProfile import tempfile -import textwrap from test.test_profile import ProfileTest, regenerate_expected_output from test.support.script_helper import assert_python_failure, assert_python_ok from test import support @@ -183,12 +182,12 @@ def test_profile_script_importing_main(self): """Check that scripts that reference __main__ see their own namespace when being profiled.""" with tempfile.NamedTemporaryFile("w+", delete_on_close=False) as f: - f.write(textwrap.dedent("""\ + f.write(d""" class Foo: pass import __main__ assert Foo == __main__.Foo - """)) + """) f.close() assert_python_ok('-m', "cProfile", f.name) diff --git a/Lib/test/test_pyexpat.py b/Lib/test/test_pyexpat.py index 42309dd8f6c190..30768b336f2122 100644 --- a/Lib/test/test_pyexpat.py +++ b/Lib/test/test_pyexpat.py @@ -892,12 +892,12 @@ def test_trigger_leak(self): # Unfixed, this test would leak the memory of the so-called # "content model" in function ``my_ElementDeclHandler`` of pyexpat. # See https://github.com/python/cpython/issues/140593. - data = textwrap.dedent('''\ + data = d''' ]> - ''').encode('UTF-8') + '''.encode('UTF-8') parser = expat.ParserCreate() parser.NotStandaloneHandler = lambda: 1.234 # arbitrary float @@ -1155,7 +1155,7 @@ def exponential_expansion_payload(*, nrows, ncols, text='.'): Be careful: the number of total items is pow(n, k), thereby requiring at least pow(ncols, nrows) * sizeof(text) memory! """ - template = textwrap.dedent(f"""\ + template = fd""" @@ -1163,7 +1163,7 @@ def exponential_expansion_payload(*, nrows, ncols, text='.'): {{body}} ]> &row{nrows}; - """).rstrip() + """.rstrip() body = '\n'.join( f'' @@ -1175,7 +1175,7 @@ def exponential_expansion_payload(*, nrows, ncols, text='.'): def test_payload_generation(self): # self-test for exponential_expansion_payload() payload = self.exponential_expansion_payload(nrows=2, ncols=3) - self.assertEqual(payload, textwrap.dedent("""\ + self.assertEqual(payload, d""" @@ -1184,7 +1184,7 @@ def test_payload_generation(self): ]> &row2; - """).rstrip()) + """.rstrip()) def assert_root_parser_failure(self, func, /, *args, **kwargs): """Check that func(*args, **kwargs) is invalid for a sub-parser.""" diff --git a/Lib/test/test_pystats.py b/Lib/test/test_pystats.py index c50cecfcfddfe6..66f244e581dae6 100644 --- a/Lib/test/test_pystats.py +++ b/Lib/test/test_pystats.py @@ -95,7 +95,7 @@ class TestPyStats(unittest.TestCase): def test_stats_toggle_on(self): """Check the toggle on functionality. """ - code = """ + code = d""" def func_start(): modify_class() """ @@ -112,7 +112,7 @@ def func_start(): stat_count = run_test_code(code) self.assertEqual(stat_count, '') - code = """ + code = d""" def func_start(): modify_class() sys._stats_on() @@ -126,7 +126,7 @@ def func_start(): def test_stats_toggle_on_thread(self): """Check the toggle on functionality when threads are used. """ - code = """ + code = d""" def func_test(thread_id): if thread_id == 0: modify_class() @@ -141,7 +141,7 @@ def func_test(thread_id): stat_count = run_test_code(code) self.assertEqual(stat_count, '2') - code = """ + code = d""" def func_test(thread_id): if thread_id == 0: modify_class() @@ -159,7 +159,7 @@ def func_test(thread_id): def test_thread_exit_merge(self): """Check that per-thread stats (when free-threading enabled) are merged. """ - code = """ + code = d""" def func_test(thread_id): modify_class() if thread_id == 0: @@ -172,7 +172,7 @@ def func_test(thread_id): def test_stats_dump(self): """Check that sys._stats_dump() works. """ - code = """ + code = d""" def func_test(thread_id): if thread_id == 0: stats_on() @@ -190,7 +190,7 @@ def func_test(thread_id): def test_stats_clear(self): """Check that sys._stats_clear() works. """ - code = """ + code = d""" ready = False def func_test(thread_id): global ready diff --git a/Lib/test/test_re.py b/Lib/test/test_re.py index 4ab615b150002c..95604d242b6720 100644 --- a/Lib/test/test_re.py +++ b/Lib/test/test_re.py @@ -2311,7 +2311,7 @@ def test_error(self): self.assertEqual(err.pos, 3) # Multiline pattern with self.assertRaises(re.PatternError) as cm: - re.compile(""" + re.compile(d""" ( abc ) @@ -2319,12 +2319,12 @@ def test_error(self): ( """, re.VERBOSE) err = cm.exception - self.assertEqual(err.pos, 77) - self.assertEqual(err.lineno, 5) - self.assertEqual(err.colno, 17) + self.assertEqual(err.pos, 12) + self.assertEqual(err.lineno, 4) + self.assertEqual(err.colno, 1) self.assertIn(err.msg, str(err)) - self.assertIn(' at position 77', str(err)) - self.assertIn('(line 5, column 17)', str(err)) + self.assertIn(' at position 12', str(err)) + self.assertIn('(line 4, column 1)', str(err)) def test_misc_errors(self): self.checkPatternError(r'(', 'missing ), unterminated subpattern', 0) diff --git a/Lib/test/test_readline.py b/Lib/test/test_readline.py index 3982686dd10aec..a0ff129bde41aa 100644 --- a/Lib/test/test_readline.py +++ b/Lib/test/test_readline.py @@ -6,7 +6,6 @@ import os import sys import tempfile -import textwrap import threading import unittest from test import support @@ -207,7 +206,7 @@ def test_auto_history_disabled(self): self.assertIn(b"History length: 0", output) def test_set_complete_delims(self): - script = textwrap.dedent(""" + script = d""" import readline def complete(text, state): if state == 0 and text == "$": @@ -220,7 +219,7 @@ def complete(text, state): readline.set_completer_delims(" \\t\\n") readline.set_completer(complete) print(input()) - """) + """ output = run_pty(script, input=b"$\t\n") self.assertIn(b"$complete", output) @@ -372,7 +371,7 @@ def test_history_size(self): @requires_working_threading() def test_gh123321_threadsafe(self): """gh-123321: readline should be thread-safe and not crash""" - script = textwrap.dedent(r""" + script = rd""" import threading from test.support.threading_helper import join_thread @@ -386,7 +385,7 @@ def func(): join_thread(thread1) join_thread(thread2) print("done") - """) + """ output = run_pty(script, input=b"input1\rinput2\r") diff --git a/Lib/test/test_regrtest.py b/Lib/test/test_regrtest.py index 6d30d267cd5ad2..97c03575144acd 100644 --- a/Lib/test/test_regrtest.py +++ b/Lib/test/test_regrtest.py @@ -64,14 +64,14 @@ EXITCODE_RERUN_FAIL = 5 EXITCODE_INTERRUPTED = 130 -TEST_INTERRUPTED = textwrap.dedent(""" +TEST_INTERRUPTED = d""" from signal import SIGINT, raise_signal try: raise_signal(SIGINT) except ImportError: import os os.kill(os.getpid(), SIGINT) - """) + """ class ParseArgsTestCase(unittest.TestCase): @@ -607,13 +607,13 @@ def create_test(self, name=None, code=None): BaseTestCase.TEST_UNIQUE_ID += 1 if code is None: - code = textwrap.dedent(""" + code = d""" import unittest class Tests(unittest.TestCase): def test_empty_test(self): pass - """) + """ # test_regrtest cannot be run twice in parallel because # of setUp() and create_test() @@ -1014,7 +1014,7 @@ def run_tests(self, *testargs, **kw): return self.run_python(cmdargs, **kw) def test_success(self): - code = textwrap.dedent(""" + code = d""" import unittest class PassingTests(unittest.TestCase): @@ -1026,7 +1026,7 @@ def test_test2(self): def test_test3(self): pass - """) + """ tests = [self.create_test(f'ok{i}', code=code) for i in range(1, 6)] output = self.run_tests(*tests) @@ -1034,10 +1034,10 @@ def test_test3(self): stats=3 * len(tests)) def test_skip(self): - code = textwrap.dedent(""" + code = d""" import unittest raise unittest.SkipTest("nope") - """) + """ test_ok = self.create_test('ok') test_skip = self.create_test('skip', code=code) tests = [test_ok, test_skip] @@ -1049,13 +1049,13 @@ def test_skip(self): def test_failing_test(self): # test a failing test - code = textwrap.dedent(""" + code = d""" import unittest class FailingTest(unittest.TestCase): def test_failing(self): self.fail("bug") - """) + """ test_ok = self.create_test('ok') test_failing = self.create_test('failing', code=code) tests = [test_ok, test_failing] @@ -1097,10 +1097,10 @@ def test_pass(self): def test_random(self): # test -r and --randseed command line option - code = textwrap.dedent(""" + code = d""" import random print("TESTRANDOM: %s" % random.randint(1, 1000)) - """) + """ test = self.create_test('random', code) # first run to get the output with the random seed @@ -1250,7 +1250,7 @@ def test_wait(self): def test_forever(self): # test --forever - code = textwrap.dedent(""" + code = d""" import builtins import unittest @@ -1264,7 +1264,7 @@ def test_run(self): self.fail("fail at the 3rd runs") else: builtins.__dict__['RUN'] = 1 - """) + """ test = self.create_test('forever', code=code) # --forever @@ -1310,7 +1310,7 @@ def check_leak(self, code, what, *, run_workers=False): @unittest.skipUnless(support.Py_DEBUG, 'need a debug build') def check_huntrleaks(self, *, run_workers: bool): # test --huntrleaks - code = textwrap.dedent(""" + code = d""" import unittest GLOBAL_LIST = [] @@ -1318,7 +1318,7 @@ def check_huntrleaks(self, *, run_workers: bool): class RefLeakTest(unittest.TestCase): def test_leak(self): GLOBAL_LIST.append(object()) - """) + """ self.check_leak(code, 'references', run_workers=run_workers) def test_huntrleaks(self): @@ -1330,7 +1330,7 @@ def test_huntrleaks_mp(self): @unittest.skipUnless(support.Py_DEBUG, 'need a debug build') def test_huntrleaks_bisect(self): # test --huntrleaks --bisect - code = textwrap.dedent(""" + code = d""" import unittest GLOBAL_LIST = [] @@ -1347,7 +1347,7 @@ def test3(self): def test4(self): pass - """) + """ test = self.create_test('huntrleaks', code=code) @@ -1371,7 +1371,7 @@ def test4(self): @unittest.skipUnless(support.Py_DEBUG, 'need a debug build') def test_huntrleaks_fd_leak(self): # test --huntrleaks for file descriptor leak - code = textwrap.dedent(""" + code = d""" import os import unittest @@ -1379,7 +1379,7 @@ class FDLeakTest(unittest.TestCase): def test_leak(self): fd = os.open(__file__, os.O_RDONLY) # bug: never close the file descriptor - """) + """ self.check_leak(code, 'file descriptors') def test_list_tests(self): @@ -1391,7 +1391,7 @@ def test_list_tests(self): def test_list_cases(self): # test --list-cases - code = textwrap.dedent(""" + code = d""" import unittest class Tests(unittest.TestCase): @@ -1399,7 +1399,7 @@ def test_method1(self): pass def test_method2(self): pass - """) + """ testname = self.create_test(code=code) # Test --list-cases @@ -1431,7 +1431,7 @@ def parse_methods(self, output): return [match.group(1) for match in regex.finditer(output)] def test_ignorefile(self): - code = textwrap.dedent(""" + code = d""" import unittest class Tests(unittest.TestCase): @@ -1443,7 +1443,7 @@ def test_method3(self): pass def test_method4(self): pass - """) + """ testname = self.create_test(code=code) # only run a subset @@ -1465,7 +1465,7 @@ def test_method4(self): self.assertEqual(methods, subset) def test_matchfile(self): - code = textwrap.dedent(""" + code = d""" import unittest class Tests(unittest.TestCase): @@ -1477,7 +1477,7 @@ def test_method3(self): pass def test_method4(self): pass - """) + """ all_methods = ['test_method1', 'test_method2', 'test_method3', 'test_method4'] testname = self.create_test(code=code) @@ -1506,13 +1506,13 @@ def test_method4(self): self.assertEqual(methods, subset) def test_env_changed(self): - code = textwrap.dedent(""" + code = d""" import unittest class Tests(unittest.TestCase): def test_env_changed(self): open("env_changed", "w").close() - """) + """ testname = self.create_test(code=code) # don't fail by default @@ -1537,7 +1537,7 @@ def test_env_changed(self): def test_rerun_fail(self): # FAILURE then FAILURE - code = textwrap.dedent(""" + code = d""" import unittest class Tests(unittest.TestCase): @@ -1547,7 +1547,7 @@ def test_succeed(self): def test_fail_always(self): # test that always fails self.fail("bug") - """) + """ testname = self.create_test(code=code) output = self.run_tests("--rerun", testname, exitcode=EXITCODE_BAD_TEST) @@ -1563,7 +1563,7 @@ def test_rerun_success(self): self.addCleanup(os_helper.unlink, marker_filename) self.assertFalse(os.path.exists(marker_filename)) - code = textwrap.dedent(f""" + code = fd""" import os.path import unittest @@ -1577,7 +1577,7 @@ def test_fail_once(self): if not os.path.exists(marker_filename): open(marker_filename, "w").close() self.fail("bug") - """) + """ testname = self.create_test(code=code) # FAILURE then SUCCESS => exit code 0 @@ -1602,7 +1602,7 @@ def test_fail_once(self): def test_rerun_setup_class_hook_failure(self): # FAILURE then FAILURE - code = textwrap.dedent(""" + code = d""" import unittest class ExampleTests(unittest.TestCase): @@ -1612,7 +1612,7 @@ def setUpClass(self): def test_success(self): return - """) + """ testname = self.create_test(code=code) output = self.run_tests("--rerun", testname, exitcode=EXITCODE_BAD_TEST) @@ -1625,7 +1625,7 @@ def test_success(self): def test_rerun_teardown_class_hook_failure(self): # FAILURE then FAILURE - code = textwrap.dedent(""" + code = d""" import unittest class ExampleTests(unittest.TestCase): @@ -1635,7 +1635,7 @@ def tearDownClass(self): def test_success(self): return - """) + """ testname = self.create_test(code=code) output = self.run_tests("--rerun", testname, exitcode=EXITCODE_BAD_TEST) @@ -1648,7 +1648,7 @@ def test_success(self): def test_rerun_setup_module_hook_failure(self): # FAILURE then FAILURE - code = textwrap.dedent(""" + code = d""" import unittest def setUpModule(): @@ -1657,7 +1657,7 @@ def setUpModule(): class ExampleTests(unittest.TestCase): def test_success(self): return - """) + """ testname = self.create_test(code=code) output = self.run_tests("--rerun", testname, exitcode=EXITCODE_BAD_TEST) @@ -1670,7 +1670,7 @@ def test_success(self): def test_rerun_teardown_module_hook_failure(self): # FAILURE then FAILURE - code = textwrap.dedent(""" + code = d""" import unittest def tearDownModule(): @@ -1679,7 +1679,7 @@ def tearDownModule(): class ExampleTests(unittest.TestCase): def test_success(self): return - """) + """ testname = self.create_test(code=code) output = self.run_tests("--rerun", testname, exitcode=EXITCODE_BAD_TEST) @@ -1692,7 +1692,7 @@ def test_success(self): def test_rerun_setup_hook_failure(self): # FAILURE then FAILURE - code = textwrap.dedent(""" + code = d""" import unittest class ExampleTests(unittest.TestCase): @@ -1701,7 +1701,7 @@ def setUp(self): def test_success(self): return - """) + """ testname = self.create_test(code=code) output = self.run_tests("--rerun", testname, exitcode=EXITCODE_BAD_TEST) @@ -1714,7 +1714,7 @@ def test_success(self): def test_rerun_teardown_hook_failure(self): # FAILURE then FAILURE - code = textwrap.dedent(""" + code = d""" import unittest class ExampleTests(unittest.TestCase): @@ -1723,7 +1723,7 @@ def tearDown(self): def test_success(self): return - """) + """ testname = self.create_test(code=code) output = self.run_tests("--rerun", testname, exitcode=EXITCODE_BAD_TEST) @@ -1736,7 +1736,7 @@ def test_success(self): def test_rerun_async_setup_hook_failure(self): # FAILURE then FAILURE - code = textwrap.dedent(""" + code = d""" import unittest class ExampleTests(unittest.IsolatedAsyncioTestCase): @@ -1745,7 +1745,7 @@ async def asyncSetUp(self): async def test_success(self): return - """) + """ testname = self.create_test(code=code) output = self.run_tests("--rerun", testname, exitcode=EXITCODE_BAD_TEST) @@ -1757,7 +1757,7 @@ async def test_success(self): def test_rerun_async_teardown_hook_failure(self): # FAILURE then FAILURE - code = textwrap.dedent(""" + code = d""" import unittest class ExampleTests(unittest.IsolatedAsyncioTestCase): @@ -1766,7 +1766,7 @@ async def asyncTearDown(self): async def test_success(self): return - """) + """ testname = self.create_test(code=code) output = self.run_tests("--rerun", testname, exitcode=EXITCODE_BAD_TEST) @@ -1778,13 +1778,13 @@ async def test_success(self): stats=2) def test_no_tests_ran(self): - code = textwrap.dedent(""" + code = d""" import unittest class Tests(unittest.TestCase): def test_bug(self): pass - """) + """ testname = self.create_test(code=code) output = self.run_tests(testname, "-m", "nosuchtest", @@ -1794,13 +1794,13 @@ def test_bug(self): stats=0, filtered=True) def test_no_tests_ran_skip(self): - code = textwrap.dedent(""" + code = d""" import unittest class Tests(unittest.TestCase): def test_skipped(self): self.skipTest("because") - """) + """ testname = self.create_test(code=code) output = self.run_tests(testname) @@ -1808,13 +1808,13 @@ def test_skipped(self): stats=TestStats(1, skipped=1)) def test_no_tests_ran_multiple_tests_nonexistent(self): - code = textwrap.dedent(""" + code = d""" import unittest class Tests(unittest.TestCase): def test_bug(self): pass - """) + """ testname = self.create_test(code=code) testname2 = self.create_test(code=code) @@ -1825,21 +1825,21 @@ def test_bug(self): stats=0, filtered=True) def test_no_test_ran_some_test_exist_some_not(self): - code = textwrap.dedent(""" + code = d""" import unittest class Tests(unittest.TestCase): def test_bug(self): pass - """) + """ testname = self.create_test(code=code) - other_code = textwrap.dedent(""" + other_code = d""" import unittest class Tests(unittest.TestCase): def test_other_bug(self): pass - """) + """ testname2 = self.create_test(code=other_code) output = self.run_tests(testname, testname2, "-m", "nosuchtest", @@ -1853,7 +1853,7 @@ def test_uncollectable(self): # Skip test if _testcapi is missing import_helper.import_module('_testcapi') - code = textwrap.dedent(r""" + code = rd""" import _testcapi import gc import unittest @@ -1869,7 +1869,7 @@ def test_garbage(self): obj = Garbage() obj.ref_cycle = obj obj = None - """) + """ testname = self.create_test(code=code) output = self.run_tests("--fail-env-changed", testname, @@ -1880,7 +1880,7 @@ def test_garbage(self): stats=1) def test_multiprocessing_timeout(self): - code = textwrap.dedent(r""" + code = rd""" import time import unittest try: @@ -1897,7 +1897,7 @@ def test_sleep(self): faulthandler.cancel_dump_traceback_later() time.sleep(60 * 5) - """) + """ testname = self.create_test(code=code) output = self.run_tests("-j2", "--timeout=1.0", testname, @@ -1910,7 +1910,7 @@ def test_sleep(self): def test_unraisable_exc(self): # --fail-env-changed must catch unraisable exception. # The exception must be displayed even if sys.stderr is redirected. - code = textwrap.dedent(r""" + code = rd""" import unittest import weakref from test.support import captured_stderr @@ -1930,7 +1930,7 @@ def test_unraisable_exc(self): # an unraisable exception obj = None self.assertEqual(stderr.getvalue(), '') - """) + """ testname = self.create_test(code=code) output = self.run_tests("--fail-env-changed", "-v", testname, @@ -1945,7 +1945,7 @@ def test_unraisable_exc(self): def test_threading_excepthook(self): # --fail-env-changed must catch uncaught thread exception. # The exception must be displayed even if sys.stderr is redirected. - code = textwrap.dedent(r""" + code = rd""" import threading import unittest from test.support import captured_stderr @@ -1963,7 +1963,7 @@ def test_threading_excepthook(self): thread.start() thread.join() self.assertEqual(stderr.getvalue(), '') - """) + """ testname = self.create_test(code=code) output = self.run_tests("--fail-env-changed", "-v", testname, @@ -1978,7 +1978,7 @@ def test_threading_excepthook(self): def test_print_warning(self): # bpo-45410: The order of messages must be preserved when -W and # support.print_warning() are used. - code = textwrap.dedent(r""" + code = rd""" import sys import unittest from test import support @@ -1995,7 +1995,7 @@ def test_print_warning(self): support.print_warning("msg2: print_warning") # Fail with ENV CHANGED to see print_warning() log support.environment_altered = True - """) + """ testname = self.create_test(code=code) # Expect an output like: @@ -2042,7 +2042,7 @@ def test_cleanup(self): @unittest.skipIf(support.is_wasi, 'checking temp files is not implemented on WASI') def test_leak_tmp_file(self): - code = textwrap.dedent(r""" + code = rd""" import os.path import tempfile import unittest @@ -2052,7 +2052,7 @@ def test_leak_tmp_file(self): filename = os.path.join(tempfile.gettempdir(), 'mytmpfile') with open(filename, "wb") as fp: fp.write(b'content') - """) + """ testnames = [self.create_test(code=code) for _ in range(3)] output = self.run_tests("--fail-env-changed", "-v", "-j2", *testnames, @@ -2093,7 +2093,7 @@ def test_worker_decode_error(self): expected_line = corrupted_output.decode(encoding, 'backslashreplace') - code = textwrap.dedent(fr""" + code = frd""" import sys import unittest @@ -2105,7 +2105,7 @@ def test_pass(self): corrupted_output = {corrupted_output!a} sys.stdout.buffer.write(corrupted_output) sys.stdout.buffer.flush() - """) + """ testname = self.create_test(code=code) output = self.run_tests("--fail-env-changed", "-v", "-j1", testname) @@ -2115,7 +2115,7 @@ def test_pass(self): self.check_line(output, expected_line, regex=False) def test_doctest(self): - code = textwrap.dedent(r''' + code = rd''' import doctest import sys from test import support @@ -2143,7 +2143,7 @@ def my_function(): def load_tests(loader, tests, pattern): tests.addTest(doctest.DocTestSuite()) return tests - ''') + ''' testname = self.create_test(code=code) output = self.run_tests("--fail-env-changed", "-v", "-j1", testname, @@ -2156,7 +2156,7 @@ def load_tests(loader, tests, pattern): def _check_random_seed(self, run_workers: bool): # gh-109276: When -r/--randomize is used, random.seed() is called # with the same random seed before running each test file. - code = textwrap.dedent(r''' + code = rd''' import random import unittest @@ -2164,7 +2164,7 @@ class RandomSeedTest(unittest.TestCase): def test_randint(self): numbers = [random.randint(0, 1000) for _ in range(10)] print(f"Random numbers: {numbers}") - ''') + ''' tests = [self.create_test(name=f'test_random{i}', code=code) for i in range(1, 3+1)] @@ -2194,14 +2194,14 @@ def test_random_seed_workers(self): self._check_random_seed(run_workers=True) def test_python_command(self): - code = textwrap.dedent(r""" + code = rd""" import sys import unittest class WorkerTests(unittest.TestCase): def test_dev_mode(self): self.assertTrue(sys.flags.dev_mode) - """) + """ tests = [self.create_test(code=code) for _ in range(3)] # Custom Python command: "python -X dev" @@ -2236,7 +2236,7 @@ def test_unload_tests(self): def check_add_python_opts(self, option): # --fast-ci and --slow-ci add "-u -W error -bb -E" options to Python - code = textwrap.dedent(r""" + code = rd""" import sys import unittest from test import support @@ -2276,7 +2276,7 @@ def test_python_opts(self): # -E option self.assertEqual(not sys.flags.ignore_environment, use_environment) - """) + """ testname = self.create_test(code=code) # Use directly subprocess to control the exact command line @@ -2303,7 +2303,7 @@ def test_worker_output_on_failure(self): # Skip test if faulthandler is missing import_helper.import_module('faulthandler') - code = textwrap.dedent(r""" + code = rd""" import faulthandler import unittest from test import support @@ -2314,7 +2314,7 @@ def test_crash(self): with support.SuppressCrashReport(): faulthandler._sigsegv(True) - """) + """ testname = self.create_test(code=code) # Sanitizers must not handle SIGSEGV (ex: for test_enable_fd()) @@ -2334,14 +2334,14 @@ def test_crash(self): self.check_line(output, "just before crash!", full=True, regex=False) def test_verbose3(self): - code = textwrap.dedent(r""" + code = rd""" import unittest from test import support class VerboseTests(unittest.TestCase): def test_pass(self): print("SPAM SPAM SPAM") - """) + """ testname = self.create_test(code=code) # Run sequentially @@ -2357,14 +2357,14 @@ def test_pass(self): self.assertNotIn('SPAM SPAM SPAM', output) def test_xml(self): - code = textwrap.dedent(r""" + code = rd""" import unittest class VerboseTests(unittest.TestCase): def test_failed(self): print("abc \x1b def") self.fail() - """) + """ testname = self.create_test(code=code) # Run sequentially @@ -2394,7 +2394,7 @@ def test_failed(self): self.assertEqual(out.text, r"abc \x1b def") def test_nonascii(self): - code = textwrap.dedent(r""" + code = rd""" import unittest class NonASCIITests(unittest.TestCase): @@ -2407,7 +2407,7 @@ def test_subtest(self): def test_skip(self): self.skipTest('skipped:\u20ac') - """) + """ testname = self.create_test(code=code) env = dict(os.environ) diff --git a/Lib/test/test_runpy.py b/Lib/test/test_runpy.py index 55b9673ef6c91c..49548a191b0de7 100644 --- a/Lib/test/test_runpy.py +++ b/Lib/test/test_runpy.py @@ -9,7 +9,6 @@ import subprocess import sys import tempfile -import textwrap import unittest import warnings from test.support import ( @@ -855,11 +854,9 @@ def run(self, *args, **kwargs): with self.tmp_path() as tmp: self.ham = ham = tmp / "ham.py" ham.write_text( - textwrap.dedent( - """\ + d""" raise KeyboardInterrupt """ - ) ) super().run(*args, **kwargs) @@ -878,12 +875,10 @@ def test_pymain_run_file_runpy_run_module(self): tmp = self.ham.parent run_module = tmp / "run_module.py" run_module.write_text( - textwrap.dedent( - """\ + d""" import runpy runpy.run_module("ham") """ - ) ) self.assertSigInt([run_module], cwd=tmp) @@ -891,12 +886,10 @@ def test_pymain_run_file_runpy_run_module_as_main(self): tmp = self.ham.parent run_module_as_main = tmp / "run_module_as_main.py" run_module_as_main.write_text( - textwrap.dedent( - """\ + d""" import runpy runpy._run_module_as_main("ham") """ - ) ) self.assertSigInt([run_module_as_main], cwd=tmp) diff --git a/Lib/test/test_select.py b/Lib/test/test_select.py index a82584d6904920..7907304159e27f 100644 --- a/Lib/test/test_select.py +++ b/Lib/test/test_select.py @@ -2,7 +2,6 @@ import select import subprocess import sys -import textwrap import unittest from test import support @@ -49,12 +48,12 @@ def test_returned_list_identity(self): @support.requires_fork() def test_select(self): - code = textwrap.dedent(''' + code = d''' import time for i in range(10): print("testing...", flush=True) time.sleep(0.050) - ''') + ''' cmd = [sys.executable, '-I', '-c', code] with subprocess.Popen(cmd, stdout=subprocess.PIPE) as proc: pipe = proc.stdout diff --git a/Lib/test/test_smtplib.py b/Lib/test/test_smtplib.py index b8aac8c20202a2..7ccc6a15637290 100644 --- a/Lib/test/test_smtplib.py +++ b/Lib/test/test_smtplib.py @@ -13,7 +13,6 @@ import time import select import errno -import textwrap import threading import unittest @@ -1514,7 +1513,7 @@ def test_send_message_uses_smtputf8_if_addrs_non_ascii(self): msg.set_content("oh là là, know what I mean, know what I mean?\n\n") # XXX smtpd converts received /r/n to /n, so we can't easily test that # we are successfully sending /r/n :(. - expected = textwrap.dedent("""\ + expected = d""" From: Páolo To: Dinsdale Subject: Nudge nudge, wink, wink \u1F609 @@ -1523,7 +1522,7 @@ def test_send_message_uses_smtputf8_if_addrs_non_ascii(self): MIME-Version: 1.0 oh là là, know what I mean, know what I mean? - """) + """ smtp = smtplib.SMTP( HOST, self.port, local_hostname='localhost', timeout=support.LOOPBACK_TIMEOUT) diff --git a/Lib/test/test_sqlite3/test_cli.py b/Lib/test/test_sqlite3/test_cli.py index 1fc0236780fa8b..c07ea79e2be21a 100644 --- a/Lib/test/test_sqlite3/test_cli.py +++ b/Lib/test/test_sqlite3/test_cli.py @@ -1,7 +1,6 @@ """sqlite3 CLI tests.""" import sqlite3 import sys -import textwrap import unittest import unittest.mock import os @@ -225,7 +224,7 @@ def setUpClass(cls): raise unittest.SkipTest("libedit readline is not supported") def write_input(self, input_, env=None): - script = textwrap.dedent(""" + script = d""" import readline from sqlite3.__main__ import main @@ -239,7 +238,7 @@ def write_input(self, input_, env=None): readline.parse_and_bind("set completion-display-width 0") main() - """) + """ return run_pty(script, input_, env) def test_complete_sql_keywords(self): @@ -267,7 +266,7 @@ def test_complete_sql_keywords(self): self.assertIn(b".version", output) def test_complete_table_indexes_triggers_views(self): - input_ = textwrap.dedent("""\ + input_ = d""" CREATE TABLE _Table (id); CREATE INDEX _Index ON _table (id); CREATE TRIGGER _Trigger BEFORE INSERT @@ -288,7 +287,7 @@ def test_complete_table_indexes_triggers_views(self): CREATE VIEW attached._Attached_view AS SELECT 1; SELECT id FROM _\t\tta\t; - .quit\n""").encode() + .quit\n""".encode() output = self.write_input(input_) lines = output.decode().splitlines() indices = [i for i, line in enumerate(lines) @@ -320,14 +319,14 @@ def test_complete_table_indexes_triggers_views(self): "PRAGMA table-valued function is not available until " "SQLite 3.16.0") def test_complete_columns(self): - input_ = textwrap.dedent("""\ + input_ = d""" CREATE TABLE _table (_col_table); CREATE TEMP TABLE _temp_table (_col_temp); ATTACH ':memory:' AS attached; CREATE TABLE attached._attached_table (_col_attached); SELECT _col_\t\tta\tFROM _table; - .quit\n""").encode() + .quit\n""".encode() output = self.write_input(input_) lines = output.decode().splitlines() indices = [ @@ -356,7 +355,7 @@ def test_complete_functions(self): self.assertIn(b"(1.0,)", output) def test_complete_schemata(self): - input_ = textwrap.dedent("""\ + input_ = d""" ATTACH ':memory:' AS MixedCase; -- Test '_' is escaped in Like pattern filtering ATTACH ':memory:' AS _underscore; @@ -365,7 +364,7 @@ def test_complete_schemata(self): SELECT * FROM \t\tmIX\t.sqlite_master; SELECT * FROM _und\t.sqlite_master; - .quit\n""").encode() + .quit\n""".encode() output = self.write_input(input_) lines = output.decode().splitlines() indices = [ @@ -398,7 +397,7 @@ def test_complete_no_match(self): self.assertEqual(line_num, len(lines)) def test_complete_no_input(self): - script = textwrap.dedent(""" + script = d""" import readline from sqlite3.__main__ import main @@ -416,7 +415,7 @@ def test_complete_no_input(self): readline.parse_and_bind("set show-all-if-unmodified off") main() - """) + """ input_ = b"\t\t.quit\n" output = run_pty(script, input_, env={**os.environ, "NO_COLOR": "1"}) try: diff --git a/Lib/test/test_str.py b/Lib/test/test_str.py index 4f57499af70f4d..3e8276f75179da 100644 --- a/Lib/test/test_str.py +++ b/Lib/test/test_str.py @@ -13,7 +13,6 @@ import pickle import struct import sys -import textwrap import unicodedata import unittest import warnings @@ -2643,7 +2642,7 @@ def test_check_encoding_errors(self): # arguments in dev mode encodings = ('ascii', 'utf8', 'latin1') invalid = 'Boom, Shaka Laka, Boom!' - code = textwrap.dedent(f''' + code = fd''' import sys encodings = {encodings!r} @@ -2694,7 +2693,7 @@ def test_check_encoding_errors(self): sys.exit(24) sys.exit(10) - ''') + ''' proc = assert_python_failure('-X', 'dev', '-c', code) self.assertEqual(proc.rc, 10, proc) diff --git a/Lib/test/test_structseq.py b/Lib/test/test_structseq.py index 74506fc54de50e..6dd0b774f8d2f8 100644 --- a/Lib/test/test_structseq.py +++ b/Lib/test/test_structseq.py @@ -3,7 +3,6 @@ import os import pickle import re -import textwrap import time import unittest from test.support import script_helper @@ -350,11 +349,11 @@ def test_reference_cycle(self): # with its own type doesn't crash. Previously, if the type's dictionary # was cleared first, the structseq instance would crash in the # destructor. - script_helper.assert_python_ok("-c", textwrap.dedent(r""" + script_helper.assert_python_ok("-c", rd""" import time t = time.gmtime() type(t).refcyle = t - """)) + """) def test_replace_gc_tracked(self): # Verify that __replace__ results are properly GC-tracked diff --git a/Lib/test/test_subprocess.py b/Lib/test/test_subprocess.py index d066ae85dfc51a..a81c49c4563b28 100644 --- a/Lib/test/test_subprocess.py +++ b/Lib/test/test_subprocess.py @@ -1313,12 +1313,12 @@ def test_universal_newlines_communicate(self): def test_universal_newlines_communicate_stdin(self): # universal newlines through communicate(), with only stdin p = subprocess.Popen([sys.executable, "-c", - 'import sys,os;' + SETBINARY + textwrap.dedent(''' + 'import sys,os;' + SETBINARY + d''' s = sys.stdin.readline() assert s == "line1\\n", repr(s) s = sys.stdin.read() assert s == "line3\\n", repr(s) - ''')], + '''], stdin=subprocess.PIPE, universal_newlines=1) (stdout, stderr) = p.communicate("line1\nline3\n") @@ -1339,7 +1339,7 @@ def test_universal_newlines_communicate_input_none(self): def test_universal_newlines_communicate_stdin_stdout_stderr(self): # universal newlines through communicate(), with stdin, stdout, stderr p = subprocess.Popen([sys.executable, "-c", - 'import sys,os;' + SETBINARY + textwrap.dedent(''' + 'import sys,os;' + SETBINARY + d''' s = sys.stdin.buffer.readline() sys.stdout.buffer.write(s) sys.stdout.buffer.write(b"line2\\r") @@ -1350,7 +1350,7 @@ def test_universal_newlines_communicate_stdin_stdout_stderr(self): sys.stdout.buffer.write(b"line5\\r\\n") sys.stderr.buffer.write(b"eline6\\r") sys.stderr.buffer.write(b"eline7\\r\\nz") - ''')], + '''], stdin=subprocess.PIPE, stderr=subprocess.PIPE, stdout=subprocess.PIPE, @@ -1578,7 +1578,7 @@ def test_nonexisting_with_pipes(self): except (AttributeError, ImportError): self.skipTest("need msvcrt.CrtSetReportMode") - code = textwrap.dedent(f""" + code = fd""" import msvcrt import subprocess @@ -1596,7 +1596,7 @@ def test_nonexisting_with_pipes(self): stderr=subprocess.PIPE) except OSError: pass - """) + """ cmd = [sys.executable, "-c", code] proc = subprocess.Popen(cmd, stderr=subprocess.PIPE, @@ -2046,11 +2046,11 @@ def test_run_with_shell_timeout_and_capture_output(self): f"{stacks}```") def test_encoding_warning(self): - code = textwrap.dedent("""\ + code = d""" from subprocess import * run("echo hello", shell=True, text=True) check_output("echo hello", shell=True, text=True) - """) + """ cp = subprocess.run([sys.executable, "-Xwarn_default_encoding", "-c", code], capture_output=True) lines = cp.stderr.splitlines() @@ -2912,13 +2912,13 @@ def _check_swap_std_fds_with_one_closed(self, from_fds, to_fds): for from_fd, to_fd in zip(from_fds, to_fds): kwargs[arg_names[to_fd]] = from_fd - code = textwrap.dedent(r''' + code = rd''' import os, sys skipped_fd = int(sys.argv[1]) for fd in range(3): if fd != skipped_fd: os.write(fd, str(fd).encode('ascii')) - ''') + ''' skipped_fd = (set(range(3)) - set(to_fds)).pop() @@ -2930,11 +2930,11 @@ def _check_swap_std_fds_with_one_closed(self, from_fds, to_fds): os.lseek(from_fd, 0, os.SEEK_SET) read_bytes = os.read(from_fd, 1024) read_fds = list(map(int, read_bytes.decode('ascii'))) - msg = textwrap.dedent(f""" + msg = fd""" When testing {from_fds} to {to_fds} redirection, parent descriptor {from_fd} got redirected to descriptor(s) {read_fds} instead of descriptor {to_fd}. - """) + """ self.assertEqual([to_fd], read_fds, msg) finally: self._restore_fds(saved_fds) diff --git a/Lib/test/test_super.py b/Lib/test/test_super.py index 193c8b7d7f3e13..8ba3834c268071 100644 --- a/Lib/test/test_super.py +++ b/Lib/test/test_super.py @@ -2,7 +2,6 @@ import copy import pickle -import textwrap import threading import unittest from unittest.mock import patch @@ -343,16 +342,14 @@ def test_super_argtype(self): super(1, int) def test_shadowed_global(self): - source = textwrap.dedent( - """ + source = d""" class super: msg = "truly super" class C: def method(self): return super().msg - """, - ) + """ with import_helper.ready_to_import(name="shadowed_super", source=source): import shadowed_super self.assertEqual(shadowed_super.C().method(), "truly super") diff --git a/Lib/test/test_support.py b/Lib/test/test_support.py index d556f96bc532ed..6ffaad0871180f 100644 --- a/Lib/test/test_support.py +++ b/Lib/test/test_support.py @@ -14,7 +14,6 @@ import sys import sysconfig import tempfile -import textwrap import unittest import warnings @@ -246,7 +245,7 @@ def test_temp_dir__forked_child(self): """Test that a forked child process does not remove the directory.""" # See bpo-30028 for details. # Run the test as an external script, because it uses fork. - script_helper.assert_python_ok("-c", textwrap.dedent(""" + script_helper.assert_python_ok("-c", d""" import os from test import support from test.support import os_helper @@ -264,7 +263,7 @@ def test_temp_dir__forked_child(self): # directory. if not os.path.isdir(temp_path): raise AssertionError("Child removed temp_path.") - """)) + """) # Tests for change_cwd() @@ -643,7 +642,7 @@ def test_has_strftime_extensions(self): def test_get_recursion_depth(self): # test support.get_recursion_depth() - code = textwrap.dedent(""" + code = d""" from test import support import sys @@ -681,7 +680,7 @@ def test_recursive(depth, limit): limit = sys.getrecursionlimit() print(f"test with sys.getrecursionlimit()={limit}") test_recursive(2, limit) - """) + """ script_helper.assert_python_ok("-c", code) @support.skip_if_unlimited_stack_size diff --git a/Lib/test/test_syntax.py b/Lib/test/test_syntax.py index a3d485c998ac91..eea834497ed19a 100644 --- a/Lib/test/test_syntax.py +++ b/Lib/test/test_syntax.py @@ -2857,7 +2857,6 @@ def f(x: *b) import re import doctest -import textwrap import unittest from test import support @@ -2873,16 +2872,16 @@ def check_warning(self, code, errtext, filename="", mode="exec"): compile(code, filename, mode) def test_return_in_finally(self): - source = textwrap.dedent(""" + source = d""" def f(): try: pass finally: return 42 - """) + """ self.check_warning(source, "'return' in a 'finally' block") - source = textwrap.dedent(""" + source = d""" def f(): try: pass @@ -2891,10 +2890,10 @@ def f(): return 42 except: pass - """) + """ self.check_warning(source, "'return' in a 'finally' block") - source = textwrap.dedent(""" + source = d""" def f(): try: pass @@ -2903,22 +2902,22 @@ def f(): pass except: return 42 - """) + """ self.check_warning(source, "'return' in a 'finally' block") def test_break_and_continue_in_finally(self): for kw in ('break', 'continue'): - source = textwrap.dedent(f""" + source = fd""" for abc in range(10): try: pass finally: {kw} - """) + """ self.check_warning(source, f"'{kw}' in a 'finally' block") - source = textwrap.dedent(f""" + source = fd""" for abc in range(10): try: pass @@ -2927,10 +2926,10 @@ def test_break_and_continue_in_finally(self): {kw} except: pass - """) + """ self.check_warning(source, f"'{kw}' in a 'finally' block") - source = textwrap.dedent(f""" + source = fd""" for abc in range(10): try: pass @@ -2939,7 +2938,7 @@ def test_break_and_continue_in_finally(self): pass except: {kw} - """) + """ self.check_warning(source, f"'{kw}' in a 'finally' block") @@ -3216,11 +3215,11 @@ def test_with_statement_many_context_managers(self): # See gh-113297 def get_code(n): - code = textwrap.dedent(""" + code = d""" def bug(): with ( a - """) + """ for i in range(n): code += f" as a{i}, a\n" code += "): yield a" @@ -3242,11 +3241,11 @@ def test_async_with_statement_many_context_managers(self): # See gh-116767 def get_code(n): - code = [ textwrap.dedent(""" + code = [ d""" async def bug(): async with ( a - """) ] + """ ] for i in range(n): code.append(f" as a{i}, a\n") code.append("): yield a") @@ -3435,33 +3434,29 @@ def test_deep_invalid_rule(self): def test_except_stmt_invalid_as_expr(self): self._check_error( - textwrap.dedent( - """ + d""" try: pass except ValueError as obj.attr: pass - """ - ), + """, errtext="cannot use except statement with attribute", - lineno=4, - end_lineno=4, + lineno=3, + end_lineno=3, offset=22, end_offset=22 + len("obj.attr"), ) def test_match_stmt_invalid_as_expr(self): self._check_error( - textwrap.dedent( - """ + d""" match 1: case x as obj.attr: ... - """ - ), + """, errtext="cannot use attribute as pattern target", - lineno=3, - end_lineno=3, + lineno=2, + end_lineno=2, offset=15, end_offset=15 + len("obj.attr"), ) diff --git a/Lib/test/test_sys.py b/Lib/test/test_sys.py index f40da0b79aa479..7e5f6f478209e7 100644 --- a/Lib/test/test_sys.py +++ b/Lib/test/test_sys.py @@ -1285,11 +1285,11 @@ def test_no_duplicates_in_meta_path(self): @support.requires_subprocess() def test_orig_argv(self): - code = textwrap.dedent(''' + code = d''' import sys print(sys.argv) print(sys.orig_argv) - ''') + ''' args = [sys.executable, '-I', '-X', 'utf8', '-c', code, 'arg'] proc = subprocess.run(args, check=True, capture_output=True, text=True) expected = [ @@ -1984,14 +1984,14 @@ def test_changing_sys_stderr_and_removing_reference(self): # If the default displayhook doesn't take a strong reference # to sys.stderr the following code can crash. See bpo-43660 # for more details. - code = textwrap.dedent(''' + code = d''' import sys class MyStderr: def write(self, s): sys.stderr = None sys.stderr = MyStderr() 1/0 - ''') + ''' rc, out, err = assert_python_failure('-c', code) self.assertEqual(out, b"") self.assertEqual(err, b"") @@ -2174,12 +2174,10 @@ def test_remote_exec_with_exception(self): def test_new_namespace_for_each_remote_exec(self): """Test that each remote_exec call gets its own namespace.""" - script = textwrap.dedent( - """ + script = d""" assert globals() is not __import__("__main__").__dict__ print("Remote script executed successfully!") """ - ) returncode, stdout, stderr = self._run_remote_exec_test(script) self.assertEqual(returncode, 0) self.assertEqual(stderr, b"") @@ -2264,8 +2262,7 @@ def test_jit_is_enabled(self): def test_jit_is_active(self): available = sys._jit.is_available() - script = textwrap.dedent( - """ + script = d""" import _testcapi import _testinternalcapi import sys @@ -2304,7 +2301,6 @@ def frame_4_interpreter() -> None: frame_4_interpreter() assert sys._jit.is_active() is False """ - ) assert_python_ok("-c", script.format(enabled=False), PYTHON_JIT="0") assert_python_ok("-c", script.format(enabled=available), PYTHON_JIT="1") diff --git a/Lib/test/test_sys_settrace.py b/Lib/test/test_sys_settrace.py index a5e7bbbfad5ffc..ff769ded01f809 100644 --- a/Lib/test/test_sys_settrace.py +++ b/Lib/test/test_sys_settrace.py @@ -10,7 +10,6 @@ import contextlib import os import tempfile -import textwrap import subprocess import warnings try: @@ -1819,7 +1818,7 @@ def test_trace_opcodes_after_settrace(self): """Make sure setting f_trace_opcodes after starting trace works even if it's the first time f_trace_opcodes is being set. GH-103615""" - code = textwrap.dedent(""" + code = d""" import sys def opcode_trace_func(frame, event, arg): @@ -1831,7 +1830,7 @@ def opcode_trace_func(frame, event, arg): sys._getframe().f_trace = opcode_trace_func sys._getframe().f_trace_opcodes = True a = 1 - """) + """ # We can't use context manager because Windows can't execute a file while # it's being written diff --git a/Lib/test/test_sysconfig.py b/Lib/test/test_sysconfig.py index e6f99581f0b7a6..5d63b92dee670e 100644 --- a/Lib/test/test_sysconfig.py +++ b/Lib/test/test_sysconfig.py @@ -6,7 +6,6 @@ import subprocess import shutil import json -import textwrap from unittest.mock import patch from copy import copy @@ -660,7 +659,7 @@ def test_abi_thread(self): @requires_subprocess() def test_makefile_overwrites_config_vars(self): - script = textwrap.dedent(""" + script = d""" import sys, sysconfig data = { @@ -673,7 +672,7 @@ def test_makefile_overwrites_config_vars(self): import json print(json.dumps(data, indent=2)) - """) + """ # We need to run the test inside a virtual environment so that # sys.prefix/sys.exec_prefix have a different value from the diff --git a/Lib/test/test_thread_local_bytecode.py b/Lib/test/test_thread_local_bytecode.py index 6a1ae4064b5daf..7cf50f468bd863 100644 --- a/Lib/test/test_thread_local_bytecode.py +++ b/Lib/test/test_thread_local_bytecode.py @@ -1,5 +1,4 @@ """Tests for thread-local bytecode.""" -import textwrap import unittest from test import support @@ -17,7 +16,7 @@ class TLBCTests(unittest.TestCase): @requires_specialization def test_new_threads_start_with_unspecialized_code(self): - code = textwrap.dedent(""" + code = d""" import dis import queue import threading @@ -43,12 +42,12 @@ def f(a, b, q=None): assert "BINARY_OP_ADD_INT" in all_opnames(get_tlbc(f)) assert "BINARY_OP_ADD_INT" not in all_opnames(q.get()) - """) + """ assert_python_ok("-X", "tlbc=1", "-c", code) @requires_specialization def test_threads_specialize_independently(self): - code = textwrap.dedent(""" + code = d""" import dis import queue import threading @@ -80,11 +79,11 @@ def g(a, b, q=None): t_opnames = all_opnames(q.get()) assert "BINARY_OP_ADD_INT" not in t_opnames assert "BINARY_OP_ADD_UNICODE" in t_opnames - """) + """ assert_python_ok("-X", "tlbc=1", "-c", code) def test_reuse_tlbc_across_threads_different_lifetimes(self): - code = textwrap.dedent(""" + code = d""" import queue import threading @@ -105,12 +104,12 @@ def f(a, b, q=None): assert tlbc_ids[0] == tlbc_ids[1] assert tlbc_ids[1] == tlbc_ids[2] - """) + """ assert_python_ok("-X", "tlbc=1", "-c", code) @support.skip_if_sanitizer("gh-129752: data race on adaptive counter", thread=True) def test_no_copies_if_tlbc_disabled(self): - code = textwrap.dedent(""" + code = d""" import queue import threading @@ -138,11 +137,11 @@ def f(a, b, q=None): assert tlbc_ids[0] == main_tlbc_id assert tlbc_ids[1] == main_tlbc_id assert tlbc_ids[2] == main_tlbc_id - """) + """ assert_python_ok("-X", "tlbc=0", "-c", code) def test_no_specialization_if_tlbc_disabled(self): - code = textwrap.dedent(""" + code = d""" import dis import queue import threading @@ -160,11 +159,11 @@ def f(a, b): f(1, 2) assert "BINARY_OP_ADD_INT" not in all_opnames(f) - """) + """ assert_python_ok("-X", "tlbc=0", "-c", code) def test_generator_throw(self): - code = textwrap.dedent(""" + code = d""" import queue import threading @@ -190,7 +189,7 @@ def f(q): next(gen) main_id = gen.throw(ValueError) assert main_id != q.get() - """) + """ assert_python_ok("-X", "tlbc=1", "-c", code) diff --git a/Lib/test/test_threading.py b/Lib/test/test_threading.py index 3d01804513bde9..4c55b30f60159a 100644 --- a/Lib/test/test_threading.py +++ b/Lib/test/test_threading.py @@ -1178,7 +1178,7 @@ def test_import_from_another_thread(self): # bpo-1596321: If the threading module is first import from a thread # different than the main thread, threading._shutdown() must handle # this case without logging an error at Python exit. - code = textwrap.dedent(''' + code = d''' import _thread import sys @@ -1202,7 +1202,7 @@ def import_threading(): raise Exception('threading is not imported') # don't wait until the thread completes - ''') + ''' rc, out, err = assert_python_ok("-c", code) self.assertEqual(out, b'') self.assertEqual(err, b'') @@ -1232,7 +1232,7 @@ def test_join_daemon_thread_in_finalization(self): # We raise an exception rather than hang. for timeout in (None, 10): with self.subTest(timeout=timeout): - code = textwrap.dedent(f""" + code = fd""" import threading @@ -1260,7 +1260,7 @@ def __del__(self): # cleaned up during the GC that runs after daemon threads # have been forced to exit during finalization. Cycle() - """) + """ rc, out, err = assert_python_ok("-c", code) self.assertEqual(err, b"") self.assertIn(b"got the correct exception", out) @@ -1268,7 +1268,7 @@ def __del__(self): def test_join_finished_daemon_thread_in_finalization(self): # (see previous test) # If the thread is already finished, join() succeeds. - code = textwrap.dedent(""" + code = d""" import threading done = threading.Event() @@ -1290,7 +1290,7 @@ def __del__(self): print('all clear!') Cycle() - """) + """ rc, out, err = assert_python_ok("-c", code) self.assertEqual(err, b"") self.assertIn(b"all clear", out) @@ -1301,7 +1301,7 @@ def test_acquire_daemon_thread_lock_in_finalization(self, lock_class_name): # code (and so, releasing locks), so acquiring a locked lock can not # succeed. # We raise an exception rather than hang. - code = textwrap.dedent(f""" + code = fd""" import threading import time @@ -1345,7 +1345,7 @@ def __del__(self): # cleaned up during the GC that runs after daemon threads # have been forced to exit during finalization. Cycle() - """) + """ rc, out, err = assert_python_ok("-c", code) self.assertEqual(err, b"") self.assertIn(b"got the correct exception", out) @@ -1388,7 +1388,7 @@ def f(): @cpython_only def test_finalize_daemon_thread_hang(self): # gh-87135: tests that daemon threads hang during finalization - script = textwrap.dedent(''' + script = d''' import os import sys import threading @@ -1446,7 +1446,7 @@ def do_flush(*args, **kwargs): # If the follow exit code is retained, `run_during_finalization` # did not run. sys.exit(1) - ''') + ''' assert_python_ok("-c", script) @skip_unless_reliable_fork @@ -1851,7 +1851,7 @@ def _check_allowed(self, before_start='', *, daemon=False, ): import_module("_testinternalcapi") - subinterp_code = textwrap.dedent(f""" + subinterp_code = fd""" import test.support import threading def func(): @@ -1859,9 +1859,9 @@ def func(): t = threading.Thread(target=func, daemon={daemon}) {before_start} t.start() - """) + """ check_multi_interp_extensions = bool(support.Py_GIL_DISABLED) - script = textwrap.dedent(f""" + script = fd""" import test.support test.support.run_in_subinterp_with_config( {subinterp_code!r}, @@ -1873,7 +1873,7 @@ def func(): check_multi_interp_extensions={check_multi_interp_extensions}, own_gil=False, ) - """) + """ with test.support.SuppressCrashReport(): _, _, err = assert_python_ok("-c", script) return err.decode() diff --git a/Lib/test/test_tomllib/test_misc.py b/Lib/test/test_tomllib/test_misc.py index af7ab91bba7cd1..0ba578d088862d 100644 --- a/Lib/test/test_tomllib/test_misc.py +++ b/Lib/test/test_tomllib/test_misc.py @@ -9,7 +9,6 @@ from pathlib import Path import sys import tempfile -import textwrap import unittest from test import support from test.support.script_helper import assert_python_ok @@ -143,8 +142,8 @@ def test_types_import(self): def test_lazy_import(self): # Test the TOML file can be parsed without importing regular # expressions (tomllib._re) - code = textwrap.dedent(""" - import sys, tomllib, textwrap + code = d""" + import sys, tomllib document = textwrap.dedent(''' [metadata] key = "text" @@ -153,6 +152,6 @@ def test_lazy_import(self): ''') tomllib.loads(document) print("lazy import?", 'tomllib._re' not in sys.modules) - """) + """ proc = assert_python_ok("-c", code) self.assertIn(b"lazy import? True", proc.out) diff --git a/Lib/test/test_tools/test_freeze.py b/Lib/test/test_tools/test_freeze.py index 0e7ed67de71067..c63eea07a20760 100644 --- a/Lib/test/test_tools/test_freeze.py +++ b/Lib/test/test_tools/test_freeze.py @@ -1,7 +1,6 @@ """Sanity-check tests for the "freeze" tool.""" import sys -import textwrap import unittest from test import support @@ -25,11 +24,11 @@ class TestFreeze(unittest.TestCase): @support.requires_resource('cpu') # Building Python is slow def test_freeze_simple_script(self): - script = textwrap.dedent(""" + script = d""" import sys print('running...') sys.exit(0) - """) + """ with os_helper.temp_dir() as outdir: outdir, scriptfile, python = helper.prepare(script, outdir) executable = helper.freeze(python, scriptfile, outdir) diff --git a/Lib/test/test_trace.py b/Lib/test/test_trace.py index 19eee19bdea6d5..5bef25a795082b 100644 --- a/Lib/test/test_trace.py +++ b/Lib/test/test_trace.py @@ -4,7 +4,6 @@ from test.support import captured_stdout, requires_resource from test.support.os_helper import (TESTFN, rmtree, unlink) from test.support.script_helper import assert_python_ok, assert_python_failure -import textwrap import unittest from types import FunctionType @@ -456,12 +455,12 @@ class TestCoverageCommandLineOutput(unittest.TestCase): def setUp(self): with open(self.codefile, 'w', encoding='iso-8859-15') as f: - f.write(textwrap.dedent('''\ + f.write(d''' # coding: iso-8859-15 x = 'spœm' if []: print('unreachable') - ''')) + ''') def tearDown(self): unlink(self.codefile) @@ -492,12 +491,12 @@ def test_cover_files_written_with_highlight(self): status, stdout, stderr = assert_python_ok(*argv) self.assertTrue(os.path.exists(self.coverfile)) with open(self.coverfile, encoding='iso-8859-15') as f: - self.assertEqual(f.read(), textwrap.dedent('''\ + self.assertEqual(f.read(), d''' # coding: iso-8859-15 1: x = 'spœm' 1: if []: >>>>>> print('unreachable') - ''')) + ''') class TestCommandLine(unittest.TestCase): @@ -544,7 +543,7 @@ def test_count_and_summary(self): with open(filename, 'w', encoding='utf-8') as fd: self.addCleanup(unlink, filename) self.addCleanup(unlink, coverfilename) - fd.write(textwrap.dedent("""\ + fd.write(d""" x = 1 y = 2 @@ -553,7 +552,7 @@ def f(): for i in range(10): f() - """)) + """) status, stdout, _ = assert_python_ok('-m', 'trace', '-cs', filename, PYTHONIOENCODING='utf-8') stdout = stdout.decode() diff --git a/Lib/test/test_traceback.py b/Lib/test/test_traceback.py index e38d0942e463e9..510aaf79779b6e 100644 --- a/Lib/test/test_traceback.py +++ b/Lib/test/test_traceback.py @@ -175,13 +175,13 @@ def test_no_caret_with_no_debug_ranges_flag(self): unlink(TESTFN) def test_no_caret_with_no_debug_ranges_flag_python_traceback(self): - code = textwrap.dedent(""" + code = d""" import traceback try: x = 1 / 0 except ZeroDivisionError: traceback.print_exc() - """) + """ try: with open(TESTFN, 'w') as f: f.write(code) @@ -192,14 +192,14 @@ def test_no_caret_with_no_debug_ranges_flag_python_traceback(self): lines = stderr.splitlines() self.assertEqual(len(lines), 4) self.assertEqual(lines[0], b'Traceback (most recent call last):') - self.assertIn(b'line 4, in ', lines[1]) + self.assertIn(b'line 3, in ', lines[1]) self.assertEqual(lines[2], b' x = 1 / 0') self.assertEqual(lines[3], b'ZeroDivisionError: division by zero') finally: unlink(TESTFN) def test_recursion_error_during_traceback(self): - code = textwrap.dedent(""" + code = d""" import sys from weakref import ref @@ -213,7 +213,7 @@ def f(): f() except RecursionError: pass - """) + """ try: with open(TESTFN, 'w') as f: f.write(code) @@ -497,7 +497,7 @@ def do_test(firstlines, message, charset, lineno): def test_print_traceback_at_exit(self): # Issue #22599: Ensure that it is possible to use the traceback module # to display an exception at Python exit - code = textwrap.dedent(""" + code = d""" import sys import traceback @@ -518,10 +518,10 @@ def __del__(self): # Keep a reference in the module namespace to call the destructor # when the module is unloaded obj = PrintExceptionAtExit() - """) + """ rc, stdout, stderr = assert_python_ok('-c', code) expected = [b'Traceback (most recent call last):', - b' File "", line 8, in __init__', + b' File "", line 7, in __init__', b' x = 1 / 0', b' ^^^^^', b'ZeroDivisionError: division by zero'] @@ -530,14 +530,14 @@ def __del__(self): @cpython_only def test_lost_io_open(self): # GH-142737: Display the traceback even if io.open is lost - crasher = textwrap.dedent("""\ + crasher = d""" import io import traceback # Trigger fallback mode traceback._print_exception_bltin = None del io.open raise RuntimeError("should not crash") - """) + """ # Create a temporary script to exercise _Py_FindSourceFile with temp_dir() as script_dir: @@ -748,7 +748,7 @@ def f_with_multiline(): def test_caret_multiline_expression_syntax_error(self): # Make sure an expression spanning multiple lines that has # a syntax error is correctly marked with carets. - code = textwrap.dedent(""" + code = d""" def foo(*args, **kwargs): pass @@ -757,7 +757,7 @@ def foo(*args, **kwargs): foo(a, z for z in range(10), b, c) - """) + """ def f_with_multiline(): # Need to defer the compilation until in self.get_exception(..) @@ -772,7 +772,7 @@ def f_with_multiline(): ' ~~~~~~~~^^\n' f' File "{__file__}", line {lineno_f+2}, in f_with_multiline\n' ' return compile(code, "?", "exec")\n' - ' File "?", line 7\n' + ' File "?", line 6\n' ' foo(a, z\n' ' ^' ) @@ -781,12 +781,12 @@ def f_with_multiline(): self.assertEqual(result_lines, expected_f.splitlines()) # Check custom error messages covering multiple lines - code = textwrap.dedent(""" + code = d""" dummy_call( "dummy value" foo="bar", ) - """) + """ def f_with_multiline(): # Need to defer the compilation until in self.get_exception(..) @@ -801,7 +801,7 @@ def f_with_multiline(): ' ~~~~~~~~^^\n' f' File "{__file__}", line {lineno_f+2}, in f_with_multiline\n' ' return compile(code, "?", "exec")\n' - ' File "?", line 3\n' + ' File "?", line 2\n' ' "dummy value"\n' ' ^^^^^^^^^^^^^' ) @@ -2650,18 +2650,18 @@ def __str__(self): self.assertEqual(exp, err) def test_exception_angle_bracketed_filename(self): - src = textwrap.dedent(""" + src = d""" try: raise ValueError(42) except Exception as e: exc = e - """) + """ code = compile(src, "", "exec") g, l = {}, {} exec(code, g, l) err = self.get_report(l['exc']) - exp = ' File "", line 3, in \nValueError: 42\n' + exp = ' File "", line 2, in \nValueError: 42\n' self.assertIn(exp, err) def test_exception_modulename_not_unicode(self): @@ -4700,41 +4700,41 @@ def callable(): return result_lines[0] def test_import_from_suggestions(self): - substitution = textwrap.dedent("""\ + substitution = d""" noise = more_noise = a = bc = None blech = None - """) + """ - elimination = textwrap.dedent(""" + elimination = d""" noise = more_noise = a = bc = None blch = None - """) + """ - addition = textwrap.dedent(""" + addition = d""" noise = more_noise = a = bc = None bluchin = None - """) + """ - substitutionOverElimination = textwrap.dedent(""" + substitutionOverElimination = d""" blach = None bluc = None - """) + """ - substitutionOverAddition = textwrap.dedent(""" + substitutionOverAddition = d""" blach = None bluchi = None - """) + """ - eliminationOverAddition = textwrap.dedent(""" + eliminationOverAddition = d""" blucha = None bluc = None - """) + """ - caseChangeOverSubstitution = textwrap.dedent(""" + caseChangeOverSubstitution = d""" Luch = None fluch = None BLuch = None - """) + """ for code, suggestion in [ (addition, "'bluchin'?"), @@ -4761,10 +4761,10 @@ def test_import_from_suggestions_underscored(self): self.assertNotIn("'_bluch'", self.get_import_from_suggestion(code, 'bluch')) def test_import_from_suggestions_non_string(self): - modWithNonStringAttr = textwrap.dedent("""\ + modWithNonStringAttr = d""" globals()[0] = 1 bluch = 1 - """) + """ self.assertIn("'bluch'", self.get_import_from_suggestion(modWithNonStringAttr, 'blech')) def test_import_from_suggestions_do_not_trigger_for_long_attributes(self): @@ -5281,11 +5281,11 @@ def test_no_site_package_flavour(self): b"or to enable your virtual environment?"), stderr ) - code = """ + code = d""" import sys sys.stdlib_module_names = sys.stdlib_module_names + ("boo",) import boo - """ + """ _, _, stderr = assert_python_failure('-S', '-c', code) self.assertNotIn( @@ -5295,22 +5295,22 @@ def test_no_site_package_flavour(self): ) def test_missing_stdlib_module(self): - code = """ + code = d""" import sys sys.stdlib_module_names |= {'spam'} import spam - """ + """ _, _, stderr = assert_python_failure('-S', '-c', code) self.assertIn(b"Standard library module 'spam' was not found", stderr) - code = """ + code = d""" import sys import traceback traceback._MISSING_STDLIB_MODULE_MESSAGES = {'spam': "Install 'spam4life' for 'spam'"} sys.stdlib_module_names |= {'spam'} import spam - """ + """ _, _, stderr = assert_python_failure('-S', '-c', code) self.assertIn(b"Install 'spam4life' for 'spam'", stderr) @@ -5613,16 +5613,16 @@ def test_attribute_error_does_not_reify_lazy_imports(self): """Printing an AttributeError should not trigger lazy import reification.""" # pkg.bar prints "BAR_MODULE_LOADED" when imported. # If lazy import is reified during suggestion computation, we'll see it. - code = textwrap.dedent(""" + code = d""" lazy import test.test_lazy_import.data.pkg.bar test.test_lazy_import.data.pkg.nonexistent - """) + """ rc, stdout, stderr = assert_python_failure('-c', code) self.assertNotIn(b"BAR_MODULE_LOADED", stdout) def test_traceback_formatting_does_not_reify_lazy_imports(self): """Formatting a traceback should not trigger lazy import reification.""" - code = textwrap.dedent(""" + code = d""" import traceback lazy import test.test_lazy_import.data.pkg.bar try: @@ -5630,18 +5630,18 @@ def test_traceback_formatting_does_not_reify_lazy_imports(self): except AttributeError: traceback.format_exc() print("OK") - """) + """ rc, stdout, stderr = assert_python_ok('-c', code) self.assertIn(b"OK", stdout) self.assertNotIn(b"BAR_MODULE_LOADED", stdout) def test_suggestion_still_works_for_non_lazy_attributes(self): """Suggestions should still work for non-lazy module attributes.""" - code = textwrap.dedent(""" + code = d""" lazy import test.test_lazy_import.data.pkg.bar # Typo for __name__ test.test_lazy_import.data.pkg.__nme__ - """) + """ rc, stdout, stderr = assert_python_failure('-c', code) self.assertIn(b"__name__", stderr) self.assertNotIn(b"BAR_MODULE_LOADED", stdout) diff --git a/Lib/test/test_tracemalloc.py b/Lib/test/test_tracemalloc.py index 9d3ff8a620b6f2..a08eb53ea2c638 100644 --- a/Lib/test/test_tracemalloc.py +++ b/Lib/test/test_tracemalloc.py @@ -1,7 +1,6 @@ import contextlib import os import sys -import textwrap import tracemalloc import unittest from unittest.mock import patch @@ -1121,7 +1120,7 @@ def test_tracemalloc_track_race(self): _testcapi.tracemalloc_track_race() def test_late_untrack(self): - code = textwrap.dedent(f""" + code = fd""" from test import support import tracemalloc import _testcapi @@ -1140,7 +1139,7 @@ def __del__(self, untrack=_testcapi.tracemalloc_untrack): tracemalloc.start() obj = Tracked(domain, 1024 * 1024) support.late_deletion(obj) - """) + """ assert_python_ok("-c", code) diff --git a/Lib/test/test_type_annotations.py b/Lib/test/test_type_annotations.py index b751f825bb97d5..ec463bdf160e18 100644 --- a/Lib/test/test_type_annotations.py +++ b/Lib/test/test_type_annotations.py @@ -493,7 +493,7 @@ class C: self.assertEqual(ns["C"].__annotations__, {"__classdict__": int}) def test_future_annotations(self): - code = """ + code = d""" from __future__ import annotations def f(x: int) -> int: pass @@ -506,14 +506,14 @@ def f(x: int) -> int: pass self.assertEqual(f.__annotations__, annos) def test_set_annotations(self): - function_code = textwrap.dedent(""" + function_code = d""" def f(x: int): pass - """) - class_code = textwrap.dedent(""" + """ + class_code = d""" class f: x: int - """) + """ for future in (False, True): for label, code in (("function", function_code), ("class", class_code)): with self.subTest(future=future, label=label): @@ -530,7 +530,7 @@ class f: def test_name_clash_with_format(self): # this test would fail if __annotate__'s parameter was called "format" # during symbol table construction - code = """ + code = d""" class format: pass def f(x: format): pass @@ -539,7 +539,7 @@ def f(x: format): pass f = ns["f"] self.assertEqual(f.__annotations__, {"x": ns["format"]}) - code = """ + code = d""" class Outer: class format: pass @@ -548,7 +548,7 @@ def meth(self, x: format): ... ns = run_code(code) self.assertEqual(ns["Outer"].meth.__annotations__, {"x": ns["Outer"].format}) - code = """ + code = d""" def f(format): def inner(x: format): pass return inner @@ -557,7 +557,7 @@ def inner(x: format): pass ns = run_code(code) self.assertEqual(ns["res"].__annotations__, {"x": "closure var"}) - code = """ + code = d""" def f(x: format): pass """ @@ -565,7 +565,7 @@ def f(x: format): # picks up the format() builtin self.assertEqual(ns["f"].__annotations__, {"x": format}) - code = """ + code = d""" def outer(): def f(x: format): pass @@ -603,7 +603,7 @@ def check_scopes(self, code, true_annos, false_annos): expected) def test_with(self): - code = """ + code = d""" class Swallower: def __enter__(self): pass @@ -616,27 +616,27 @@ def __exit__(self, *args): about_to_raise: int raise Exception in_with: "with" - """ + """ self.check_scopes(code, {"about_to_raise": int}, {"in_with": "with"}) def test_simple_if(self): - code = """ + code = d""" if {cond}: in_if: "if" else: in_if: "else" - """ + """ self.check_scopes(code, {"in_if": "if"}, {"in_if": "else"}) def test_if_elif(self): - code = """ + code = d""" if not len: in_if: "if" elif {cond}: in_elif: "elif" else: in_else: "else" - """ + """ self.check_scopes( code, {"in_elif": "elif"}, @@ -644,7 +644,7 @@ def test_if_elif(self): ) def test_try(self): - code = """ + code = d""" try: if {cond}: raise Exception @@ -653,7 +653,7 @@ def test_try(self): in_except: "except" finally: in_finally: "finally" - """ + """ self.check_scopes( code, {"in_except": "except", "in_finally": "finally"}, @@ -661,7 +661,7 @@ def test_try(self): ) def test_try_star(self): - code = """ + code = d""" try: if {cond}: raise Exception @@ -670,7 +670,7 @@ def test_try_star(self): in_except_star: "except" finally: in_finally: "finally" - """ + """ self.check_scopes( code, {"in_except_star": "except", "in_finally": "finally"}, @@ -678,13 +678,13 @@ def test_try_star(self): ) def test_while(self): - code = """ + code = d""" while {cond}: in_while: "while" break else: in_else: "else" - """ + """ self.check_scopes( code, {"in_while": "while"}, @@ -692,12 +692,12 @@ def test_while(self): ) def test_for(self): - code = """ + code = d""" for _ in ([1] if {cond} else []): in_for: "for" else: in_else: "else" - """ + """ self.check_scopes( code, {"in_for": "for", "in_else": "else"}, @@ -705,13 +705,13 @@ def test_for(self): ) def test_match(self): - code = """ + code = d""" match {cond}: case True: x: "true" case False: x: "false" - """ + """ self.check_scopes( code, {"x": "true"}, @@ -719,12 +719,12 @@ def test_match(self): ) def test_nesting_override(self): - code = """ + code = d""" if {cond}: x: "foo" if {cond}: x: "bar" - """ + """ self.check_scopes( code, {"x": "bar"}, @@ -732,7 +732,7 @@ def test_nesting_override(self): ) def test_nesting_outer(self): - code = """ + code = d""" if {cond}: outer_before: "outer_before" if len: @@ -740,7 +740,7 @@ def test_nesting_outer(self): else: inner_else: "inner_else" outer_after: "outer_after" - """ + """ self.check_scopes( code, {"outer_before": "outer_before", "inner_if": "inner_if", @@ -749,7 +749,7 @@ def test_nesting_outer(self): ) def test_nesting_inner(self): - code = """ + code = d""" if len: outer_before: "outer_before" if {cond}: @@ -757,7 +757,7 @@ def test_nesting_inner(self): else: inner_else: "inner_else" outer_after: "outer_after" - """ + """ self.check_scopes( code, {"outer_before": "outer_before", "inner_if": "inner_if", @@ -767,7 +767,7 @@ def test_nesting_inner(self): ) def test_non_name_annotations(self): - code = """ + code = d""" before: "before" if {cond}: a = "x" @@ -776,7 +776,7 @@ def test_non_name_annotations(self): a = object() a.b: str after: "after" - """ + """ expected = {"before": "before", "after": "after"} self.check_scopes(code, expected, expected) @@ -825,7 +825,7 @@ def test_complex_comprehension_inlining(self): compile(case, "", "exec") def test_complex_comprehension_inlining_exec(self): - code = """ + code = d""" unique_name_1 = unique_name_5 = [1] name_0 = 42 unique_name_7: {name_0 for name_0 in unique_name_1} @@ -834,7 +834,7 @@ def test_complex_comprehension_inlining_exec(self): for unique_name_6 in [1] if name_0 } - """ + """ mod = build_module(code) annos = mod.__annotations__ self.assertEqual(annos.keys(), {"unique_name_7", "unique_name_2"}) @@ -844,7 +844,7 @@ def test_complex_comprehension_inlining_exec(self): self.assertEqual(lamb(), 42) def test_annotate_qualname(self): - code = """ + code = d""" def f() -> None: def nested() -> None: pass return nested diff --git a/Lib/test/test_type_params.py b/Lib/test/test_type_params.py index b6588269e1d0c6..92418c140917c6 100644 --- a/Lib/test/test_type_params.py +++ b/Lib/test/test_type_params.py @@ -163,7 +163,7 @@ def test_compile_error_in_type_param_bound(self): class TypeParamsNonlocalTest(unittest.TestCase): def test_nonlocal_disallowed_01(self): - code = """ + code = d""" def outer(): X = 1 def inner[X](): @@ -173,22 +173,22 @@ def inner[X](): check_syntax_error(self, code) def test_nonlocal_disallowed_02(self): - code = """ + code = d""" def outer2[T](): def inner1(): nonlocal T - """ + """ check_syntax_error(self, textwrap.dedent(code)) def test_nonlocal_disallowed_03(self): - code = """ + code = d""" class Cls[T]: nonlocal T - """ + """ check_syntax_error(self, textwrap.dedent(code)) def test_nonlocal_allowed(self): - code = """ + code = d""" def func[T](): T = "func" def inner(): @@ -196,7 +196,7 @@ def inner(): T = "inner" inner() assert T == "inner" - """ + """ ns = run_code(code) func = ns["func"] T, = func.__type_params__ @@ -230,7 +230,7 @@ class ClassA[A, B](metaclass=MyMeta[A, B]): self.assertIs(type(cls), meta) def test_class_access_03(self): - code = """ + code = d""" def my_decorator(a): ... @my_decorator(A) @@ -252,7 +252,7 @@ def func[A, B](a: dict[A, B]): self.assertEqual(func.__annotations__["a"], dict[A, B]) def test_function_access_02(self): - code = """ + code = d""" def func[A](a = list[A]()): ... """ @@ -261,7 +261,7 @@ def func[A](a = list[A]()): run_code(code) def test_function_access_03(self): - code = """ + code = d""" def my_decorator(a): ... @my_decorator(A) @@ -304,7 +304,7 @@ def funcD[D](self): self.assertEqual(classC().funcD()(), (A, B, C, D)) def test_out_of_scope_01(self): - code = """ + code = d""" class ClassA[T]: ... x = T """ @@ -313,7 +313,7 @@ class ClassA[T]: ... run_code(code) def test_out_of_scope_02(self): - code = """ + code = d""" class ClassA[A]: def funcB[B](self): ... @@ -429,14 +429,14 @@ def F[T: [lambda: T for T in (T, [1])[1]]](): return [lambda: T for T in T.__nam self.assertEqual(func(), 1) def test_gen_exp_in_nested_class(self): - code = """ + code = d""" from test.test_type_params import make_base class C[T]: T = "class" class Inner(make_base(T for _ in (1,)), make_base(T)): pass - """ + """ C = run_code(code)["C"] T, = C.__type_params__ base1, base2 = C.Inner.__bases__ @@ -444,14 +444,14 @@ class Inner(make_base(T for _ in (1,)), make_base(T)): self.assertEqual(base2.__arg__, "class") def test_gen_exp_in_nested_generic_class(self): - code = """ + code = d""" from test.test_type_params import make_base class C[T]: T = "class" class Inner[U](make_base(T for _ in (1,)), make_base(T)): pass - """ + """ ns = run_code(code) inner = ns["C"].Inner base1, base2, _ = inner.__bases__ @@ -459,14 +459,14 @@ class Inner[U](make_base(T for _ in (1,)), make_base(T)): self.assertEqual(base2.__arg__, "class") def test_listcomp_in_nested_class(self): - code = """ + code = d""" from test.test_type_params import make_base class C[T]: T = "class" class Inner(make_base([T for _ in (1,)]), make_base(T)): pass - """ + """ C = run_code(code)["C"] T, = C.__type_params__ base1, base2 = C.Inner.__bases__ @@ -474,14 +474,14 @@ class Inner(make_base([T for _ in (1,)]), make_base(T)): self.assertEqual(base2.__arg__, "class") def test_listcomp_in_nested_generic_class(self): - code = """ + code = d""" from test.test_type_params import make_base class C[T]: T = "class" class Inner[U](make_base([T for _ in (1,)]), make_base(T)): pass - """ + """ ns = run_code(code) inner = ns["C"].Inner base1, base2, _ = inner.__bases__ @@ -489,24 +489,24 @@ class Inner[U](make_base([T for _ in (1,)]), make_base(T)): self.assertEqual(base2.__arg__, "class") def test_gen_exp_in_generic_method(self): - code = """ + code = d""" class C[T]: T = "class" def meth[U](x: (T for _ in (1,)), y: T): pass - """ + """ ns = run_code(code) meth = ns["C"].meth self.assertEqual(list(meth.__annotations__["x"]), [ns["C"].__type_params__[0]]) self.assertEqual(meth.__annotations__["y"], "class") def test_nested_scope_in_generic_alias(self): - code = """ + code = d""" T = "global" class C: T = "class" {} - """ + """ cases = [ "type Alias[T] = (T for _ in (1,))", "type Alias = (T for _ in (1,))", @@ -524,34 +524,34 @@ class C: self.assertEqual(value, "global") def test_lambda_in_alias_in_class(self): - code = """ + code = d""" T = "global" class C: T = "class" type Alias = lambda: T - """ + """ C = run_code(code)["C"] self.assertEqual(C.Alias.__value__(), "global") def test_lambda_in_alias_in_generic_class(self): - code = """ + code = d""" class C[T]: T = "class" type Alias = lambda: T - """ + """ C = run_code(code)["C"] self.assertIs(C.Alias.__value__(), C.__type_params__[0]) def test_lambda_in_generic_alias_in_class(self): # A lambda nested in the alias cannot see the class scope, but can see # a surrounding annotation scope. - code = """ + code = d""" T = U = "global" class C: T = "class" U = "class" type Alias[T] = lambda: (T, U) - """ + """ C = run_code(code)["C"] T, U = C.Alias.__value__() self.assertIs(T, C.Alias.__type_params__[0]) @@ -560,12 +560,12 @@ class C: def test_lambda_in_generic_alias_in_generic_class(self): # A lambda nested in the alias cannot see the class scope, but can see # a surrounding annotation scope. - code = """ + code = d""" class C[T, U]: T = "class" U = "class" type Alias[T] = lambda: (T, U) - """ + """ C = run_code(code)["C"] T, U = C.Alias.__value__() self.assertIs(T, C.Alias.__type_params__[0]) @@ -987,10 +987,10 @@ class C2[T](*bases): pass class TypeParamsTraditionalTypeVarsTest(unittest.TestCase): def test_traditional_01(self): - code = """ + code = d""" from typing import Generic class ClassA[T](Generic[T]): ... - """ + """ with self.assertRaisesRegex(TypeError, r"Cannot inherit from Generic\[...\] multiple times."): run_code(code) @@ -1145,12 +1145,12 @@ class ClassA: self.assertEqual(ClassA.__type_params__, ()) def test_typeparams_dunder_class_03(self): - code = """ + code = d""" class ClassA[A](): pass ClassA.__type_params__ = () params = ClassA.__type_params__ - """ + """ ns = run_code(code) self.assertEqual(ns["params"], ()) @@ -1174,11 +1174,11 @@ def func1(): self.assertEqual(func1.__type_params__, ()) def test_typeparams_dunder_function_03(self): - code = """ + code = d""" def func[A](): pass func.__type_params__ = () - """ + """ ns = run_code(code) self.assertEqual(ns["func"].__type_params__, ()) @@ -1282,7 +1282,7 @@ class NewStyle[T]: class TypeParamsRuntimeTest(unittest.TestCase): def test_name_error(self): # gh-109118: This crashed the interpreter due to a refcounting bug - code = """ + code = d""" class name_2[name_5]: class name_4[name_5](name_0): pass @@ -1291,7 +1291,7 @@ class name_4[name_5](name_0): run_code(code) # Crashed with a slightly different stack trace - code = """ + code = d""" class name_2[name_5]: class name_4[name_5: name_5](name_0): pass @@ -1300,7 +1300,7 @@ class name_4[name_5: name_5](name_0): run_code(code) def test_broken_class_namespace(self): - code = """ + code = d""" class WeirdMapping(dict): def __missing__(self, key): if key == "T": diff --git a/Lib/test/test_types.py b/Lib/test/test_types.py index 2084b30d71ff6c..e4f50f82ef4976 100644 --- a/Lib/test/test_types.py +++ b/Lib/test/test_types.py @@ -16,7 +16,6 @@ import pickle import locale import sys -import textwrap import types import unittest.mock import weakref @@ -2596,7 +2595,7 @@ def setUpClass(cls): def test_static_types_inherited_slots(self): rch, sch = self.create_channel() - script = textwrap.dedent(""" + script = d""" import test.support results = [] for cls in test.support.iter_builtin_types(): @@ -2606,7 +2605,7 @@ def test_static_types_inherited_slots(self): results.append(res) results = tuple((repr(c), a, repr(w)) for c, a, w in results) sch.send_nowait(results) - """) + """ def collate_results(raw): results = {} for cls, attr, wrapper in raw: diff --git a/Lib/test/test_typing.py b/Lib/test/test_typing.py index ed07503cd63f12..5ce56f9c6ac082 100644 --- a/Lib/test/test_typing.py +++ b/Lib/test/test_typing.py @@ -5267,11 +5267,11 @@ class C2: # Test stringified annotations scope = {} - exec(textwrap.dedent(''' + exec(d''' from __future__ import annotations class C3: a: List[list["C2"]] - '''), scope) + ''', scope) C3 = scope['C3'] self.assertEqual(C3.__annotations__['a'], "List[list['C2']]") self.assertEqual( @@ -8344,7 +8344,7 @@ class Z(NamedTuple): self.assertEqual(Z.__annotate__(annotationlib.Format.STRING), {"a": "None", "b": "str"}) def test_future_annotations(self): - code = """ + code = d""" from __future__ import annotations from typing import NamedTuple class X(NamedTuple): diff --git a/Lib/test/test_unittest/test_result.py b/Lib/test/test_unittest/test_result.py index 3f44e617303f81..97a206db63046e 100644 --- a/Lib/test/test_unittest/test_result.py +++ b/Lib/test/test_unittest/test_result.py @@ -868,16 +868,18 @@ def testBufferOutputAddErrorOrFailure(self): self.assertEqual(len(result_list), 1) test, message = result_list[0] - expectedOutMessage = textwrap.dedent(""" + expectedOutMessage = d""" + Stdout: foo - """) + """ expectedErrMessage = '' if include_error: - expectedErrMessage = textwrap.dedent(""" + expectedErrMessage = d""" + Stderr: bar - """) + """ expectedFullMessage = 'A traceback%s%s' % (expectedOutMessage, expectedErrMessage) diff --git a/Lib/test/test_utf8_mode.py b/Lib/test/test_utf8_mode.py index b8e49440c9f7da..050ec290d025ac 100644 --- a/Lib/test/test_utf8_mode.py +++ b/Lib/test/test_utf8_mode.py @@ -5,7 +5,6 @@ import locale import subprocess import sys -import textwrap import unittest from test import support from test.support.script_helper import assert_python_ok, assert_python_failure @@ -98,11 +97,11 @@ def test_env_var(self): out.rstrip()) def test_filesystemencoding(self): - code = textwrap.dedent(''' + code = d''' import sys print("{}/{}".format(sys.getfilesystemencoding(), sys.getfilesystemencodeerrors())) - ''') + ''' if MS_WINDOWS: expected = 'utf-8/surrogatepass' @@ -121,12 +120,12 @@ def test_filesystemencoding(self): self.assertEqual(out, 'mbcs/replace') def test_stdio(self): - code = textwrap.dedent(''' + code = d''' import sys print(f"stdin: {sys.stdin.encoding}/{sys.stdin.errors}") print(f"stdout: {sys.stdout.encoding}/{sys.stdout.errors}") print(f"stderr: {sys.stderr.encoding}/{sys.stderr.errors}") - ''') + ''' out = self.get_output('-X', 'utf8', '-c', code, PYTHONIOENCODING='') @@ -151,12 +150,12 @@ def test_stdio(self): 'stderr: utf-8/backslashreplace']) def test_io(self): - code = textwrap.dedent(''' + code = d''' import sys filename = sys.argv[1] with open(filename) as fp: print(f"{fp.encoding}/{fp.errors}") - ''') + ''' filename = __file__ out = self.get_output('-c', code, filename, PYTHONUTF8='1') @@ -171,13 +170,13 @@ def _check_io_encoding(self, module, encoding=None, errors=None): args.append(f'encoding={encoding!r}') if errors: args.append(f'errors={errors!r}') - code = textwrap.dedent(''' + code = d''' import sys from %s import open filename = sys.argv[1] with open(filename, %s) as fp: print(f"{fp.encoding}/{fp.errors}") - ''') % (module, ', '.join(args)) + ''' % (module, ', '.join(args)) out = self.get_output('-c', code, filename, PYTHONUTF8='1') diff --git a/Lib/test/test_warnings/__init__.py b/Lib/test/test_warnings/__init__.py index bf1bcf8e6ed5d9..797b6117b1a421 100644 --- a/Lib/test/test_warnings/__init__.py +++ b/Lib/test/test_warnings/__init__.py @@ -7,7 +7,6 @@ from io import StringIO import re import sys -import textwrap import types from typing import overload, get_overloads import unittest @@ -1312,14 +1311,14 @@ def test_tracemalloc(self): self.addCleanup(os_helper.unlink, os_helper.TESTFN) with open(os_helper.TESTFN, 'w', encoding="utf-8") as fp: - fp.write(textwrap.dedent(""" + fp.write(d""" def func(): f = open(__file__, "rb") # Emit ResourceWarning f = None func() - """)) + """) def run(*args): res = assert_python_ok(*args, PYTHONIOENCODING='utf-8') @@ -1333,24 +1332,24 @@ def run(*args): # tracemalloc disabled filename = os.path.abspath(os_helper.TESTFN) stderr = run('-Wd', os_helper.TESTFN) - expected = textwrap.dedent(f''' - {filename}:5: ResourceWarning: unclosed file <...> + expected = fd''' + {filename}:4: ResourceWarning: unclosed file <...> f = None ResourceWarning: Enable tracemalloc to get the object allocation traceback - ''').strip() + '''.strip() self.assertEqual(stderr, expected) # tracemalloc enabled stderr = run('-Wd', '-X', 'tracemalloc=2', os_helper.TESTFN) - expected = textwrap.dedent(f''' - {filename}:5: ResourceWarning: unclosed file <...> + expected = fd''' + {filename}:4: ResourceWarning: unclosed file <...> f = None Object allocated at (most recent call last): - File "{filename}", lineno 7 + File "{filename}", lineno 6 func() - File "{filename}", lineno 3 + File "{filename}", lineno 2 f = open(__file__, "rb") - ''').strip() + '''.strip() self.assertEqual(stderr, expected) diff --git a/Lib/test/test_weakref.py b/Lib/test/test_weakref.py index 0c4717521f16f6..3916b6b133415a 100644 --- a/Lib/test/test_weakref.py +++ b/Lib/test/test_weakref.py @@ -10,7 +10,6 @@ import threading import time import random -import textwrap from test import support from test.support import script_helper, ALWAYS_EQ @@ -1028,7 +1027,7 @@ def __del__(self): pass def test_no_memory_when_clearing(self): # gh-118331: Make sure we do not raise an exception from the destructor # when clearing weakrefs if allocating the intermediate tuple fails. - code = textwrap.dedent(""" + code = d""" import _testcapi import weakref @@ -1044,7 +1043,7 @@ def callback(obj): wrs = [weakref.ref(obj, callback) for _ in range(50)] _testcapi.set_nomemory(0) del obj - """).strip() + """.strip() res, _ = script_helper.run_python_until_end("-c", code) stderr = res.err.decode("ascii", "backslashreplace") self.assertNotRegex(stderr, "_Py_Dealloc: Deallocator of type 'TestObj'") diff --git a/Lib/test/test_xml_etree.py b/Lib/test/test_xml_etree.py index acec4ec2ca257c..e8171af79a6264 100644 --- a/Lib/test/test_xml_etree.py +++ b/Lib/test/test_xml_etree.py @@ -15,7 +15,6 @@ import pickle import pyexpat import sys -import textwrap import types import unittest import unittest.mock as mock @@ -693,7 +692,7 @@ def end_ns(self, prefix): builder = Builder() parser = ET.XMLParser(target=builder) - parser.feed(textwrap.dedent("""\ + parser.feed(d""" @@ -701,7 +700,7 @@ def end_ns(self, prefix): texttail - """)) + """) self.assertEqual(builder, [ ('end-ns', 'a'), ('end-ns', 'p'), @@ -4721,7 +4720,7 @@ def test_simple_roundtrip(self): self.assertEqual(c14n_roundtrip(xml), xml) def test_c14n_exclusion(self): - xml = textwrap.dedent("""\ + xml = d""" abtext @@ -4731,7 +4730,7 @@ def test_c14n_exclusion(self): dtext - """) + """ self.assertEqual( c14n_roundtrip(xml, strip_text=True), '' diff --git a/Lib/test/test_zipimport_support.py b/Lib/test/test_zipimport_support.py index 2b28f46149b4ff..8e04170f811efd 100644 --- a/Lib/test/test_zipimport_support.py +++ b/Lib/test/test_zipimport_support.py @@ -6,7 +6,6 @@ import os import os.path import sys -import textwrap import zipfile import zipimport import doctest @@ -188,14 +187,14 @@ def test_doctest_issue4197(self): del sys.modules["test_zipped_doctest"] def test_doctest_main_issue4197(self): - test_src = textwrap.dedent("""\ + test_src = d""" class Test: ">>> 'line 2'" pass import doctest doctest.testmod() - """) + """ pattern = 'File "%s", line 2, in %s' with os_helper.temp_dir() as d: script_name = make_script(d, 'script', test_src) @@ -217,13 +216,13 @@ class Test: self.assertIn(expected.encode('utf-8'), out) def test_pdb_issue4201(self): - test_src = textwrap.dedent("""\ + test_src = d""" def f(): pass import pdb pdb.Pdb(nosigint=True).runcall(f) - """) + """ with os_helper.temp_dir() as d: script_name = make_script(d, 'script', test_src) p = spawn_python(script_name)