Skip to content

Commit 35715d1

Browse files
authored
bpo-43651: PEP 597: Fix EncodingWarning in some tests (GH-25145)
* test_asyncio * test_bz2 * test_math * test_cmath * test_cmd_line * test_cmd_line_script * test_compile * test_contextlib * test_profile * ctypes/test/test_find * test_multiprocessing * test_configparser * test_csv * test_dbm_dumb * test_decimal * test_difflib * os.fdopen() calls io.text_encoding() to emit EncodingWarning for right place.
1 parent dc6d3e1 commit 35715d1

19 files changed

+78
-75
lines changed

Lib/ctypes/test/test_find.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -90,7 +90,7 @@ def test_find_on_libpath(self):
9090
srcname = os.path.join(d, 'dummy.c')
9191
libname = 'py_ctypes_test_dummy'
9292
dstname = os.path.join(d, 'lib%s.so' % libname)
93-
with open(srcname, 'w') as f:
93+
with open(srcname, 'wb') as f:
9494
pass
9595
self.assertTrue(os.path.exists(srcname))
9696
# compile the file to a shared library

Lib/os.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1020,11 +1020,13 @@ def __iter__(self):
10201020
__all__.append("popen")
10211021

10221022
# Supply os.fdopen()
1023-
def fdopen(fd, *args, **kwargs):
1023+
def fdopen(fd, mode="r", buffering=-1, encoding=None, *args, **kwargs):
10241024
if not isinstance(fd, int):
10251025
raise TypeError("invalid fd type (%s, expected integer)" % type(fd))
10261026
import io
1027-
return io.open(fd, *args, **kwargs)
1027+
if "b" not in mode:
1028+
encoding = io.text_encoding(encoding)
1029+
return io.open(fd, mode, buffering, encoding, *args, **kwargs)
10281030

10291031

10301032
# For testing purposes, make sure the function is available when the C

Lib/test/_test_multiprocessing.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -826,7 +826,7 @@ def test_stderr_flush(self):
826826
proc = self.Process(target=self._test_stderr_flush, args=(testfn,))
827827
proc.start()
828828
proc.join()
829-
with open(testfn, 'r') as f:
829+
with open(testfn, encoding="utf-8") as f:
830830
err = f.read()
831831
# The whole traceback was printed
832832
self.assertIn("ZeroDivisionError", err)
@@ -836,14 +836,14 @@ def test_stderr_flush(self):
836836
@classmethod
837837
def _test_stderr_flush(cls, testfn):
838838
fd = os.open(testfn, os.O_WRONLY | os.O_CREAT | os.O_EXCL)
839-
sys.stderr = open(fd, 'w', closefd=False)
839+
sys.stderr = open(fd, 'w', encoding="utf-8", closefd=False)
840840
1/0 # MARKER
841841

842842

843843
@classmethod
844844
def _test_sys_exit(cls, reason, testfn):
845845
fd = os.open(testfn, os.O_WRONLY | os.O_CREAT | os.O_EXCL)
846-
sys.stderr = open(fd, 'w', closefd=False)
846+
sys.stderr = open(fd, 'w', encoding="utf-8", closefd=False)
847847
sys.exit(reason)
848848

849849
def test_sys_exit(self):
@@ -864,7 +864,7 @@ def test_sys_exit(self):
864864
join_process(p)
865865
self.assertEqual(p.exitcode, 1)
866866

867-
with open(testfn, 'r') as f:
867+
with open(testfn, encoding="utf-8") as f:
868868
content = f.read()
869869
self.assertEqual(content.rstrip(), str(reason))
870870

