]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
[3.12] gh-119064: Use os_helper.FakePath instead of pathlib.Path in tests (GH-119065...
authorSerhiy Storchaka <storchaka@gmail.com>
Thu, 16 May 2024 08:04:37 +0000 (11:04 +0300)
committerGitHub <noreply@github.com>
Thu, 16 May 2024 08:04:37 +0000 (08:04 +0000)
(cherry picked from commit 0152dc4ff5534fa2948b95262e70ff6b202b9b99)

19 files changed:
Lib/test/_test_multiprocessing.py
Lib/test/test_asyncio/test_unix_events.py
Lib/test/test_compileall.py
Lib/test/test_configparser.py
Lib/test/test_ctypes/test_loading.py
Lib/test/test_fileinput.py
Lib/test/test_http_cookiejar.py
Lib/test/test_logging.py
Lib/test/test_mimetypes.py
Lib/test/test_pkgutil.py
Lib/test/test_runpy.py
Lib/test/test_shutil.py
Lib/test/test_subprocess.py
Lib/test/test_tarfile.py
Lib/test/test_tempfile.py
Lib/test/test_venv.py
Lib/test/test_winsound.py
Lib/test/test_zipapp.py
Lib/test/test_zipfile/_path/test_path.py

index 9e688efb1e469bfd2fffba8e501cc3c6eeb9a056..39551234552c678f4f5001492675a842204ecd8c 100644 (file)
@@ -22,7 +22,6 @@ import logging
 import subprocess
 import struct
 import operator
-import pathlib
 import pickle
 import weakref
 import warnings
@@ -324,8 +323,9 @@ class _TestProcess(BaseTestCase):
             self.skipTest(f'test not appropriate for {self.TYPE}')
         paths = [
             sys.executable,               # str
-            sys.executable.encode(),      # bytes
-            pathlib.Path(sys.executable)  # os.PathLike
+            os.fsencode(sys.executable),  # bytes
+            os_helper.FakePath(sys.executable),  # os.PathLike
+            os_helper.FakePath(os.fsencode(sys.executable)),  # os.PathLike bytes
         ]
         for path in paths:
             self.set_executable(path)
index d2c8cba6acfa31c6766db4514a0a17a5b0f1e0e8..35c924a0cd633d72fbda550dd535fbfc3ac5027a 100644 (file)
@@ -6,7 +6,6 @@ import io
 import multiprocessing
 from multiprocessing.util import _cleanup_tests as multiprocessing_cleanup_tests
 import os
-import pathlib
 import signal
 import socket
 import stat
@@ -304,20 +303,20 @@ class SelectorEventLoopUnixSocketTests(test_utils.TestCase):
             self.loop.run_until_complete(srv.wait_closed())
 
     @socket_helper.skip_unless_bind_unix_socket
-    def test_create_unix_server_pathlib(self):
+    def test_create_unix_server_pathlike(self):
         with test_utils.unix_socket_path() as path:
-            path = pathlib.Path(path)
+            path = os_helper.FakePath(path)
             srv_coro = self.loop.create_unix_server(lambda: None, path)
             srv = self.loop.run_until_complete(srv_coro)
             srv.close()
             self.loop.run_until_complete(srv.wait_closed())
 
-    def test_create_unix_connection_pathlib(self):
+    def test_create_unix_connection_pathlike(self):
         with test_utils.unix_socket_path() as path:
-            path = pathlib.Path(path)
+            path = os_helper.FakePath(path)
             coro = self.loop.create_unix_connection(lambda: None, path)
             with self.assertRaises(FileNotFoundError):
-                # If pathlib.Path wasn't supported, the exception would be
+                # If path-like object weren't supported, the exception would be
                 # different.
                 self.loop.run_until_complete(coro)
 
index 5189637c5cfd6d37f002f62099662936696a2a3f..5832f8443f941e555c4292e21e6e5d4ec405a031 100644 (file)
@@ -4,7 +4,6 @@ import filecmp
 import importlib.util
 import io
 import os
-import pathlib
 import py_compile
 import shutil
 import struct
@@ -31,6 +30,7 @@ from test.support import os_helper
 from test.support import script_helper
 from test.test_py_compile import without_source_date_epoch
 from test.test_py_compile import SourceDateEpochTestMeta
+from test.support.os_helper import FakePath
 
 
 def get_pyc(script, opt):
@@ -156,28 +156,28 @@ class CompileallTestsBase:
         self.assertFalse(os.path.isfile(self.bc_path))
         # we should also test the output
         with support.captured_stdout() as stdout:
-            self.assertTrue(compileall.compile_file(pathlib.Path(self.source_path)))
+            self.assertTrue(compileall.compile_file(FakePath(self.source_path)))
         self.assertRegex(stdout.getvalue(), r'Compiling ([^WindowsPath|PosixPath].*)')
         self.assertTrue(os.path.isfile(self.bc_path))
 
     def test_compile_file_pathlike_ddir(self):
         self.assertFalse(os.path.isfile(self.bc_path))
-        self.assertTrue(compileall.compile_file(pathlib.Path(self.source_path),
-                                                ddir=pathlib.Path('ddir_path'),
+        self.assertTrue(compileall.compile_file(FakePath(self.source_path),
+                                                ddir=FakePath('ddir_path'),
                                                 quiet=2))
         self.assertTrue(os.path.isfile(self.bc_path))
 
     def test_compile_file_pathlike_stripdir(self):
         self.assertFalse(os.path.isfile(self.bc_path))
-        self.assertTrue(compileall.compile_file(pathlib.Path(self.source_path),
-                                                stripdir=pathlib.Path('stripdir_path'),
+        self.assertTrue(compileall.compile_file(FakePath(self.source_path),
+                                                stripdir=FakePath('stripdir_path'),
                                                 quiet=2))
         self.assertTrue(os.path.isfile(self.bc_path))
 
     def test_compile_file_pathlike_prependdir(self):
         self.assertFalse(os.path.isfile(self.bc_path))
-        self.assertTrue(compileall.compile_file(pathlib.Path(self.source_path),
-                                                prependdir=pathlib.Path('prependdir_path'),
+        self.assertTrue(compileall.compile_file(FakePath(self.source_path),
+                                                prependdir=FakePath('prependdir_path'),
                                                 quiet=2))
         self.assertTrue(os.path.isfile(self.bc_path))
 
@@ -228,22 +228,22 @@ class CompileallTestsBase:
     def test_compile_dir_pathlike(self):
         self.assertFalse(os.path.isfile(self.bc_path))
         with support.captured_stdout() as stdout:
-            compileall.compile_dir(pathlib.Path(self.directory))
+            compileall.compile_dir(FakePath(self.directory))
         line = stdout.getvalue().splitlines()[0]
         self.assertRegex(line, r'Listing ([^WindowsPath|PosixPath].*)')
         self.assertTrue(os.path.isfile(self.bc_path))
 
     def test_compile_dir_pathlike_stripdir(self):
         self.assertFalse(os.path.isfile(self.bc_path))
-        self.assertTrue(compileall.compile_dir(pathlib.Path(self.directory),
-                                               stripdir=pathlib.Path('stripdir_path'),
+        self.assertTrue(compileall.compile_dir(FakePath(self.directory),
+                                               stripdir=FakePath('stripdir_path'),
                                                quiet=2))
         self.assertTrue(os.path.isfile(self.bc_path))
 
     def test_compile_dir_pathlike_prependdir(self):
         self.assertFalse(os.path.isfile(self.bc_path))
-        self.assertTrue(compileall.compile_dir(pathlib.Path(self.directory),
-                                               prependdir=pathlib.Path('prependdir_path'),
+        self.assertTrue(compileall.compile_dir(FakePath(self.directory),
+                                               prependdir=FakePath('prependdir_path'),
                                                quiet=2))
         self.assertTrue(os.path.isfile(self.bc_path))
 
index 5e6e57ad5736c105baa085ceac4ab1d16cbfb4b0..b7e68d7a3e733258c734279c387f6dc59aa42083 100644 (file)
@@ -2,7 +2,6 @@ import collections
 import configparser
 import io
 import os
-import pathlib
 import textwrap
 import unittest
 import warnings
@@ -746,12 +745,12 @@ boolean {0[0]} NO
         self.assertEqual(cf.get("Foo Bar", "foo"), "newbar")
         # check when we pass only a Path object:
         cf = self.newconfig()
-        parsed_files = cf.read(pathlib.Path(file1), encoding="utf-8")
+        parsed_files = cf.read(os_helper.FakePath(file1), encoding="utf-8")
         self.assertEqual(parsed_files, [file1])
         self.assertEqual(cf.get("Foo Bar", "foo"), "newbar")
         # check when we passed both a filename and a Path object:
         cf = self.newconfig()
-        parsed_files = cf.read([pathlib.Path(file1), file1], encoding="utf-8")
+        parsed_files = cf.read([os_helper.FakePath(file1), file1], encoding="utf-8")
         self.assertEqual(parsed_files, [file1, file1])
         self.assertEqual(cf.get("Foo Bar", "foo"), "newbar")
         # check when we pass only missing files:
index 0ecd2b41869e35319816ceeb043cc401a7eb43c6..fab3deb20dd22e7b3740ccdac57e15a2e651a8c3 100644 (file)
@@ -38,10 +38,7 @@ class LoaderTest(unittest.TestCase):
                 self.skipTest('could not find library to load')
         CDLL(test_lib)
         CDLL(os.path.basename(test_lib))
-        class CTypesTestPathLikeCls:
-            def __fspath__(self):
-                return test_lib
-        CDLL(CTypesTestPathLikeCls())
+        CDLL(os_helper.FakePath(test_lib))
         self.assertRaises(OSError, CDLL, self.unknowndll)
 
     def test_load_version(self):
index 786d9186634305b2b8a472c90013e536fed6da06..f5c1f26fafb148f79d7cbda1ab92dd158815d87e 100644 (file)
@@ -23,10 +23,9 @@ except ImportError:
 
 from io import BytesIO, StringIO
 from fileinput import FileInput, hook_encoded
-from pathlib import Path
 
 from test.support import verbose
-from test.support.os_helper import TESTFN
+from test.support.os_helper import TESTFN, FakePath
 from test.support.os_helper import unlink as safe_unlink
 from test.support import os_helper
 from test import support
@@ -478,23 +477,23 @@ class FileInputTests(BaseTests, unittest.TestCase):
             self.assertRaises(StopIteration, next, fi)
             self.assertEqual(src.linesread, [])
 
-    def test_pathlib_file(self):
-        t1 = Path(self.writeTmp("Pathlib file."))
+    def test_pathlike_file(self):
+        t1 = FakePath(self.writeTmp("Path-like file."))
         with FileInput(t1, encoding="utf-8") as fi:
             line = fi.readline()
-            self.assertEqual(line, 'Pathlib file.')
+            self.assertEqual(line, 'Path-like file.')
             self.assertEqual(fi.lineno(), 1)
             self.assertEqual(fi.filelineno(), 1)
             self.assertEqual(fi.filename(), os.fspath(t1))
 
-    def test_pathlib_file_inplace(self):
-        t1 = Path(self.writeTmp('Pathlib file.'))
+    def test_pathlike_file_inplace(self):
+        t1 = FakePath(self.writeTmp('Path-like file.'))
         with FileInput(t1, inplace=True, encoding="utf-8") as fi:
             line = fi.readline()
-            self.assertEqual(line, 'Pathlib file.')
+            self.assertEqual(line, 'Path-like file.')
             print('Modified %s' % line)
         with open(t1, encoding="utf-8") as f:
-            self.assertEqual(f.read(), 'Modified Pathlib file.\n')
+            self.assertEqual(f.read(), 'Modified Path-like file.\n')
 
 
 class MockFileInput:
index 97e9c82cde9ec46384941001d888d7bdcc973c4e..dbf9ce10f76f91fd89a30c7ed5d1cd75d94002a3 100644 (file)
@@ -9,7 +9,6 @@ from test.support import warnings_helper
 import time
 import unittest
 import urllib.request
-import pathlib
 
 from http.cookiejar import (time2isoz, http2time, iso2time, time2netscape,
      parse_ns_headers, join_header_words, split_header_words, Cookie,
@@ -337,9 +336,9 @@ class FileCookieJarTests(unittest.TestCase):
         self.assertEqual(c.filename, filename)
 
     def test_constructor_with_path_like(self):
-        filename = pathlib.Path(os_helper.TESTFN)
-        c = LWPCookieJar(filename)
-        self.assertEqual(c.filename, os.fspath(filename))
+        filename = os_helper.TESTFN
+        c = LWPCookieJar(os_helper.FakePath(filename))
+        self.assertEqual(c.filename, filename)
 
     def test_constructor_with_none(self):
         c = LWPCookieJar(None)
index cf9fd427be2f912a2f75c598d01e0d6b1b64dec4..5a9772dffafb85a118f62afa4f3b3c1a15f9be91 100644 (file)
@@ -662,15 +662,15 @@ class HandlerTest(BaseTest):
         self.assertFalse(h.shouldFlush(r))
         h.close()
 
-    def test_path_objects(self):
+    def test_pathlike_objects(self):
         """
-        Test that Path objects are accepted as filename arguments to handlers.
+        Test that path-like objects are accepted as filename arguments to handlers.
 
         See Issue #27493.
         """
         fn = make_temp_file()
         os.unlink(fn)
-        pfn = pathlib.Path(fn)
+        pfn = os_helper.FakePath(fn)
         cases = (
                     (logging.FileHandler, (pfn, 'w')),
                     (logging.handlers.RotatingFileHandler, (pfn, 'a')),
index cc91d539d477fa3d8584197ba98dc2fd2ea347ee..90b983aec1b2068a4edfdf397f9c104dbd559bdf 100644 (file)
@@ -1,7 +1,6 @@
 import io
 import mimetypes
 import os
-import pathlib
 import sys
 import unittest.mock
 
@@ -75,11 +74,19 @@ class MimeTypesTestCase(unittest.TestCase):
 
         with os_helper.temp_dir() as directory:
             data = "x-application/x-unittest pyunit\n"
-            file = pathlib.Path(directory, "sample.mimetype")
-            file.write_text(data, encoding="utf-8")
+            file = os.path.join(directory, "sample.mimetype")
+            with open(file, 'w', encoding="utf-8") as f:
+                f.write(data)
             mime_dict = mimetypes.read_mime_types(file)
             eq(mime_dict[".pyunit"], "x-application/x-unittest")
 
+            data = "x-application/x-unittest2 pyunit2\n"
+            file = os.path.join(directory, "sample2.mimetype")
+            with open(file, 'w', encoding="utf-8") as f:
+                f.write(data)
+            mime_dict = mimetypes.read_mime_types(os_helper.FakePath(file))
+            eq(mime_dict[".pyunit2"], "x-application/x-unittest2")
+
         # bpo-41048: read_mime_types should read the rule file with 'utf-8' encoding.
         # Not with locale encoding. _bootlocale has been imported because io.open(...)
         # uses it.
@@ -241,10 +248,10 @@ class MimeTypesTestCase(unittest.TestCase):
 
     def test_path_like_ob(self):
         filename = "LICENSE.txt"
-        filepath = pathlib.Path(filename)
-        filepath_with_abs_dir = pathlib.Path('/dir/'+filename)
-        filepath_relative = pathlib.Path('../dir/'+filename)
-        path_dir = pathlib.Path('./')
+        filepath = os_helper.FakePath(filename)
+        filepath_with_abs_dir = os_helper.FakePath('/dir/'+filename)
+        filepath_relative = os_helper.FakePath('../dir/'+filename)
+        path_dir = os_helper.FakePath('./')
 
         expected = self.db.guess_type(filename)
 
index e19dce1dbd258347165fd8643f093fc0136c9e1d..d095f440a99f637a98188ed9e4d1dc51b2894df1 100644 (file)
@@ -13,6 +13,7 @@ import shutil
 import zipfile
 
 from test.support.import_helper import DirsOnSysPath
+from test.support.os_helper import FakePath
 from test.test_importlib.util import uncache
 
 # Note: pkgutil.walk_packages is currently tested in test_runpy. This is
@@ -121,7 +122,7 @@ class PkgutilTests(unittest.TestCase):
 
             # make sure iter_modules accepts Path objects
             names = []
-            for moduleinfo in pkgutil.iter_modules([Path(zip_file)]):
+            for moduleinfo in pkgutil.iter_modules([FakePath(zip_file)]):
                 self.assertIsInstance(moduleinfo, pkgutil.ModuleInfo)
                 names.append(moduleinfo.name)
             self.assertEqual(names, [pkg])
index 628c8cae38a75194476a2d5fd37c1f09c42f83f6..9c8494105838fc447f4ea94769d902c74a44b54b 100644 (file)
@@ -14,7 +14,7 @@ import unittest
 import warnings
 from test.support import no_tracing, verbose, requires_subprocess, requires_resource
 from test.support.import_helper import forget, make_legacy_pyc, unload
-from test.support.os_helper import create_empty_file, temp_dir
+from test.support.os_helper import create_empty_file, temp_dir, FakePath
 from test.support.script_helper import make_script, make_zip_script
 
 
@@ -656,11 +656,10 @@ class RunPathTestCase(unittest.TestCase, CodeExecutionMixin):
             self._check_script(script_name, "<run_path>", script_name,
                                script_name, expect_spec=False)
 
-    def test_basic_script_with_path_object(self):
+    def test_basic_script_with_pathlike_object(self):
         with temp_dir() as script_dir:
             mod_name = 'script'
-            script_name = pathlib.Path(self._make_test_script(script_dir,
-                                                              mod_name))
+            script_name = FakePath(self._make_test_script(script_dir, mod_name))
             self._check_script(script_name, "<run_path>", script_name,
                                script_name, expect_spec=False)
 
index 012c7118eede1fd9ec7486d5d226298456235cd5..51eccb8a1e4669a0c27e79818c9cfe6c2f32758d 100644 (file)
@@ -859,7 +859,7 @@ class TestCopyTree(BaseTest, unittest.TestCase):
                                     'test.txt')))
 
         dst_dir = join(self.mkdtemp(), 'destination')
-        shutil.copytree(pathlib.Path(src_dir), dst_dir, ignore=_ignore)
+        shutil.copytree(FakePath(src_dir), dst_dir, ignore=_ignore)
         self.assertTrue(exists(join(dst_dir, 'test_dir', 'subdir',
                                     'test.txt')))
 
@@ -2055,7 +2055,7 @@ class TestArchives(BaseTest, unittest.TestCase):
         self.check_unpack_archive_with_converter(
             format, lambda path: path, **kwargs)
         self.check_unpack_archive_with_converter(
-            format, pathlib.Path, **kwargs)
+            format, FakePath, **kwargs)
         self.check_unpack_archive_with_converter(format, FakePath, **kwargs)
 
     def check_unpack_archive_with_converter(self, format, converter, **kwargs):
@@ -2587,12 +2587,12 @@ class TestMove(BaseTest, unittest.TestCase):
 
     def test_move_file_to_dir_pathlike_src(self):
         # Move a pathlike file to another location on the same filesystem.
-        src = pathlib.Path(self.src_file)
+        src = FakePath(self.src_file)
         self._check_move_file(src, self.dst_dir, self.dst_file)
 
     def test_move_file_to_dir_pathlike_dst(self):
         # Move a file to another pathlike location on the same filesystem.
-        dst = pathlib.Path(self.dst_dir)
+        dst = FakePath(self.dst_dir)
         self._check_move_file(self.src_file, dst, self.dst_file)
 
     @mock_rename
index 79efa42791bb2ce308dd5a8ff797cfa15467fcb4..f77c6ecc050f9b52187222ad3b934de2fadd1c1b 100644 (file)
@@ -25,7 +25,6 @@ import threading
 import gc
 import textwrap
 import json
-import pathlib
 from test.support.os_helper import FakePath
 
 try:
@@ -1522,9 +1521,6 @@ class ProcessTestCase(BaseTestCase):
         p.communicate(b"x" * 2**20)
 
     def test_repr(self):
-        path_cmd = pathlib.Path("my-tool.py")
-        pathlib_cls = path_cmd.__class__.__name__
-
         cases = [
             ("ls", True, 123, "<Popen: returncode: 123 args: 'ls'>"),
             ('a' * 100, True, 0,
@@ -1532,7 +1528,8 @@ class ProcessTestCase(BaseTestCase):
             (["ls"], False, None, "<Popen: returncode: None args: ['ls']>"),
             (["ls", '--my-opts', 'a' * 100], False, None,
              "<Popen: returncode: None args: ['ls', '--my-opts', 'aaaaaaaaaaaaaaaaaaaaaaaa...>"),
-            (path_cmd, False, 7, f"<Popen: returncode: 7 args: {pathlib_cls}('my-tool.py')>")
+            (os_helper.FakePath("my-tool.py"), False, 7,
+             "<Popen: returncode: 7 args: <FakePath 'my-tool.py'>>")
         ]
         with unittest.mock.patch.object(subprocess.Popen, '_execute_child'):
             for cmd, shell, code, sx in cases:
index 414843ea4a28442cf382f1eb1005cfdaad2a79c1..3fbd25e742b181c65edb2cfb125c92fa1005b9bc 100644 (file)
@@ -366,7 +366,7 @@ class CommonReadTest(ReadTest):
         self.assertFalse(tarfile.is_tarfile(tmpname))
 
         # is_tarfile works on path-like objects
-        self.assertFalse(tarfile.is_tarfile(pathlib.Path(tmpname)))
+        self.assertFalse(tarfile.is_tarfile(os_helper.FakePath(tmpname)))
 
         # is_tarfile works on file objects
         with open(tmpname, "rb") as fobj:
@@ -380,7 +380,7 @@ class CommonReadTest(ReadTest):
         self.assertTrue(tarfile.is_tarfile(self.tarname))
 
         # is_tarfile works on path-like objects
-        self.assertTrue(tarfile.is_tarfile(pathlib.Path(self.tarname)))
+        self.assertTrue(tarfile.is_tarfile(os_helper.FakePath(self.tarname)))
 
         # is_tarfile works on file objects
         with open(self.tarname, "rb") as fobj:
@@ -558,21 +558,23 @@ class MiscReadTestBase(CommonReadTest):
                 self.assertIsInstance(tar.name, bytes)
                 self.assertEqual(tar.name, os.path.abspath(fobj.name))
 
-    def test_pathlike_name(self):
-        tarname = pathlib.Path(self.tarname)
+    def test_pathlike_name(self, tarname=None):
+        if tarname is None:
+            tarname = self.tarname
+        expected = os.path.abspath(tarname)
+        tarname = os_helper.FakePath(tarname)
         with tarfile.open(tarname, mode=self.mode) as tar:
-            self.assertIsInstance(tar.name, str)
-            self.assertEqual(tar.name, os.path.abspath(os.fspath(tarname)))
+            self.assertEqual(tar.name, expected)
         with self.taropen(tarname) as tar:
-            self.assertIsInstance(tar.name, str)
-            self.assertEqual(tar.name, os.path.abspath(os.fspath(tarname)))
+            self.assertEqual(tar.name, expected)
         with tarfile.TarFile.open(tarname, mode=self.mode) as tar:
-            self.assertIsInstance(tar.name, str)
-            self.assertEqual(tar.name, os.path.abspath(os.fspath(tarname)))
+            self.assertEqual(tar.name, expected)
         if self.suffix == '':
             with tarfile.TarFile(tarname, mode='r') as tar:
-                self.assertIsInstance(tar.name, str)
-                self.assertEqual(tar.name, os.path.abspath(os.fspath(tarname)))
+                self.assertEqual(tar.name, expected)
+
+    def test_pathlike_bytes_name(self):
+        self.test_pathlike_name(os.fsencode(self.tarname))
 
     def test_illegal_mode_arg(self):
         with open(tmpname, 'wb'):
@@ -743,24 +745,24 @@ class MiscReadTestBase(CommonReadTest):
             # check that the stacklevel of the deprecation warning is correct:
             self.assertEqual(cm.filename, __file__)
 
-    def test_extractall_pathlike_name(self):
-        DIR = pathlib.Path(TEMPDIR) / "extractall"
+    def test_extractall_pathlike_dir(self):
+        DIR = os.path.join(TEMPDIR, "extractall")
         with os_helper.temp_dir(DIR), \
              tarfile.open(tarname, encoding="iso8859-1") as tar:
             directories = [t for t in tar if t.isdir()]
-            tar.extractall(DIR, directories, filter='fully_trusted')
+            tar.extractall(os_helper.FakePath(DIR), directories, filter='fully_trusted')
             for tarinfo in directories:
-                path = DIR / tarinfo.name
+                path = os.path.join(DIR, tarinfo.name)
                 self.assertEqual(os.path.getmtime(path), tarinfo.mtime)
 
-    def test_extract_pathlike_name(self):
+    def test_extract_pathlike_dir(self):
         dirtype = "ustar/dirtype"
-        DIR = pathlib.Path(TEMPDIR) / "extractall"
+        DIR = os.path.join(TEMPDIR, "extractall")
         with os_helper.temp_dir(DIR), \
              tarfile.open(tarname, encoding="iso8859-1") as tar:
             tarinfo = tar.getmember(dirtype)
-            tar.extract(tarinfo, path=DIR, filter='fully_trusted')
-            extracted = DIR / dirtype
+            tar.extract(tarinfo, path=os_helper.FakePath(DIR), filter='fully_trusted')
+            extracted = os.path.join(DIR, dirtype)
             self.assertEqual(os.path.getmtime(extracted), tarinfo.mtime)
 
     def test_init_close_fobj(self):
@@ -1359,11 +1361,11 @@ class WriteTest(WriteTestBase, unittest.TestCase):
 
     def test_gettarinfo_pathlike_name(self):
         with tarfile.open(tmpname, self.mode) as tar:
-            path = pathlib.Path(TEMPDIR) / "file"
+            path = os.path.join(TEMPDIR, "file")
             with open(path, "wb") as fobj:
                 fobj.write(b"aaa")
-            tarinfo = tar.gettarinfo(path)
-            tarinfo2 = tar.gettarinfo(os.fspath(path))
+            tarinfo = tar.gettarinfo(os_helper.FakePath(path))
+            tarinfo2 = tar.gettarinfo(path)
             self.assertIsInstance(tarinfo.name, str)
             self.assertEqual(tarinfo.name, tarinfo2.name)
             self.assertEqual(tarinfo.size, 3)
@@ -1910,10 +1912,10 @@ class CreateTest(WriteTestBase, unittest.TestCase):
         self.assertIn("spameggs42", names[0])
 
     def test_create_pathlike_name(self):
-        with tarfile.open(pathlib.Path(tmpname), self.mode) as tobj:
+        with tarfile.open(os_helper.FakePath(tmpname), self.mode) as tobj:
             self.assertIsInstance(tobj.name, str)
             self.assertEqual(tobj.name, os.path.abspath(tmpname))
-            tobj.add(pathlib.Path(self.file_path))
+            tobj.add(os_helper.FakePath(self.file_path))
             names = tobj.getnames()
         self.assertEqual(len(names), 1)
         self.assertIn('spameggs42', names[0])
@@ -1924,10 +1926,10 @@ class CreateTest(WriteTestBase, unittest.TestCase):
         self.assertIn('spameggs42', names[0])
 
     def test_create_taropen_pathlike_name(self):
-        with self.taropen(pathlib.Path(tmpname), "x") as tobj:
+        with self.taropen(os_helper.FakePath(tmpname), "x") as tobj:
             self.assertIsInstance(tobj.name, str)
             self.assertEqual(tobj.name, os.path.abspath(tmpname))
-            tobj.add(pathlib.Path(self.file_path))
+            tobj.add(os_helper.FakePath(self.file_path))
             names = tobj.getnames()
         self.assertEqual(len(names), 1)
         self.assertIn('spameggs42', names[0])
index 19ddeaa169bf9351054679c7f7a9a53b28213335..a5e182cef23dc54f534fe04dcc2aafcf0e35fe6a 100644 (file)
@@ -63,16 +63,10 @@ class TestLowLevelInternals(unittest.TestCase):
             tempfile._infer_return_type(b'', None, '')
 
     def test_infer_return_type_pathlib(self):
-        self.assertIs(str, tempfile._infer_return_type(pathlib.Path('/')))
+        self.assertIs(str, tempfile._infer_return_type(os_helper.FakePath('/')))
 
     def test_infer_return_type_pathlike(self):
-        class Path:
-            def __init__(self, path):
-                self.path = path
-
-            def __fspath__(self):
-                return self.path
-
+        Path = os_helper.FakePath
         self.assertIs(str, tempfile._infer_return_type(Path('/')))
         self.assertIs(bytes, tempfile._infer_return_type(Path(b'/')))
         self.assertIs(str, tempfile._infer_return_type('', Path('')))
@@ -443,7 +437,7 @@ class TestMkstempInner(TestBadTempdir, BaseTestCase):
         dir = tempfile.mkdtemp()
         try:
             self.do_create(dir=dir).write(b"blat")
-            self.do_create(dir=pathlib.Path(dir)).write(b"blat")
+            self.do_create(dir=os_helper.FakePath(dir)).write(b"blat")
         finally:
             support.gc_collect()  # For PyPy or other GCs.
             os.rmdir(dir)
@@ -681,7 +675,7 @@ class TestMkstemp(BaseTestCase):
         dir = tempfile.mkdtemp()
         try:
             self.do_create(dir=dir)
-            self.do_create(dir=pathlib.Path(dir))
+            self.do_create(dir=os_helper.FakePath(dir))
         finally:
             os.rmdir(dir)
 
@@ -782,7 +776,7 @@ class TestMkdtemp(TestBadTempdir, BaseTestCase):
         dir = tempfile.mkdtemp()
         try:
             os.rmdir(self.do_create(dir=dir))
-            os.rmdir(self.do_create(dir=pathlib.Path(dir)))
+            os.rmdir(self.do_create(dir=os_helper.FakePath(dir)))
         finally:
             os.rmdir(dir)
 
index 34e13e2c5774666d2c420f56432ecc726ea00b58..feaf978454906832690bb7df55bd08263d425cd4 100644 (file)
@@ -23,7 +23,7 @@ from test.support import (captured_stdout, captured_stderr,
                           requires_venv_with_pip, TEST_HOME_DIR,
                           requires_resource, copy_python_src_ignore)
 from test.support.os_helper import (can_symlink, EnvironmentVarGuard, rmtree,
-                                    TESTFN)
+                                    TESTFN, FakePath)
 import unittest
 import venv
 from unittest.mock import patch, Mock
@@ -112,12 +112,12 @@ class BasicTest(BaseTest):
         self.run_with_capture(venv.create, self.env_dir)
         self._check_output_of_default_create()
 
-    def test_defaults_with_pathlib_path(self):
+    def test_defaults_with_pathlike(self):
         """
-        Test the create function with default arguments and a pathlib.Path path.
+        Test the create function with default arguments and a path-like path.
         """
         rmtree(self.env_dir)
-        self.run_with_capture(venv.create, pathlib.Path(self.env_dir))
+        self.run_with_capture(venv.create, FakePath(self.env_dir))
         self._check_output_of_default_create()
 
     def _check_output_of_default_create(self):
@@ -537,7 +537,7 @@ class BasicTest(BaseTest):
         rmtree(self.env_dir)
         bad_itempath = self.env_dir + os.pathsep
         self.assertRaises(ValueError, venv.create, bad_itempath)
-        self.assertRaises(ValueError, venv.create, pathlib.Path(bad_itempath))
+        self.assertRaises(ValueError, venv.create, FakePath(bad_itempath))
 
     @unittest.skipIf(os.name == 'nt', 'not relevant on Windows')
     @requireVenvCreate
index a59d0d24f5db4863cc8f5df195d5c21cf00b76f0..870ab7bd41d8ce7038d5dbcd47ffeb8b75e1b070 100644 (file)
@@ -1,12 +1,13 @@
 # Ridiculously simple test of the winsound module for Windows.
 
 import functools
-import pathlib
+import os
 import time
 import unittest
 
 from test import support
 from test.support import import_helper
+from test.support import os_helper
 
 
 support.requires('audio')
@@ -85,13 +86,6 @@ class MessageBeepTest(unittest.TestCase):
         safe_MessageBeep(type=winsound.MB_OK)
 
 
-# A class for testing winsound when the given path resolves
-# to bytes rather than str.
-class BytesPath(pathlib.WindowsPath):
-    def __fspath__(self):
-        return bytes(super().__fspath__(), 'UTF-8')
-
-
 class PlaySoundTest(unittest.TestCase):
 
     def test_errors(self):
@@ -126,7 +120,7 @@ class PlaySoundTest(unittest.TestCase):
 
     def test_snd_filepath(self):
         fn = support.findfile('pluck-pcm8.wav', subdir='audiodata')
-        path = pathlib.Path(fn)
+        path = os_helper.FakePath(fn)
         safe_PlaySound(path, winsound.SND_FILENAME | winsound.SND_NODEFAULT)
 
     def test_snd_filepath_as_bytes(self):
@@ -134,7 +128,7 @@ class PlaySoundTest(unittest.TestCase):
         self.assertRaises(
             TypeError,
             winsound.PlaySound,
-            BytesPath(fn),
+            os_helper.FakePath(os.fsencode(fn)),
             winsound.SND_FILENAME | winsound.SND_NODEFAULT
         )
 
index f1c6b2d97621ee5bb2c1041801e6c73bb58d6289..00a5ed6626ddc55d036ab948febe1b85de071a7e 100644 (file)
@@ -265,14 +265,15 @@ class ZipAppTest(unittest.TestCase):
         zipapp.create_archive(str(target), new_target, interpreter='python2.7')
         self.assertTrue(new_target.getvalue().startswith(b'#!python2.7\n'))
 
-    def test_read_from_pathobj(self):
-        # Test that we can copy an archive using a pathlib.Path object
+    def test_read_from_pathlike_obj(self):
+        # Test that we can copy an archive using a path-like object
         # for the source.
         source = self.tmpdir / 'source'
         source.mkdir()
         (source / '__main__.py').touch()
-        target1 = self.tmpdir / 'target1.pyz'
-        target2 = self.tmpdir / 'target2.pyz'
+        source = os_helper.FakePath(str(source))
+        target1 = os_helper.FakePath(str(self.tmpdir / 'target1.pyz'))
+        target2 = os_helper.FakePath(str(self.tmpdir / 'target2.pyz'))
         zipapp.create_archive(source, target1, interpreter='python')
         zipapp.create_archive(target1, target2, interpreter='python2.7')
         self.assertEqual(zipapp.get_interpreter(target2), 'python2.7')
index c66cb3cba69ebd05de2fb0a51b796d3e7f1a05c9..67602421f6be38991bcb13f5000e710f29954f36 100644 (file)
@@ -12,7 +12,7 @@ from ._itertools import Counter
 
 from ._test_params import parameterize, Invoked
 
-from test.support.os_helper import temp_dir
+from test.support.os_helper import temp_dir, FakePath
 
 
 class jaraco:
@@ -271,13 +271,13 @@ class TestPath(unittest.TestCase):
         zipfile.Path should be constructable from a path-like object
         """
         zipfile_ondisk = self.zipfile_ondisk(alpharep)
-        pathlike = pathlib.Path(str(zipfile_ondisk))
+        pathlike = FakePath(str(zipfile_ondisk))
         zipfile.Path(pathlike)
 
     @pass_alpharep
     def test_traverse_pathlike(self, alpharep):
         root = zipfile.Path(alpharep)
-        root / pathlib.Path("a")
+        root / FakePath("a")
 
     @pass_alpharep
     def test_parent(self, alpharep):
@@ -546,12 +546,12 @@ class TestPath(unittest.TestCase):
         ['alpharep', 'path_type', 'subpath'],
         itertools.product(
             alpharep_generators,
-            [str, pathlib.Path],
+            [str, FakePath],
             ['', 'b/'],
         ),
     )
     def test_pickle(self, alpharep, path_type, subpath):
-        zipfile_ondisk = path_type(self.zipfile_ondisk(alpharep))
+        zipfile_ondisk = path_type(str(self.zipfile_ondisk(alpharep)))
 
         saved_1 = pickle.dumps(zipfile.Path(zipfile_ondisk, at=subpath))
         restored_1 = pickle.loads(saved_1)