Skip to content

Commit 33a9f0c

Browse files
[3.12] gh-119064: Use os_helper.FakePath instead of pathlib.Path in tests (GH-119065) (GH-119088)
(cherry picked from commit 0152dc4)
1 parent ed395f5 commit 33a9f0c

19 files changed

+116
-128
lines changed

Lib/test/_test_multiprocessing.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,6 @@
2222
import subprocess
2323
import struct
2424
import operator
25-
import pathlib
2625
import pickle
2726
import weakref
2827
import warnings
@@ -324,8 +323,9 @@ def test_set_executable(self):
324323
self.skipTest(f'test not appropriate for {self.TYPE}')
325324
paths = [
326325
sys.executable, # str
327-
sys.executable.encode(), # bytes
328-
pathlib.Path(sys.executable) # os.PathLike
326+
os.fsencode(sys.executable), # bytes
327+
os_helper.FakePath(sys.executable), # os.PathLike
328+
os_helper.FakePath(os.fsencode(sys.executable)), # os.PathLike bytes
329329
]
330330
for path in paths:
331331
self.set_executable(path)

Lib/test/test_asyncio/test_unix_events.py

+5-6
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,6 @@
66
import multiprocessing
77
from multiprocessing.util import _cleanup_tests as multiprocessing_cleanup_tests
88
import os
9-
import pathlib
109
import signal
1110
import socket
1211
import stat
@@ -304,20 +303,20 @@ def test_create_unix_server_existing_path_sock(self):
304303
self.loop.run_until_complete(srv.wait_closed())
305304

306305
@socket_helper.skip_unless_bind_unix_socket
307-
def test_create_unix_server_pathlib(self):
306+
def test_create_unix_server_pathlike(self):
308307
with test_utils.unix_socket_path() as path:
309-
path = pathlib.Path(path)
308+
path = os_helper.FakePath(path)
310309
srv_coro = self.loop.create_unix_server(lambda: None, path)
311310
srv = self.loop.run_until_complete(srv_coro)
312311
srv.close()
313312
self.loop.run_until_complete(srv.wait_closed())
314313

315-
def test_create_unix_connection_pathlib(self):
314+
def test_create_unix_connection_pathlike(self):
316315
with test_utils.unix_socket_path() as path:
317-
path = pathlib.Path(path)
316+
path = os_helper.FakePath(path)
318317
coro = self.loop.create_unix_connection(lambda: None, path)
319318
with self.assertRaises(FileNotFoundError):
320-
# If pathlib.Path wasn't supported, the exception would be
319+
# If path-like object weren't supported, the exception would be
321320
# different.
322321
self.loop.run_until_complete(coro)
323322

Lib/test/test_compileall.py

+13-13
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,6 @@
44
import importlib.util
55
import io
66
import os
7-
import pathlib
87
import py_compile
98
import shutil
109
import struct
@@ -31,6 +30,7 @@
3130
from test.support import script_helper
3231
from test.test_py_compile import without_source_date_epoch
3332
from test.test_py_compile import SourceDateEpochTestMeta
33+
from test.support.os_helper import FakePath
3434

3535

3636
def get_pyc(script, opt):
@@ -156,28 +156,28 @@ def test_compile_file_pathlike(self):
156156
self.assertFalse(os.path.isfile(self.bc_path))
157157
# we should also test the output
158158
with support.captured_stdout() as stdout:
159-
self.assertTrue(compileall.compile_file(pathlib.Path(self.source_path)))
159+
self.assertTrue(compileall.compile_file(FakePath(self.source_path)))
160160
self.assertRegex(stdout.getvalue(), r'Compiling ([^WindowsPath|PosixPath].*)')
161161
self.assertTrue(os.path.isfile(self.bc_path))
162162