@@ -1118,7 +1118,7 @@ def test_task_done(self):
11181118
def test_no_import_lock_contention(self):
11191119
with os_helper.temp_cwd():
11201120
module_name = 'imported_by_an_imported_module'
1121-
with open(module_name + '.py', 'w') as f:
1121+
with open(module_name + '.py', 'w', encoding="utf-8") as f:
11221122
f.write("""if 1:
11231123
import multiprocessing
11241124

Lib/test/multibytecodec_support.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -296,7 +296,7 @@ def setUp(self):
296296
self.skipTest("Could not retrieve "+self.mapfileurl)
297297

298298
def open_mapping_file(self):
299-
return support.open_urlresource(self.mapfileurl)
299+
return support.open_urlresource(self.mapfileurl, encoding="utf-8")
300300

301301
def test_mapping_file(self):
302302
if self.mapfileurl.endswith('.xml'):

Lib/test/test_asyncio/test_base_events.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2096,7 +2096,7 @@ def test_blocking_socket(self):
20962096

20972097
def test_nonbinary_file(self):
20982098
sock = self.make_socket()
2099-
with open(os_helper.TESTFN, 'r') as f:
2099+
with open(os_helper.TESTFN, encoding="utf-8") as f:
21002100
with self.assertRaisesRegex(ValueError, "binary mode"):
21012101
self.run_loop(self.loop.sock_sendfile(sock, f))
21022102

Lib/test/test_asyncio/test_events.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1349,7 +1349,7 @@ def test_unclosed_pipe_transport(self):
13491349

13501350
rpipe, wpipe = os.pipe()
13511351
rpipeobj = io.open(rpipe, 'rb', 1024)
1352-
wpipeobj = io.open(wpipe, 'w', 1024)
1352+
wpipeobj = io.open(wpipe, 'w', 1024, encoding="utf-8")
13531353

13541354
async def connect():
13551355
read_transport, _ = await loop.connect_read_pipe(

Lib/test/test_bz2.py

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -922,14 +922,14 @@ def test_text_modes(self):
922922
for mode in ("wt", "xt"):
923923
if mode == "xt":
924924
unlink(self.filename)
925-
with self.open(self.filename, mode) as f:
925+
with self.open(self.filename, mode, encoding="ascii") as f:
926926
f.write(text)
927927
with open(self.filename, "rb") as f:
928928
file_data = ext_decompress(f.read()).decode("ascii")
929929
self.assertEqual(file_data, text_native_eol)
930-
with self.open(self.filename, "rt") as f:
930+
with self.open(self.filename, "rt", encoding="ascii") as f:
931931
self.assertEqual(f.read(), text)
932-
with self.open(self.filename, "at") as f:
932+
with self.open(self.filename, "at", encoding="ascii") as f:
933933
f.write(text)
934934
with open(self.filename, "rb") as f:
935935
file_data = ext_decompress(f.read()).decode("ascii")
@@ -938,7 +938,8 @@ def test_text_modes(self):
938938
def test_x_mode(self):
939939
for mode in ("x", "xb", "xt"):
940940
unlink(self.filename)
941-
with self.open(self.filename, mode) as f:
941+
encoding = "utf-8" if "t" in mode else None
942+
with self.open(self.filename, mode, encoding=encoding) as f:
942943
pass
943944
with self.assertRaises(FileExistsError):
944945
with self.open(self.filename, mode) as f:
@@ -950,7 +951,7 @@ def test_fileobj(self):
950951
with self.open(BytesIO(self.DATA), "rb") as f:
951952
self.assertEqual(f.read(), self.TEXT)
952953
text = self.TEXT.decode("ascii")
953-
with self.open(BytesIO(self.DATA), "rt") as f:
954+
with self.open(BytesIO(self.DATA), "rt", encoding="utf-8") as f:
954955
self.assertEqual(f.read(), text)
955956

956957
def test_bad_params(self):
@@ -989,9 +990,9 @@ def test_encoding_error_handler(self):
989990
def test_newline(self):
990991
# Test with explicit newline (universal newline mode disabled).
991992
text = self.TEXT.decode("ascii")
992-
with self.open(self.filename, "wt", newline="\n") as f:
993+
with self.open(self.filename, "wt", encoding="utf-8", newline="\n") as f:
993994
f.write(text)
994-
with self.open(self.filename, "rt", newline="\r") as f:
995+
with self.open(self.filename, "rt", encoding="utf-8", newline="\r") as f:
995996
self.assertEqual(f.readlines(), [text])
996997

997998

Lib/test/test_cmath.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -60,7 +60,7 @@ class CMathTests(unittest.TestCase):
6060
test_functions.append(lambda x : cmath.log(14.-27j, x))
6161

6262
def setUp(self):
63-
self.test_values = open(test_file)
63+
self.test_values = open(test_file, encoding="utf-8")
6464

6565
def tearDown(self):
6666
self.test_values.close()

Lib/test/test_cmd_line.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -512,7 +512,7 @@ def test_del___main__(self):
512512
# the dict whereas the module was destroyed
513513
filename = os_helper.TESTFN
514514
self.addCleanup(os_helper.unlink, filename)
515-
with open(filename, "w") as script:
515+
with open(filename, "w", encoding="utf-8") as script:
516516
print("import sys", file=script)
517517
print("del sys.modules['__main__']", file=script)
518518
assert_python_ok(filename)
@@ -549,9 +549,9 @@ def test_isolatedmode(self):
549549
with os_helper.temp_cwd() as tmpdir:
550550
fake = os.path.join(tmpdir, "uuid.py")
551551
main = os.path.join(tmpdir, "main.py")
552-
with open(fake, "w") as f:
552+
with open(fake, "w", encoding="utf-8") as f:
553553
f.write("raise RuntimeError('isolated mode test')\n")
554-
with open(main, "w") as f:
554+
with open(main, "w", encoding="utf-8") as f:
555555
f.write("import uuid\n")
556556
f.write("print('ok')\n")
557557
self.assertRaises(subprocess.CalledProcessError,

Lib/test/test_cmd_line_script.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -400,7 +400,7 @@ def test_issue8202_dash_c_file_ignored(self):
400400
# does not alter the value of sys.path[0]
401401
with os_helper.temp_dir() as script_dir:
402402
with os_helper.change_cwd(path=script_dir):
403-
with open("-c", "w") as f:
403+
with open("-c", "w", encoding="utf-8") as f:
404404
f.write("data")
405405
rc, out, err = assert_python_ok('-c',
406406
'import sys; print("sys.path[0]==%r" % sys.path[0])',
@@ -416,7 +416,7 @@ def test_issue8202_dash_m_file_ignored(self):
416416
with os_helper.temp_dir() as script_dir:
417417
script_name = _make_test_script(script_dir, 'other')
418418
with os_helper.change_cwd(path=script_dir):
419-
with open("-m", "w") as f:
419+
with open("-m", "w", encoding="utf-8") as f:
420420
f.write("data")
421421
rc, out, err = assert_python_ok('-m', 'other', *example_args,
422422
__isolated=False)
@@ -429,7 +429,7 @@ def test_issue20884(self):
429429
# will be failed.
430430
with os_helper.temp_dir() as script_dir:
431431
script_name = os.path.join(script_dir, "issue20884.py")
432-
with open(script_name, "w", newline='\n') as f:
432+
with open(script_name, "w", encoding="latin1", newline='\n') as f:
433433
f.write("#coding: iso-8859-1\n")
434434
f.write('"""\n')
435435
for _ in range(30):

Lib/test/test_compile.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -427,7 +427,7 @@ def test_compile_ast(self):
427427
fname = __file__
428428
if fname.lower().endswith('pyc'):
429429
fname = fname[:-1]
430-
with open(fname, 'r') as f:
430+
with open(fname, encoding='utf-8') as f:
431431
fcontents = f.read()
432432
sample_code = [
433433
['<assign>', 'x = 5'],

Lib/test/test_configparser.py

Lines changed: 13 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -714,31 +714,31 @@ def test_read_returns_file_list(self):
714714
file1 = support.findfile("cfgparser.1")
715715
# check when we pass a mix of readable and non-readable files:
716716
cf = self.newconfig()
717-
parsed_files = cf.read([file1, "nonexistent-file"])
717+
parsed_files = cf.read([file1, "nonexistent-file"], encoding="utf-8")
718718
self.assertEqual(parsed_files, [file1])
719719
self.assertEqual(cf.get("Foo Bar", "foo"), "newbar")
720720
# check when we pass only a filename:
721721
cf = self.newconfig()
722-
parsed_files = cf.read(file1)
722+
parsed_files = cf.read(file1, encoding="utf-8")
723723
self.assertEqual(parsed_files, [file1])
724724
self.assertEqual(cf.get("Foo Bar", "foo"), "newbar")
725725
# check when we pass only a Path object:
726726
cf = self.newconfig()
727-
parsed_files = cf.read(pathlib.Path(file1))
727+
parsed_files = cf.read(pathlib.Path(file1), encoding="utf-8")
728728
self.assertEqual(parsed_files, [file1])
729729
self.assertEqual(cf.get("Foo Bar", "foo"), "newbar")
730730
# check when we passed both a filename and a Path object:
731731
cf = self.newconfig()
732-
parsed_files = cf.read([pathlib.Path(file1), file1])
732+
parsed_files = cf.read([pathlib.Path(file1), file1], encoding="utf-8")
733733
self.assertEqual(parsed_files, [file1, file1])
734734
self.assertEqual(cf.get("Foo Bar", "foo"), "newbar")
735735
# check when we pass only missing files:
736736
cf = self.newconfig()
737-
parsed_files = cf.read(["nonexistent-file"])
737+
parsed_files = cf.read(["nonexistent-file"], encoding="utf-8")
738738
self.assertEqual(parsed_files, [])
739739
# check when we pass no files:
740740
cf = self.newconfig()
741-
parsed_files = cf.read([])
741+
parsed_files = cf.read([], encoding="utf-8")
742742
self.assertEqual(parsed_files, [])
743743

744744
def test_read_returns_file_list_with_bytestring_path(self):
@@ -747,15 +747,15 @@ def test_read_returns_file_list_with_bytestring_path(self):
747747
file1_bytestring = support.findfile("cfgparser.1").encode()
748748
# check when passing an existing bytestring path
749749
cf = self.newconfig()
750-
parsed_files = cf.read(file1_bytestring)
750+
parsed_files = cf.read(file1_bytestring, encoding="utf-8")
751751
self.assertEqual(parsed_files, [file1_bytestring])
752752
# check when passing an non-existing bytestring path
753753
cf = self.newconfig()
754-
parsed_files = cf.read(b'nonexistent-file')
754+
parsed_files = cf.read(b'nonexistent-file', encoding="utf-8")
755755
self.assertEqual(parsed_files, [])
756756
# check when passing both an existing and non-existing bytestring path
757757
cf = self.newconfig()
758-
parsed_files = cf.read([file1_bytestring, b'nonexistent-file'])
758+
parsed_files = cf.read([file1_bytestring, b'nonexistent-file'], encoding="utf-8")
759759
self.assertEqual(parsed_files, [file1_bytestring])
760760

761761
# shared by subclasses
@@ -1064,7 +1064,7 @@ def setUp(self):
10641064
cf.add_section(s)
10651065
for j in range(10):
10661066
cf.set(s, 'lovely_spam{}'.format(j), self.wonderful_spam)
1067-
with open(os_helper.TESTFN, 'w') as f:
1067+
with open(os_helper.TESTFN, 'w', encoding="utf-8") as f:
10681068
cf.write(f)
10691069

10701070
def tearDown(self):
@@ -1074,7 +1074,7 @@ def test_dominating_multiline_values(self):
10741074
# We're reading from file because this is where the code changed
10751075
# during performance updates in Python 3.2
10761076
cf_from_file = self.newconfig()
1077-
with open(os_helper.TESTFN) as f:
1077+
with open(os_helper.TESTFN, encoding="utf-8") as f:
10781078
cf_from_file.read_file(f)
10791079
self.assertEqual(cf_from_file.get('section8', 'lovely_spam4'),
10801080
self.wonderful_spam.replace('\t\n', '\n'))
@@ -1473,7 +1473,7 @@ def fromstring(self, string, defaults=None):
14731473
class FakeFile:
14741474
def __init__(self):
14751475
file_path = support.findfile("cfgparser.1")
1476-
with open(file_path) as f:
1476+
with open(file_path, encoding="utf-8") as f:
14771477
self.lines = f.readlines()
14781478
self.lines.reverse()
14791479

@@ -1500,7 +1500,7 @@ def test_file(self):
15001500
pass # unfortunately we can't test bytes on this path
15011501
for file_path in file_paths:
15021502
parser = configparser.ConfigParser()
1503-
with open(file_path) as f:
1503+
with open(file_path, encoding="utf-8") as f:
15041504
parser.read_file(f)
15051505
self.assertIn("Foo Bar", parser)
15061506
self.assertIn("foo", parser["Foo Bar"])

Lib/test/test_contextlib.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -316,13 +316,13 @@ def testWithOpen(self):
316316
tfn = tempfile.mktemp()
317317
try:
318318
f = None
319-
with open(tfn, "w") as f:
319+
with open(tfn, "w", encoding="utf-8") as f:
320320
self.assertFalse(f.closed)
321321
f.write("Booh\n")
322322
self.assertTrue(f.closed)
323323
f = None
324324
with self.assertRaises(ZeroDivisionError):
325-
with open(tfn, "r") as f:
325+
with open(tfn, "r", encoding="utf-8") as f:
326326
self.assertFalse(f.closed)
327327
self.assertEqual(f.read(), "Booh\n")
328328
1 / 0

0 commit comments

Comments
 (0)