Skip to content

Commit b21d155

Browse files
bpo-32964: Reuse a testing implementation of the path protocol in tests. (#5930)
1 parent bf63e8d commit b21d155

File tree

11 files changed

+70
-103
lines changed

11 files changed

+70
-103
lines changed

Doc/library/test.rst

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1293,6 +1293,13 @@ The :mod:`test.support` module defines the following classes:
12931293
Class for logging support.
12941294

12951295

1296+
.. class:: FakePath(path)
1297+
1298+
Simple :term:`path-like object`. It implements the :meth:`__fspath__`
1299+
method which just returns the *path* argument. If *path* is an exception,
1300+
it will be raised in :meth:`!__fspath__`.
1301+
1302+
12961303
:mod:`test.support.script_helper` --- Utilities for the Python execution tests
12971304
==============================================================================
12981305

Lib/test/support/__init__.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2840,3 +2840,21 @@ def restore(self):
28402840
def with_pymalloc():
28412841
import _testcapi
28422842
return _testcapi.WITH_PYMALLOC
2843+
2844+
2845+
class FakePath:
2846+
"""Simple implementing of the path protocol.
2847+
"""
2848+
def __init__(self, path):
2849+
self.path = path
2850+
2851+
def __repr__(self):
2852+
return f'<FakePath {self.path!r}>'
2853+
2854+
def __fspath__(self):
2855+
if (isinstance(self.path, BaseException) or
2856+
isinstance(self.path, type) and
2857+
issubclass(self.path, BaseException)):
2858+
raise self.path
2859+
else:
2860+
return self.path

Lib/test/test_compile.py

Lines changed: 2 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66
import tempfile
77
import types
88
from test import support
9-
from test.support import script_helper
9+
from test.support import script_helper, FakePath
1010

1111
class TestSpecifics(unittest.TestCase):
1212

@@ -663,13 +663,7 @@ def check_different_constants(const1, const2):
663663

664664
def test_path_like_objects(self):
665665
# An implicit test for PyUnicode_FSDecoder().
666-
class PathLike:
667-
def __init__(self, path):
668-
self._path = path
669-
def __fspath__(self):
670-
return self._path
671-
672-
compile("42", PathLike("test_compile_pathlike"), "single")
666+
compile("42", FakePath("test_compile_pathlike"), "single")
673667

674668
def test_stack_overflow(self):
675669
# bpo-31113: Stack overflow when compile a long sequence of

Lib/test/test_genericpath.py

Lines changed: 2 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
import warnings
1010
from test import support
1111
from test.support.script_helper import assert_python_ok
12+
from test.support import FakePath
1213

1314

1415
def create_file(filename, data=b'foo'):
@@ -493,18 +494,9 @@ def test_import(self):
493494

494495
class PathLikeTests(unittest.TestCase):
495496

496-
class PathLike:
497-
def __init__(self, path=''):
498-
self.path = path
499-
def __fspath__(self):
500-
if isinstance(self.path, BaseException):
501-
raise self.path
502-
else:
503-
return self.path
504-
505497
def setUp(self):
506498
self.file_name = support.TESTFN.lower()
507-
self.file_path = self.PathLike(support.TESTFN)
499+
self.file_path = FakePath(support.TESTFN)
508500
self.addCleanup(support.unlink, self.file_name)
509501
create_file(self.file_name, b"test_genericpath.PathLikeTests")
510502

Lib/test/test_io.py

Lines changed: 14 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,7 @@
3737
from itertools import cycle, count
3838
from test import support
3939
from test.support.script_helper import assert_python_ok, run_python_until_end
40+
from test.support import FakePath
4041

4142
import codecs
4243
import io # C implementation of io
@@ -891,30 +892,32 @@ def read(self, size):
891892
self.assertEqual(bytes(buffer), b"12345")
892893

893894
def test_fspath_support(self):
894-
class PathLike:
895-
def __init__(self, path):
896-
self.path = path
897-
898-
def __fspath__(self):
899-
return self.path
900-
901895
def check_path_succeeds(path):
902896
with self.open(path, "w") as f:
903897
f.write("egg\n")
904898

905899
with self.open(path, "r") as f:
906900
self.assertEqual(f.read(), "egg\n")
907901

908-
check_path_succeeds(PathLike(support.TESTFN))
909-
check_path_succeeds(PathLike(support.TESTFN.encode('utf-8')))
902+
check_path_succeeds(FakePath(support.TESTFN))
903+
check_path_succeeds(FakePath(support.TESTFN.encode('utf-8')))
904+
905+
with self.open(support.TESTFN, "w") as f:
906+
bad_path = FakePath(f.fileno())
907+
with self.assertRaises(TypeError):
908+
self.open(bad_path, 'w')
910909

911-
bad_path = PathLike(TypeError)
910+
bad_path = FakePath(None)
912911
with self.assertRaises(TypeError):
913912
self.open(bad_path, 'w')
914913

914+
bad_path = FakePath(FloatingPointError)
915+
with self.assertRaises(FloatingPointError):
916+
self.open(bad_path, 'w')
917+
915918
# ensure that refcounting is correct with some error conditions
916919
with self.assertRaisesRegex(ValueError, 'read/write/append mode'):
917-
self.open(PathLike(support.TESTFN), 'rwxa')
920+
self.open(FakePath(support.TESTFN), 'rwxa')
918921

919922
def test_RawIOBase_readall(self):
920923
# Exercise the default unlimited RawIOBase.read() and readall()

Lib/test/test_ntpath.py

Lines changed: 3 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
import sys
44
import unittest
55
import warnings
6-
from test.support import TestFailed
6+
from test.support import TestFailed, FakePath
77
from test import support, test_genericpath
88
from tempfile import TemporaryFile
99

@@ -459,18 +459,9 @@ class PathLikeTests(unittest.TestCase):
459459

460460
path = ntpath
461461

462-
class PathLike:
463-
def __init__(self, path=''):
464-
self.path = path
465-
def __fspath__(self):
466-
if isinstance(self.path, BaseException):
467-
raise self.path
468-
else:
469-
return self.path
470-
471462
def setUp(self):
472463
self.file_name = support.TESTFN.lower()
473-
self.file_path = self.PathLike(support.TESTFN)
464+
self.file_path = FakePath(support.TESTFN)
474465
self.addCleanup(support.unlink, self.file_name)
475466
with open(self.file_name, 'xb', 0) as file:
476467
file.write(b"test_ntpath.PathLikeTests")
@@ -485,7 +476,7 @@ def test_path_isabs(self):
485476
self.assertPathEqual(self.path.isabs)
486477

487478
def test_path_join(self):
488-
self.assertEqual(self.path.join('a', self.PathLike('b'), 'c'),
479+
self.assertEqual(self.path.join('a', FakePath('b'), 'c'),
489480
self.path.join('a', 'b', 'c'))
490481

491482
def test_path_split(self):

Lib/test/test_os.py

Lines changed: 14 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -61,7 +61,7 @@
6161
INT_MAX = PY_SSIZE_T_MAX = sys.maxsize
6262

6363
from test.support.script_helper import assert_python_ok
64-
from test.support import unix_shell
64+
from test.support import unix_shell, FakePath
6565

6666

6767
root_in_posix = False
@@ -85,21 +85,6 @@ def requires_os_func(name):
8585
return unittest.skipUnless(hasattr(os, name), 'requires os.%s' % name)
8686

8787

88-
class _PathLike(os.PathLike):
89-
90-
def __init__(self, path=""):
91-
self.path = path
92-
93-
def __str__(self):
94-
return str(self.path)
95-
96-
def __fspath__(self):
97-
if isinstance(self.path, BaseException):
98-
raise self.path
99-
else:
100-
return self.path
101-
102-
10388
def create_file(filename, content=b'content'):
10489
with open(filename, "xb", 0) as fp:
10590
fp.write(content)
@@ -942,15 +927,14 @@ def test_walk_prune(self, walk_path=None):
942927
dirs.remove('SUB1')
943928

944929
self.assertEqual(len(all), 2)
945-
self.assertEqual(all[0],
946-
(str(walk_path), ["SUB2"], ["tmp1"]))
930+
self.assertEqual(all[0], (self.walk_path, ["SUB2"], ["tmp1"]))
947931

948932
all[1][-1].sort()
949933
all[1][1].sort()
950934
self.assertEqual(all[1], self.sub2_tree)
951935

952936
def test_file_like_path(self):
953-
self.test_walk_prune(_PathLike(self.walk_path))
937+
self.test_walk_prune(FakePath(self.walk_path))
954938

955939
def test_walk_bottom_up(self):
956940
# Walk bottom-up.
@@ -2288,7 +2272,7 @@ def test_getppid(self):
22882272
def test_waitpid(self):
22892273
args = [sys.executable, '-c', 'pass']
22902274
# Add an implicit test for PyUnicode_FSConverter().
2291-
pid = os.spawnv(os.P_NOWAIT, _PathLike(args[0]), args)
2275+
pid = os.spawnv(os.P_NOWAIT, FakePath(args[0]), args)
22922276
status = os.waitpid(pid, 0)
22932277
self.assertEqual(status, (pid, 0))
22942278

@@ -3129,13 +3113,13 @@ def test_path_t_converter(self):
31293113
bytes_fspath = bytes_filename = None
31303114
else:
31313115
bytes_filename = support.TESTFN.encode('ascii')
3132-
bytes_fspath = _PathLike(bytes_filename)
3133-
fd = os.open(_PathLike(str_filename), os.O_WRONLY|os.O_CREAT)
3116+
bytes_fspath = FakePath(bytes_filename)
3117+
fd = os.open(FakePath(str_filename), os.O_WRONLY|os.O_CREAT)
31343118
self.addCleanup(support.unlink, support.TESTFN)
31353119
self.addCleanup(os.close, fd)
31363120

3137-
int_fspath = _PathLike(fd)
3138-
str_fspath = _PathLike(str_filename)
3121+
int_fspath = FakePath(fd)
3122+
str_fspath = FakePath(str_filename)
31393123

31403124
for name, allow_fd, extra_args, cleanup_fn in self.functions:
31413125
with self.subTest(name=name):
@@ -3540,16 +3524,16 @@ def test_return_string(self):
35403524

35413525
def test_fsencode_fsdecode(self):
35423526
for p in "path/like/object", b"path/like/object":
3543-
pathlike = _PathLike(p)
3527+
pathlike = FakePath(p)
35443528

35453529
self.assertEqual(p, self.fspath(pathlike))
35463530
self.assertEqual(b"path/like/object", os.fsencode(pathlike))
35473531
self.assertEqual("path/like/object", os.fsdecode(pathlike))
35483532

35493533
def test_pathlike(self):
3550-
self.assertEqual('#feelthegil', self.fspath(_PathLike('#feelthegil')))
3551-
self.assertTrue(issubclass(_PathLike, os.PathLike))
3552-
self.assertTrue(isinstance(_PathLike(), os.PathLike))
3534+
self.assertEqual('#feelthegil', self.fspath(FakePath('#feelthegil')))
3535+
self.assertTrue(issubclass(FakePath, os.PathLike))
3536+
self.assertTrue(isinstance(FakePath('x'), os.PathLike))
35533537

35543538
def test_garbage_in_exception_out(self):
35553539
vapor = type('blah', (), {})
@@ -3561,14 +3545,14 @@ def test_argument_required(self):
35613545

35623546
def test_bad_pathlike(self):
35633547
# __fspath__ returns a value other than str or bytes.
3564-
self.assertRaises(TypeError, self.fspath, _PathLike(42))
3548+
self.assertRaises(TypeError, self.fspath, FakePath(42))
35653549
# __fspath__ attribute that is not callable.
35663550
c = type('foo', (), {})
35673551
c.__fspath__ = 1
35683552
self.assertRaises(TypeError, self.fspath, c())
35693553
# __fspath__ raises an exception.
35703554
self.assertRaises(ZeroDivisionError, self.fspath,
3571-
_PathLike(ZeroDivisionError()))
3555+
FakePath(ZeroDivisionError()))
35723556

35733557

35743558
class TimesTests(unittest.TestCase):

Lib/test/test_pathlib.py

Lines changed: 3 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@
1111
from unittest import mock
1212

1313
from test import support
14-
TESTFN = support.TESTFN
14+
from test.support import TESTFN, FakePath
1515

1616
try:
1717
import grp, pwd
@@ -191,18 +191,15 @@ def test_constructor_common(self):
191191
P = self.cls
192192
p = P('a')
193193
self.assertIsInstance(p, P)
194-
class PathLike:
195-
def __fspath__(self):
196-
return "a/b/c"
197194
P('a', 'b', 'c')
198195
P('/a', 'b', 'c')
199196
P('a/b/c')
200197
P('/a/b/c')
201-
P(PathLike())
198+
P(FakePath("a/b/c"))
202199
self.assertEqual(P(P('a')), P('a'))
203200
self.assertEqual(P(P('a'), 'b'), P('a/b'))
204201
self.assertEqual(P(P('a'), P('b')), P('a/b'))
205-
self.assertEqual(P(P('a'), P('b'), P('c')), P(PathLike()))
202+
self.assertEqual(P(P('a'), P('b'), P('c')), P(FakePath("a/b/c")))
206203

207204
def _check_str_subclass(self, *args):
208205
# Issue #21127: it should be possible to construct a PurePath object

Lib/test/test_posixpath.py

Lines changed: 3 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
import warnings
55
from posixpath import realpath, abspath, dirname, basename
66
from test import support, test_genericpath
7+
from test.support import FakePath
78

89
try:
910
import posix
@@ -600,18 +601,9 @@ class PathLikeTests(unittest.TestCase):
600601

601602
path = posixpath
602603

603-
class PathLike:
604-
def __init__(self, path=''):
605-
self.path = path
606-
def __fspath__(self):
607-
if isinstance(self.path, BaseException):
608-
raise self.path
609-
else:
610-
return self.path
611-
612604
def setUp(self):
613605
self.file_name = support.TESTFN.lower()
614-
self.file_path = self.PathLike(support.TESTFN)
606+
self.file_path = FakePath(support.TESTFN)
615607
self.addCleanup(support.unlink, self.file_name)
616608
with open(self.file_name, 'xb', 0) as file:
617609
file.write(b"test_posixpath.PathLikeTests")
@@ -626,7 +618,7 @@ def test_path_isabs(self):
626618
self.assertPathEqual(self.path.isabs)
627619

628620
def test_path_join(self):
629-
self.assertEqual(self.path.join('a', self.PathLike('b'), 'c'),
621+
self.assertEqual(self.path.join('a', FakePath('b'), 'c'),
630622
self.path.join('a', 'b', 'c'))
631623

632624
def test_path_split(self):

Lib/test/test_shutil.py

Lines changed: 2 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@
2222
import zipfile
2323

2424
from test import support
25-
from test.support import TESTFN
25+
from test.support import TESTFN, FakePath
2626

2727
TESTFN2 = TESTFN + "2"
2828

@@ -1232,14 +1232,7 @@ def test_register_archive_format(self):
12321232
def check_unpack_archive(self, format):
12331233
self.check_unpack_archive_with_converter(format, lambda path: path)
12341234
self.check_unpack_archive_with_converter(format, pathlib.Path)
1235-
1236-
class MyPath:
1237-
def __init__(self, path):
1238-
self.path = path
1239-
def __fspath__(self):
1240-
return self.path
1241-
1242-
self.check_unpack_archive_with_converter(format, MyPath)
1235+
self.check_unpack_archive_with_converter(format, FakePath)
12431236

12441237
def check_unpack_archive_with_converter(self, format, converter):
12451238
root_dir, base_dir = self._create_files()

0 commit comments

Comments
 (0)