163163
def test_compile_file_pathlike_ddir(self):
164164
self.assertFalse(os.path.isfile(self.bc_path))
165-
self.assertTrue(compileall.compile_file(pathlib.Path(self.source_path),
166-
ddir=pathlib.Path('ddir_path'),
165+
self.assertTrue(compileall.compile_file(FakePath(self.source_path),
166+
ddir=FakePath('ddir_path'),
167167
quiet=2))
168168
self.assertTrue(os.path.isfile(self.bc_path))
169169

170170
def test_compile_file_pathlike_stripdir(self):
171171
self.assertFalse(os.path.isfile(self.bc_path))
172-
self.assertTrue(compileall.compile_file(pathlib.Path(self.source_path),
173-
stripdir=pathlib.Path('stripdir_path'),
172+
self.assertTrue(compileall.compile_file(FakePath(self.source_path),
173+
stripdir=FakePath('stripdir_path'),
174174
quiet=2))
175175
self.assertTrue(os.path.isfile(self.bc_path))
176176

177177
def test_compile_file_pathlike_prependdir(self):
178178
self.assertFalse(os.path.isfile(self.bc_path))
179-
self.assertTrue(compileall.compile_file(pathlib.Path(self.source_path),
180-
prependdir=pathlib.Path('prependdir_path'),
179+
self.assertTrue(compileall.compile_file(FakePath(self.source_path),
180+
prependdir=FakePath('prependdir_path'),
181181
quiet=2))
182182
self.assertTrue(os.path.isfile(self.bc_path))
183183

@@ -228,22 +228,22 @@ def test_optimize(self):
228228
def test_compile_dir_pathlike(self):
229229
self.assertFalse(os.path.isfile(self.bc_path))
230230
with support.captured_stdout() as stdout:
231-
compileall.compile_dir(pathlib.Path(self.directory))
231+
compileall.compile_dir(FakePath(self.directory))
232232
line = stdout.getvalue().splitlines()[0]
233233
self.assertRegex(line, r'Listing ([^WindowsPath|PosixPath].*)')
234234
self.assertTrue(os.path.isfile(self.bc_path))
235235

236236
def test_compile_dir_pathlike_stripdir(self):
237237
self.assertFalse(os.path.isfile(self.bc_path))
238-
self.assertTrue(compileall.compile_dir(pathlib.Path(self.directory),
239-
stripdir=pathlib.Path('stripdir_path'),
238+
self.assertTrue(compileall.compile_dir(FakePath(self.directory),
239+
stripdir=FakePath('stripdir_path'),
240240
quiet=2))
241241
self.assertTrue(os.path.isfile(self.bc_path))
242242

243243
def test_compile_dir_pathlike_prependdir(self):
244244
self.assertFalse(os.path.isfile(self.bc_path))
245-
self.assertTrue(compileall.compile_dir(pathlib.Path(self.directory),
246-
prependdir=pathlib.Path('prependdir_path'),
245+
self.assertTrue(compileall.compile_dir(FakePath(self.directory),
246+
prependdir=FakePath('prependdir_path'),
247247
quiet=2))
248248
self.assertTrue(os.path.isfile(self.bc_path))
249249

Lib/test/test_configparser.py

+2-3
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@
22
import configparser
33
import io
44
import os
5-
import pathlib
65
import textwrap
76
import unittest
87
import warnings
@@ -746,12 +745,12 @@ def test_read_returns_file_list(self):
746745
self.assertEqual(cf.get("Foo Bar", "foo"), "newbar")
747746
# check when we pass only a Path object:
748747
cf = self.newconfig()
749-
parsed_files = cf.read(pathlib.Path(file1), encoding="utf-8")
748+
parsed_files = cf.read(os_helper.FakePath(file1), encoding="utf-8")
750749
self.assertEqual(parsed_files, [file1])
751750
self.assertEqual(cf.get("Foo Bar", "foo"), "newbar")
752751
# check when we passed both a filename and a Path object:
753752
cf = self.newconfig()
754-
parsed_files = cf.read([pathlib.Path(file1), file1], encoding="utf-8")
753+
parsed_files = cf.read([os_helper.FakePath(file1), file1], encoding="utf-8")
755754
self.assertEqual(parsed_files, [file1, file1])
756755
self.assertEqual(cf.get("Foo Bar", "foo"), "newbar")
757756
# check when we pass only missing files:

Lib/test/test_ctypes/test_loading.py

+1-4
Original file line numberDiff line numberDiff line change
@@ -38,10 +38,7 @@ def test_load(self):
3838
self.skipTest('could not find library to load')
3939
CDLL(test_lib)
4040
CDLL(os.path.basename(test_lib))
41-
class CTypesTestPathLikeCls:
42-
def __fspath__(self):
43-
return test_lib
44-
CDLL(CTypesTestPathLikeCls())
41+
CDLL(os_helper.FakePath(test_lib))
4542
self.assertRaises(OSError, CDLL, self.unknowndll)
4643

4744
def test_load_version(self):

Lib/test/test_fileinput.py

+8-9
Original file line numberDiff line numberDiff line change
@@ -23,10 +23,9 @@
2323

2424
from io import BytesIO, StringIO
2525
from fileinput import FileInput, hook_encoded
26-
from pathlib import Path
2726

2827
from test.support import verbose
29-
from test.support.os_helper import TESTFN
28+
from test.support.os_helper import TESTFN, FakePath
3029
from test.support.os_helper import unlink as safe_unlink
3130
from test.support import os_helper
3231
from test import support
@@ -478,23 +477,23 @@ def test_iteration_buffering(self):
478477
self.assertRaises(StopIteration, next, fi)
479478
self.assertEqual(src.linesread, [])
480479

481-
def test_pathlib_file(self):
482-
t1 = Path(self.writeTmp("Pathlib file."))
480+
def test_pathlike_file(self):
481+
t1 = FakePath(self.writeTmp("Path-like file."))
483482
with FileInput(t1, encoding="utf-8") as fi:
484483
line = fi.readline()
485-
self.assertEqual(line, 'Pathlib file.')
484+
self.assertEqual(line, 'Path-like file.')
486485
self.assertEqual(fi.lineno(), 1)
487486
self.assertEqual(fi.filelineno(), 1)
488487
self.assertEqual(fi.filename(), os.fspath(t1))
489488

490-
def test_pathlib_file_inplace(self):
491-
t1 = Path(self.writeTmp('Pathlib file.'))
489+
def test_pathlike_file_inplace(self):
490+
t1 = FakePath(self.writeTmp('Path-like file.'))
492491
with FileInput(t1, inplace=True, encoding="utf-8") as fi:
493492
line = fi.readline()
494-
self.assertEqual(line, 'Pathlib file.')
493+
self.assertEqual(line, 'Path-like file.')
495494
print('Modified %s' % line)
496495
with open(t1, encoding="utf-8") as f:
497-
self.assertEqual(f.read(), 'Modified Pathlib file.\n')
496+
self.assertEqual(f.read(), 'Modified Path-like file.\n')
498497

499498

500499
class MockFileInput:

Lib/test/test_http_cookiejar.py

+3-4
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,6 @@
99
import time
1010
import unittest
1111
import urllib.request
12-
import pathlib
1312

1413
from http.cookiejar import (time2isoz, http2time, iso2time, time2netscape,
1514
parse_ns_headers, join_header_words, split_header_words, Cookie,
@@ -337,9 +336,9 @@ def test_constructor_with_str(self):
337336
self.assertEqual(c.filename, filename)
338337

339338
def test_constructor_with_path_like(self):
340-
filename = pathlib.Path(os_helper.TESTFN)
341-
c = LWPCookieJar(filename)
342-
self.assertEqual(c.filename, os.fspath(filename))
339+
filename = os_helper.TESTFN
340+
c = LWPCookieJar(os_helper.FakePath(filename))
341+
self.assertEqual(c.filename, filename)
343342

344343
def test_constructor_with_none(self):
345344
c = LWPCookieJar(None)

Lib/test/test_logging.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -662,15 +662,15 @@ def test_builtin_handlers(self):
662662
self.assertFalse(h.shouldFlush(r))
663663
h.close()
664664

665-
def test_path_objects(self):
665+
def test_pathlike_objects(self):
666666
"""
667-
Test that Path objects are accepted as filename arguments to handlers.
667+
Test that path-like objects are accepted as filename arguments to handlers.
668668
669669
See Issue #27493.
670670
"""
671671
fn = make_temp_file()
672672
os.unlink(fn)
673-
pfn = pathlib.Path(fn)
673+
pfn = os_helper.FakePath(fn)
674674
cases = (
675675
(logging.FileHandler, (pfn, 'w')),
676676
(logging.handlers.RotatingFileHandler, (pfn, 'a')),

Lib/test/test_mimetypes.py

+14-7
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
import io
22
import mimetypes
33
import os
4-
import pathlib
54
import sys
65
import unittest.mock
76

@@ -75,11 +74,19 @@ def test_read_mime_types(self):
7574

7675
with os_helper.temp_dir() as directory:
7776
data = "x-application/x-unittest pyunit\n"
78-
file = pathlib.Path(directory, "sample.mimetype")
79-
file.write_text(data, encoding="utf-8")
77+
file = os.path.join(directory, "sample.mimetype")
78+
with open(file, 'w', encoding="utf-8") as f:
79+
f.write(data)
8080
mime_dict = mimetypes.read_mime_types(file)
8181
eq(mime_dict[".pyunit"], "x-application/x-unittest")
8282

83+
data = "x-application/x-unittest2 pyunit2\n"
84+
file = os.path.join(directory, "sample2.mimetype")
85+
with open(file, 'w', encoding="utf-8") as f:
86+
f.write(data)
87+
mime_dict = mimetypes.read_mime_types(os_helper.FakePath(file))
88+
eq(mime_dict[".pyunit2"], "x-application/x-unittest2")
89+
8390
# bpo-41048: read_mime_types should read the rule file with 'utf-8' encoding.
8491
# Not with locale encoding. _bootlocale has been imported because io.open(...)
8592
# uses it.
@@ -241,10 +248,10 @@ def test_init_stability(self):
241248

242249
def test_path_like_ob(self):
243250
filename = "LICENSE.txt"
244-
filepath = pathlib.Path(filename)
245-
filepath_with_abs_dir = pathlib.Path('/dir/'+filename)
246-
filepath_relative = pathlib.Path('../dir/'+filename)
247-
path_dir = pathlib.Path('./')
251+
filepath = os_helper.FakePath(filename)
252+
filepath_with_abs_dir = os_helper.FakePath('/dir/'+filename)
253+
filepath_relative = os_helper.FakePath('../dir/'+filename)
254+
path_dir = os_helper.FakePath('./')
248255

249256
expected = self.db.guess_type(filename)
250257

Lib/test/test_pkgutil.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313
import zipfile
1414

1515
from test.support.import_helper import DirsOnSysPath
16+
from test.support.os_helper import FakePath
1617
from test.test_importlib.util import uncache
1718

1819
# Note: pkgutil.walk_packages is currently tested in test_runpy. This is
@@ -121,7 +122,7 @@ def test_issue44061_iter_modules(self):
121122

122123
# make sure iter_modules accepts Path objects
123124
names = []
124-
for moduleinfo in pkgutil.iter_modules([Path(zip_file)]):
125+
for moduleinfo in pkgutil.iter_modules([FakePath(zip_file)]):
125126
self.assertIsInstance(moduleinfo, pkgutil.ModuleInfo)
126127
names.append(moduleinfo.name)
127128
self.assertEqual(names, [pkg])

Lib/test/test_runpy.py

+3-4
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@
1414
import warnings
1515
from test.support import no_tracing, verbose, requires_subprocess, requires_resource
1616
from test.support.import_helper import forget, make_legacy_pyc, unload
17-
from test.support.os_helper import create_empty_file, temp_dir
17+
from test.support.os_helper import create_empty_file, temp_dir, FakePath
1818
from test.support.script_helper import make_script, make_zip_script
1919

2020

@@ -656,11 +656,10 @@ def test_basic_script(self):
656656
self._check_script(script_name, "<run_path>", script_name,
657657
script_name, expect_spec=False)
658658

659-
def test_basic_script_with_path_object(self):
659+
def test_basic_script_with_pathlike_object(self):
660660
with temp_dir() as script_dir:
661661
mod_name = 'script'
662-
script_name = pathlib.Path(self._make_test_script(script_dir,
663-
mod_name))
662+
script_name = FakePath(self._make_test_script(script_dir, mod_name))
664663
self._check_script(script_name, "<run_path>", script_name,
665664
script_name, expect_spec=False)
666665

Lib/test/test_shutil.py

+4-4
Original file line numberDiff line numberDiff line change
@@ -859,7 +859,7 @@ def _ignore(src, names):
859859
'test.txt')))
860860

861861
dst_dir = join(self.mkdtemp(), 'destination')
862-
shutil.copytree(pathlib.Path(src_dir), dst_dir, ignore=_ignore)
862+
shutil.copytree(FakePath(src_dir), dst_dir, ignore=_ignore)
863863
self.assertTrue(exists(join(dst_dir, 'test_dir', 'subdir',
864864
'test.txt')))
865865

@@ -2055,7 +2055,7 @@ def check_unpack_archive(self, format, **kwargs):
20552055
self.check_unpack_archive_with_converter(
20562056
format, lambda path: path, **kwargs)
20572057
self.check_unpack_archive_with_converter(
2058-
format, pathlib.Path, **kwargs)
2058+
format, FakePath, **kwargs)
20592059
self.check_unpack_archive_with_converter(format, FakePath, **kwargs)
20602060

20612061
def check_unpack_archive_with_converter(self, format, converter, **kwargs):
@@ -2587,12 +2587,12 @@ def test_move_file_to_dir(self):
25872587

25882588
def test_move_file_to_dir_pathlike_src(self):
25892589
# Move a pathlike file to another location on the same filesystem.
2590-
src = pathlib.Path(self.src_file)
2590+
src = FakePath(self.src_file)
25912591
self._check_move_file(src, self.dst_dir, self.dst_file)
25922592

25932593
def test_move_file_to_dir_pathlike_dst(self):
25942594
# Move a file to another pathlike location on the same filesystem.
2595-
dst = pathlib.Path(self.dst_dir)
2595+
dst = FakePath(self.dst_dir)
25962596
self._check_move_file(self.src_file, dst, self.dst_file)
25972597

25982598
@mock_rename

Lib/test/test_subprocess.py

+2-5
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,6 @@
2525
import gc
2626
import textwrap
2727
import json
28-
import pathlib
2928
from test.support.os_helper import FakePath
3029

3130
try:
@@ -1522,17 +1521,15 @@ def test_communicate_epipe(self):
15221521
p.communicate(b"x" * 2**20)
15231522

15241523
def test_repr(self):
1525-
path_cmd = pathlib.Path("my-tool.py")
1526-
pathlib_cls = path_cmd.__class__.__name__
1527-
15281524
cases = [
15291525
("ls", True, 123, "<Popen: returncode: 123 args: 'ls'>"),
15301526
('a' * 100, True, 0,
15311527
"<Popen: returncode: 0 args: 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa...>"),
15321528
(["ls"], False, None, "<Popen: returncode: None args: ['ls']>"),
15331529
(["ls", '--my-opts', 'a' * 100], False, None,
15341530
"<Popen: returncode: None args: ['ls', '--my-opts', 'aaaaaaaaaaaaaaaaaaaaaaaa...>"),
1535-
(path_cmd, False, 7, f"<Popen: returncode: 7 args: {pathlib_cls}('my-tool.py')>")
1531+
(os_helper.FakePath("my-tool.py"), False, 7,
1532+
"<Popen: returncode: 7 args: <FakePath 'my-tool.py'>>")
15361533
]
15371534
with unittest.mock.patch.object(subprocess.Popen, '_execute_child'):
15381535
for cmd, shell, code, sx in cases:

0 commit comments

Comments
 (0)