[3.13] gh-119064: Use os_helper.FakePath instead of pathlib.Path in tests (GH-119065) (GH-119087)

(cherry picked from commit 0152dc4ff5)

Co-authored-by: Serhiy Storchaka <storchaka@gmail.com>
This commit is contained in:
Miss Islington (bot) 2024-05-16 09:51:18 +02:00 committed by GitHub
parent bca7fb0e7a
commit 1dc7fcd803
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
19 changed files with 115 additions and 127 deletions

View File

@ -22,7 +22,6 @@ import logging
import subprocess import subprocess
import struct import struct
import operator import operator
import pathlib
import pickle import pickle
import weakref import weakref
import warnings import warnings
@ -324,8 +323,9 @@ class _TestProcess(BaseTestCase):
self.skipTest(f'test not appropriate for {self.TYPE}') self.skipTest(f'test not appropriate for {self.TYPE}')
paths = [ paths = [
sys.executable, # str sys.executable, # str
sys.executable.encode(), # bytes os.fsencode(sys.executable), # bytes
pathlib.Path(sys.executable) # os.PathLike os_helper.FakePath(sys.executable), # os.PathLike
os_helper.FakePath(os.fsencode(sys.executable)), # os.PathLike bytes
] ]
for path in paths: for path in paths:
self.set_executable(path) self.set_executable(path)

View File

@ -6,7 +6,6 @@ import io
import multiprocessing import multiprocessing
from multiprocessing.util import _cleanup_tests as multiprocessing_cleanup_tests from multiprocessing.util import _cleanup_tests as multiprocessing_cleanup_tests
import os import os
import pathlib
import signal import signal
import socket import socket
import stat import stat
@ -304,20 +303,20 @@ class SelectorEventLoopUnixSocketTests(test_utils.TestCase):
self.loop.run_until_complete(srv.wait_closed()) self.loop.run_until_complete(srv.wait_closed())
@socket_helper.skip_unless_bind_unix_socket @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: 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_coro = self.loop.create_unix_server(lambda: None, path)
srv = self.loop.run_until_complete(srv_coro) srv = self.loop.run_until_complete(srv_coro)
srv.close() srv.close()
self.loop.run_until_complete(srv.wait_closed()) 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: 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) coro = self.loop.create_unix_connection(lambda: None, path)
with self.assertRaises(FileNotFoundError): 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. # different.
self.loop.run_until_complete(coro) self.loop.run_until_complete(coro)

View File

@ -4,7 +4,6 @@ import filecmp
import importlib.util import importlib.util
import io import io
import os import os
import pathlib
import py_compile import py_compile
import shutil import shutil
import struct import struct
@ -31,6 +30,7 @@ from test.support import os_helper
from test.support import script_helper from test.support import script_helper
from test.test_py_compile import without_source_date_epoch from test.test_py_compile import without_source_date_epoch
from test.test_py_compile import SourceDateEpochTestMeta from test.test_py_compile import SourceDateEpochTestMeta
from test.support.os_helper import FakePath
def get_pyc(script, opt): def get_pyc(script, opt):
@ -156,28 +156,28 @@ class CompileallTestsBase:
self.assertFalse(os.path.isfile(self.bc_path)) self.assertFalse(os.path.isfile(self.bc_path))
# we should also test the output # we should also test the output
with support.captured_stdout() as stdout: 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.assertRegex(stdout.getvalue(), r'Compiling ([^WindowsPath|PosixPath].*)')
self.assertTrue(os.path.isfile(self.bc_path)) self.assertTrue(os.path.isfile(self.bc_path))
def test_compile_file_pathlike_ddir(self): def test_compile_file_pathlike_ddir(self):
self.assertFalse(os.path.isfile(self.bc_path)) self.assertFalse(os.path.isfile(self.bc_path))
self.assertTrue(compileall.compile_file(pathlib.Path(self.source_path), self.assertTrue(compileall.compile_file(FakePath(self.source_path),
ddir=pathlib.Path('ddir_path'), ddir=FakePath('ddir_path'),
quiet=2)) quiet=2))
self.assertTrue(os.path.isfile(self.bc_path)) self.assertTrue(os.path.isfile(self.bc_path))
def test_compile_file_pathlike_stripdir(self): def test_compile_file_pathlike_stripdir(self):
self.assertFalse(os.path.isfile(self.bc_path)) self.assertFalse(os.path.isfile(self.bc_path))
self.assertTrue(compileall.compile_file(pathlib.Path(self.source_path), self.assertTrue(compileall.compile_file(FakePath(self.source_path),
stripdir=pathlib.Path('stripdir_path'), stripdir=FakePath('stripdir_path'),
quiet=2)) quiet=2))
self.assertTrue(os.path.isfile(self.bc_path)) self.assertTrue(os.path.isfile(self.bc_path))
def test_compile_file_pathlike_prependdir(self): def test_compile_file_pathlike_prependdir(self):
self.assertFalse(os.path.isfile(self.bc_path)) self.assertFalse(os.path.isfile(self.bc_path))
self.assertTrue(compileall.compile_file(pathlib.Path(self.source_path), self.assertTrue(compileall.compile_file(FakePath(self.source_path),
prependdir=pathlib.Path('prependdir_path'), prependdir=FakePath('prependdir_path'),
quiet=2)) quiet=2))
self.assertTrue(os.path.isfile(self.bc_path)) self.assertTrue(os.path.isfile(self.bc_path))
@ -228,22 +228,22 @@ class CompileallTestsBase:
def test_compile_dir_pathlike(self): def test_compile_dir_pathlike(self):
self.assertFalse(os.path.isfile(self.bc_path)) self.assertFalse(os.path.isfile(self.bc_path))
with support.captured_stdout() as stdout: with support.captured_stdout() as stdout:
compileall.compile_dir(pathlib.Path(self.directory)) compileall.compile_dir(FakePath(self.directory))
line = stdout.getvalue().splitlines()[0] line = stdout.getvalue().splitlines()[0]
self.assertRegex(line, r'Listing ([^WindowsPath|PosixPath].*)') self.assertRegex(line, r'Listing ([^WindowsPath|PosixPath].*)')
self.assertTrue(os.path.isfile(self.bc_path)) self.assertTrue(os.path.isfile(self.bc_path))
def test_compile_dir_pathlike_stripdir(self): def test_compile_dir_pathlike_stripdir(self):
self.assertFalse(os.path.isfile(self.bc_path)) self.assertFalse(os.path.isfile(self.bc_path))
self.assertTrue(compileall.compile_dir(pathlib.Path(self.directory), self.assertTrue(compileall.compile_dir(FakePath(self.directory),
stripdir=pathlib.Path('stripdir_path'), stripdir=FakePath('stripdir_path'),
quiet=2)) quiet=2))
self.assertTrue(os.path.isfile(self.bc_path)) self.assertTrue(os.path.isfile(self.bc_path))
def test_compile_dir_pathlike_prependdir(self): def test_compile_dir_pathlike_prependdir(self):
self.assertFalse(os.path.isfile(self.bc_path)) self.assertFalse(os.path.isfile(self.bc_path))
self.assertTrue(compileall.compile_dir(pathlib.Path(self.directory), self.assertTrue(compileall.compile_dir(FakePath(self.directory),
prependdir=pathlib.Path('prependdir_path'), prependdir=FakePath('prependdir_path'),
quiet=2)) quiet=2))
self.assertTrue(os.path.isfile(self.bc_path)) self.assertTrue(os.path.isfile(self.bc_path))

View File

@ -2,7 +2,6 @@ import collections
import configparser import configparser
import io import io
import os import os
import pathlib
import textwrap import textwrap
import unittest import unittest
@ -745,12 +744,12 @@ boolean {0[0]} NO
self.assertEqual(cf.get("Foo Bar", "foo"), "newbar") self.assertEqual(cf.get("Foo Bar", "foo"), "newbar")
# check when we pass only a Path object: # check when we pass only a Path object:
cf = self.newconfig() 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(parsed_files, [file1])
self.assertEqual(cf.get("Foo Bar", "foo"), "newbar") self.assertEqual(cf.get("Foo Bar", "foo"), "newbar")
# check when we passed both a filename and a Path object: # check when we passed both a filename and a Path object:
cf = self.newconfig() 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(parsed_files, [file1, file1])
self.assertEqual(cf.get("Foo Bar", "foo"), "newbar") self.assertEqual(cf.get("Foo Bar", "foo"), "newbar")
# check when we pass only missing files: # check when we pass only missing files:

View File

@ -42,10 +42,7 @@ class LoaderTest(unittest.TestCase):
self.skipTest('could not find library to load') self.skipTest('could not find library to load')
CDLL(test_lib) CDLL(test_lib)
CDLL(os.path.basename(test_lib)) CDLL(os.path.basename(test_lib))
class CTypesTestPathLikeCls: CDLL(os_helper.FakePath(test_lib))
def __fspath__(self):
return test_lib
CDLL(CTypesTestPathLikeCls())
self.assertRaises(OSError, CDLL, self.unknowndll) self.assertRaises(OSError, CDLL, self.unknowndll)
def test_load_version(self): def test_load_version(self):

View File

@ -23,10 +23,9 @@ except ImportError:
from io import BytesIO, StringIO from io import BytesIO, StringIO
from fileinput import FileInput, hook_encoded from fileinput import FileInput, hook_encoded
from pathlib import Path
from test.support import verbose 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.os_helper import unlink as safe_unlink
from test.support import os_helper from test.support import os_helper
from test import support from test import support
@ -478,23 +477,23 @@ class FileInputTests(BaseTests, unittest.TestCase):
self.assertRaises(StopIteration, next, fi) self.assertRaises(StopIteration, next, fi)
self.assertEqual(src.linesread, []) self.assertEqual(src.linesread, [])
def test_pathlib_file(self): def test_pathlike_file(self):
t1 = Path(self.writeTmp("Pathlib file.")) t1 = FakePath(self.writeTmp("Path-like file."))
with FileInput(t1, encoding="utf-8") as fi: with FileInput(t1, encoding="utf-8") as fi:
line = fi.readline() line = fi.readline()
self.assertEqual(line, 'Pathlib file.') self.assertEqual(line, 'Path-like file.')
self.assertEqual(fi.lineno(), 1) self.assertEqual(fi.lineno(), 1)
self.assertEqual(fi.filelineno(), 1) self.assertEqual(fi.filelineno(), 1)
self.assertEqual(fi.filename(), os.fspath(t1)) self.assertEqual(fi.filename(), os.fspath(t1))
def test_pathlib_file_inplace(self): def test_pathlike_file_inplace(self):
t1 = Path(self.writeTmp('Pathlib file.')) t1 = FakePath(self.writeTmp('Path-like file.'))
with FileInput(t1, inplace=True, encoding="utf-8") as fi: with FileInput(t1, inplace=True, encoding="utf-8") as fi:
line = fi.readline() line = fi.readline()
self.assertEqual(line, 'Pathlib file.') self.assertEqual(line, 'Path-like file.')
print('Modified %s' % line) print('Modified %s' % line)
with open(t1, encoding="utf-8") as f: 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: class MockFileInput:

View File

@ -9,7 +9,6 @@ from test.support import warnings_helper
import time import time
import unittest import unittest
import urllib.request import urllib.request
import pathlib
from http.cookiejar import (time2isoz, http2time, iso2time, time2netscape, from http.cookiejar import (time2isoz, http2time, iso2time, time2netscape,
parse_ns_headers, join_header_words, split_header_words, Cookie, parse_ns_headers, join_header_words, split_header_words, Cookie,
@ -337,9 +336,9 @@ class FileCookieJarTests(unittest.TestCase):
self.assertEqual(c.filename, filename) self.assertEqual(c.filename, filename)
def test_constructor_with_path_like(self): def test_constructor_with_path_like(self):
filename = pathlib.Path(os_helper.TESTFN) filename = os_helper.TESTFN
c = LWPCookieJar(filename) c = LWPCookieJar(os_helper.FakePath(filename))
self.assertEqual(c.filename, os.fspath(filename)) self.assertEqual(c.filename, filename)
def test_constructor_with_none(self): def test_constructor_with_none(self):
c = LWPCookieJar(None) c = LWPCookieJar(None)

View File

@ -657,15 +657,15 @@ class HandlerTest(BaseTest):
self.assertFalse(h.shouldFlush(r)) self.assertFalse(h.shouldFlush(r))
h.close() 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. See Issue #27493.
""" """
fn = make_temp_file() fn = make_temp_file()
os.unlink(fn) os.unlink(fn)
pfn = pathlib.Path(fn) pfn = os_helper.FakePath(fn)
cases = ( cases = (
(logging.FileHandler, (pfn, 'w')), (logging.FileHandler, (pfn, 'w')),
(logging.handlers.RotatingFileHandler, (pfn, 'a')), (logging.handlers.RotatingFileHandler, (pfn, 'a')),

View File

@ -1,7 +1,6 @@
import io import io
import mimetypes import mimetypes
import os import os
import pathlib
import sys import sys
import unittest.mock import unittest.mock
@ -83,11 +82,19 @@ class MimeTypesTestCase(unittest.TestCase):
with os_helper.temp_dir() as directory: with os_helper.temp_dir() as directory:
data = "x-application/x-unittest pyunit\n" data = "x-application/x-unittest pyunit\n"
file = pathlib.Path(directory, "sample.mimetype") file = os.path.join(directory, "sample.mimetype")
file.write_text(data, encoding="utf-8") with open(file, 'w', encoding="utf-8") as f:
f.write(data)
mime_dict = mimetypes.read_mime_types(file) mime_dict = mimetypes.read_mime_types(file)
eq(mime_dict[".pyunit"], "x-application/x-unittest") 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. # 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(...) # Not with locale encoding. _bootlocale has been imported because io.open(...)
# uses it. # uses it.

View File

@ -13,6 +13,7 @@ import shutil
import zipfile import zipfile
from test.support.import_helper import DirsOnSysPath from test.support.import_helper import DirsOnSysPath
from test.support.os_helper import FakePath
from test.test_importlib.util import uncache from test.test_importlib.util import uncache
# Note: pkgutil.walk_packages is currently tested in test_runpy. This is # 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 # make sure iter_modules accepts Path objects
names = [] names = []
for moduleinfo in pkgutil.iter_modules([Path(zip_file)]): for moduleinfo in pkgutil.iter_modules([FakePath(zip_file)]):
self.assertIsInstance(moduleinfo, pkgutil.ModuleInfo) self.assertIsInstance(moduleinfo, pkgutil.ModuleInfo)
names.append(moduleinfo.name) names.append(moduleinfo.name)
self.assertEqual(names, [pkg]) self.assertEqual(names, [pkg])

View File

@ -15,7 +15,7 @@ import warnings
from test.support import (infinite_recursion, no_tracing, verbose, from test.support import (infinite_recursion, no_tracing, verbose,
requires_subprocess, requires_resource) requires_subprocess, requires_resource)
from test.support.import_helper import forget, make_legacy_pyc, unload 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 from test.support.script_helper import make_script, make_zip_script
@ -657,14 +657,13 @@ class RunPathTestCase(unittest.TestCase, CodeExecutionMixin):
self._check_script(script_name, "<run_path>", script_name, self._check_script(script_name, "<run_path>", script_name,
script_name, expect_spec=False) 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: with temp_dir() as script_dir:
mod_name = 'script' mod_name = 'script'
script_name = pathlib.Path(self._make_test_script(script_dir, script_name = self._make_test_script(script_dir, mod_name)
mod_name)) self._check_script(FakePath(script_name), "<run_path>",
self._check_script(script_name, "<run_path>", script_name,
os.fsdecode(script_name), script_name,
os.fsdecode(script_name),
expect_spec=False) expect_spec=False)
def test_basic_script_no_suffix(self): def test_basic_script_no_suffix(self):

View File

@ -914,7 +914,7 @@ class TestCopyTree(BaseTest, unittest.TestCase):
'test.txt'))) 'test.txt')))
dst_dir = join(self.mkdtemp(), 'destination') 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', self.assertTrue(exists(join(dst_dir, 'test_dir', 'subdir',
'test.txt'))) 'test.txt')))
@ -2107,7 +2107,7 @@ class TestArchives(BaseTest, unittest.TestCase):
self.check_unpack_archive_with_converter( self.check_unpack_archive_with_converter(
format, lambda path: path, **kwargs) format, lambda path: path, **kwargs)
self.check_unpack_archive_with_converter( self.check_unpack_archive_with_converter(
format, pathlib.Path, **kwargs) format, FakePath, **kwargs)
self.check_unpack_archive_with_converter(format, FakePath, **kwargs) self.check_unpack_archive_with_converter(format, FakePath, **kwargs)
def check_unpack_archive_with_converter(self, format, converter, **kwargs): def check_unpack_archive_with_converter(self, format, converter, **kwargs):
@ -2672,12 +2672,12 @@ class TestMove(BaseTest, unittest.TestCase):
def test_move_file_to_dir_pathlike_src(self): def test_move_file_to_dir_pathlike_src(self):
# Move a pathlike file to another location on the same filesystem. # 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) self._check_move_file(src, self.dst_dir, self.dst_file)
def test_move_file_to_dir_pathlike_dst(self): def test_move_file_to_dir_pathlike_dst(self):
# Move a file to another pathlike location on the same filesystem. # 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) self._check_move_file(self.src_file, dst, self.dst_file)
@mock_rename @mock_rename

View File

@ -25,7 +25,6 @@ import threading
import gc import gc
import textwrap import textwrap
import json import json
import pathlib
from test.support.os_helper import FakePath from test.support.os_helper import FakePath
try: try:
@ -1522,9 +1521,6 @@ class ProcessTestCase(BaseTestCase):
p.communicate(b"x" * 2**20) p.communicate(b"x" * 2**20)
def test_repr(self): def test_repr(self):
path_cmd = pathlib.Path("my-tool.py")
pathlib_cls = path_cmd.__class__.__name__
cases = [ cases = [
("ls", True, 123, "<Popen: returncode: 123 args: 'ls'>"), ("ls", True, 123, "<Popen: returncode: 123 args: 'ls'>"),
('a' * 100, True, 0, ('a' * 100, True, 0,
@ -1532,7 +1528,8 @@ class ProcessTestCase(BaseTestCase):
(["ls"], False, None, "<Popen: returncode: None args: ['ls']>"), (["ls"], False, None, "<Popen: returncode: None args: ['ls']>"),
(["ls", '--my-opts', 'a' * 100], False, None, (["ls", '--my-opts', 'a' * 100], False, None,
"<Popen: returncode: None args: ['ls', '--my-opts', 'aaaaaaaaaaaaaaaaaaaaaaaa...>"), "<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'): with unittest.mock.patch.object(subprocess.Popen, '_execute_child'):
for cmd, shell, code, sx in cases: for cmd, shell, code, sx in cases:

View File

@ -386,7 +386,7 @@ class CommonReadTest(ReadTest):
self.assertFalse(tarfile.is_tarfile(tmpname)) self.assertFalse(tarfile.is_tarfile(tmpname))
# is_tarfile works on path-like objects # 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 # is_tarfile works on file objects
with open(tmpname, "rb") as fobj: with open(tmpname, "rb") as fobj:
@ -400,7 +400,7 @@ class CommonReadTest(ReadTest):
self.assertTrue(tarfile.is_tarfile(self.tarname)) self.assertTrue(tarfile.is_tarfile(self.tarname))
# is_tarfile works on path-like objects # 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 # is_tarfile works on file objects
with open(self.tarname, "rb") as fobj: with open(self.tarname, "rb") as fobj:
@ -576,21 +576,23 @@ class MiscReadTestBase(CommonReadTest):
self.assertIsInstance(tar.name, bytes) self.assertIsInstance(tar.name, bytes)
self.assertEqual(tar.name, os.path.abspath(fobj.name)) self.assertEqual(tar.name, os.path.abspath(fobj.name))
def test_pathlike_name(self): def test_pathlike_name(self, tarname=None):
tarname = pathlib.Path(self.tarname) 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: with tarfile.open(tarname, mode=self.mode) as tar:
self.assertIsInstance(tar.name, str) self.assertEqual(tar.name, expected)
self.assertEqual(tar.name, os.path.abspath(os.fspath(tarname)))
with self.taropen(tarname) as tar: with self.taropen(tarname) as tar:
self.assertIsInstance(tar.name, str) self.assertEqual(tar.name, expected)
self.assertEqual(tar.name, os.path.abspath(os.fspath(tarname)))
with tarfile.TarFile.open(tarname, mode=self.mode) as tar: with tarfile.TarFile.open(tarname, mode=self.mode) as tar:
self.assertIsInstance(tar.name, str) self.assertEqual(tar.name, expected)
self.assertEqual(tar.name, os.path.abspath(os.fspath(tarname)))
if self.suffix == '': if self.suffix == '':
with tarfile.TarFile(tarname, mode='r') as tar: with tarfile.TarFile(tarname, mode='r') as tar:
self.assertIsInstance(tar.name, str) self.assertEqual(tar.name, expected)
self.assertEqual(tar.name, os.path.abspath(os.fspath(tarname)))
def test_pathlike_bytes_name(self):
self.test_pathlike_name(os.fsencode(self.tarname))
def test_illegal_mode_arg(self): def test_illegal_mode_arg(self):
with open(tmpname, 'wb'): with open(tmpname, 'wb'):
@ -761,24 +763,24 @@ class MiscReadTestBase(CommonReadTest):
# check that the stacklevel of the deprecation warning is correct: # check that the stacklevel of the deprecation warning is correct:
self.assertEqual(cm.filename, __file__) self.assertEqual(cm.filename, __file__)
def test_extractall_pathlike_name(self): def test_extractall_pathlike_dir(self):
DIR = pathlib.Path(TEMPDIR) / "extractall" DIR = os.path.join(TEMPDIR, "extractall")
with os_helper.temp_dir(DIR), \ with os_helper.temp_dir(DIR), \
tarfile.open(tarname, encoding="iso8859-1") as tar: tarfile.open(tarname, encoding="iso8859-1") as tar:
directories = [t for t in tar if t.isdir()] 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: for tarinfo in directories:
path = DIR / tarinfo.name path = os.path.join(DIR, tarinfo.name)
self.assertEqual(os.path.getmtime(path), tarinfo.mtime) self.assertEqual(os.path.getmtime(path), tarinfo.mtime)
def test_extract_pathlike_name(self): def test_extract_pathlike_dir(self):
dirtype = "ustar/dirtype" dirtype = "ustar/dirtype"
DIR = pathlib.Path(TEMPDIR) / "extractall" DIR = os.path.join(TEMPDIR, "extractall")
with os_helper.temp_dir(DIR), \ with os_helper.temp_dir(DIR), \
tarfile.open(tarname, encoding="iso8859-1") as tar: tarfile.open(tarname, encoding="iso8859-1") as tar:
tarinfo = tar.getmember(dirtype) tarinfo = tar.getmember(dirtype)
tar.extract(tarinfo, path=DIR, filter='fully_trusted') tar.extract(tarinfo, path=os_helper.FakePath(DIR), filter='fully_trusted')
extracted = DIR / dirtype extracted = os.path.join(DIR, dirtype)
self.assertEqual(os.path.getmtime(extracted), tarinfo.mtime) self.assertEqual(os.path.getmtime(extracted), tarinfo.mtime)
def test_init_close_fobj(self): def test_init_close_fobj(self):
@ -1390,11 +1392,11 @@ class WriteTest(WriteTestBase, unittest.TestCase):
def test_gettarinfo_pathlike_name(self): def test_gettarinfo_pathlike_name(self):
with tarfile.open(tmpname, self.mode) as tar: 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: with open(path, "wb") as fobj:
fobj.write(b"aaa") fobj.write(b"aaa")
tarinfo = tar.gettarinfo(path) tarinfo = tar.gettarinfo(os_helper.FakePath(path))
tarinfo2 = tar.gettarinfo(os.fspath(path)) tarinfo2 = tar.gettarinfo(path)
self.assertIsInstance(tarinfo.name, str) self.assertIsInstance(tarinfo.name, str)
self.assertEqual(tarinfo.name, tarinfo2.name) self.assertEqual(tarinfo.name, tarinfo2.name)
self.assertEqual(tarinfo.size, 3) self.assertEqual(tarinfo.size, 3)
@ -1947,10 +1949,10 @@ class CreateTest(WriteTestBase, unittest.TestCase):
self.assertIn("spameggs42", names[0]) self.assertIn("spameggs42", names[0])
def test_create_pathlike_name(self): 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.assertIsInstance(tobj.name, str)
self.assertEqual(tobj.name, os.path.abspath(tmpname)) 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() names = tobj.getnames()
self.assertEqual(len(names), 1) self.assertEqual(len(names), 1)
self.assertIn('spameggs42', names[0]) self.assertIn('spameggs42', names[0])
@ -1961,10 +1963,10 @@ class CreateTest(WriteTestBase, unittest.TestCase):
self.assertIn('spameggs42', names[0]) self.assertIn('spameggs42', names[0])
def test_create_taropen_pathlike_name(self): 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.assertIsInstance(tobj.name, str)
self.assertEqual(tobj.name, os.path.abspath(tmpname)) 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() names = tobj.getnames()
self.assertEqual(len(names), 1) self.assertEqual(len(names), 1)
self.assertIn('spameggs42', names[0]) self.assertIn('spameggs42', names[0])

View File

@ -63,16 +63,10 @@ class TestLowLevelInternals(unittest.TestCase):
tempfile._infer_return_type(b'', None, '') tempfile._infer_return_type(b'', None, '')
def test_infer_return_type_pathlib(self): 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): def test_infer_return_type_pathlike(self):
class Path: Path = os_helper.FakePath
def __init__(self, path):
self.path = path
def __fspath__(self):
return self.path
self.assertIs(str, tempfile._infer_return_type(Path('/'))) self.assertIs(str, tempfile._infer_return_type(Path('/')))
self.assertIs(bytes, tempfile._infer_return_type(Path(b'/'))) self.assertIs(bytes, tempfile._infer_return_type(Path(b'/')))
self.assertIs(str, tempfile._infer_return_type('', Path(''))) self.assertIs(str, tempfile._infer_return_type('', Path('')))
@ -443,7 +437,7 @@ class TestMkstempInner(TestBadTempdir, BaseTestCase):
dir = tempfile.mkdtemp() dir = tempfile.mkdtemp()
try: try:
self.do_create(dir=dir).write(b"blat") 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: finally:
support.gc_collect() # For PyPy or other GCs. support.gc_collect() # For PyPy or other GCs.
os.rmdir(dir) os.rmdir(dir)
@ -681,7 +675,7 @@ class TestMkstemp(BaseTestCase):
dir = tempfile.mkdtemp() dir = tempfile.mkdtemp()
try: try:
self.do_create(dir=dir) self.do_create(dir=dir)
self.do_create(dir=pathlib.Path(dir)) self.do_create(dir=os_helper.FakePath(dir))
finally: finally:
os.rmdir(dir) os.rmdir(dir)
@ -782,7 +776,7 @@ class TestMkdtemp(TestBadTempdir, BaseTestCase):
dir = tempfile.mkdtemp() dir = tempfile.mkdtemp()
try: try:
os.rmdir(self.do_create(dir=dir)) 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: finally:
os.rmdir(dir) os.rmdir(dir)

View File

@ -24,7 +24,7 @@ from test.support import (captured_stdout, captured_stderr,
requires_venv_with_pip, TEST_HOME_DIR, requires_venv_with_pip, TEST_HOME_DIR,
requires_resource, copy_python_src_ignore) requires_resource, copy_python_src_ignore)
from test.support.os_helper import (can_symlink, EnvironmentVarGuard, rmtree, from test.support.os_helper import (can_symlink, EnvironmentVarGuard, rmtree,
TESTFN) TESTFN, FakePath)
import unittest import unittest
import venv import venv
from unittest.mock import patch, Mock from unittest.mock import patch, Mock
@ -125,12 +125,12 @@ class BasicTest(BaseTest):
self.run_with_capture(venv.create, self.env_dir) self.run_with_capture(venv.create, self.env_dir)
self._check_output_of_default_create() 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) 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() self._check_output_of_default_create()
def _check_output_of_default_create(self): def _check_output_of_default_create(self):
@ -572,7 +572,7 @@ class BasicTest(BaseTest):
rmtree(self.env_dir) rmtree(self.env_dir)
bad_itempath = self.env_dir + os.pathsep bad_itempath = self.env_dir + os.pathsep
self.assertRaises(ValueError, venv.create, bad_itempath) 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') @unittest.skipIf(os.name == 'nt', 'not relevant on Windows')
@requireVenvCreate @requireVenvCreate

View File

@ -1,12 +1,13 @@
# Ridiculously simple test of the winsound module for Windows. # Ridiculously simple test of the winsound module for Windows.
import functools import functools
import pathlib import os
import time import time
import unittest import unittest
from test import support from test import support
from test.support import import_helper from test.support import import_helper
from test.support import os_helper
support.requires('audio') support.requires('audio')
@ -85,13 +86,6 @@ class MessageBeepTest(unittest.TestCase):
safe_MessageBeep(type=winsound.MB_OK) 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): class PlaySoundTest(unittest.TestCase):
def test_errors(self): def test_errors(self):
@ -126,7 +120,7 @@ class PlaySoundTest(unittest.TestCase):
def test_snd_filepath(self): def test_snd_filepath(self):
fn = support.findfile('pluck-pcm8.wav', subdir='audiodata') 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) safe_PlaySound(path, winsound.SND_FILENAME | winsound.SND_NODEFAULT)
def test_snd_filepath_as_bytes(self): def test_snd_filepath_as_bytes(self):
@ -134,7 +128,7 @@ class PlaySoundTest(unittest.TestCase):
self.assertRaises( self.assertRaises(
TypeError, TypeError,
winsound.PlaySound, winsound.PlaySound,
BytesPath(fn), os_helper.FakePath(os.fsencode(fn)),
winsound.SND_FILENAME | winsound.SND_NODEFAULT winsound.SND_FILENAME | winsound.SND_NODEFAULT
) )

View File

@ -265,14 +265,15 @@ class ZipAppTest(unittest.TestCase):
zipapp.create_archive(str(target), new_target, interpreter='python2.7') zipapp.create_archive(str(target), new_target, interpreter='python2.7')
self.assertTrue(new_target.getvalue().startswith(b'#!python2.7\n')) self.assertTrue(new_target.getvalue().startswith(b'#!python2.7\n'))
def test_read_from_pathobj(self): def test_read_from_pathlike_obj(self):
# Test that we can copy an archive using a pathlib.Path object # Test that we can copy an archive using a path-like object
# for the source. # for the source.
source = self.tmpdir / 'source' source = self.tmpdir / 'source'
source.mkdir() source.mkdir()
(source / '__main__.py').touch() (source / '__main__.py').touch()
target1 = self.tmpdir / 'target1.pyz' source = os_helper.FakePath(str(source))
target2 = self.tmpdir / 'target2.pyz' 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(source, target1, interpreter='python')
zipapp.create_archive(target1, target2, interpreter='python2.7') zipapp.create_archive(target1, target2, interpreter='python2.7')
self.assertEqual(zipapp.get_interpreter(target2), 'python2.7') self.assertEqual(zipapp.get_interpreter(target2), 'python2.7')

View File

@ -13,7 +13,7 @@ from ._itertools import Counter
from ._test_params import parameterize, Invoked 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: class jaraco:
@ -264,13 +264,13 @@ class TestPath(unittest.TestCase):
zipfile.Path should be constructable from a path-like object zipfile.Path should be constructable from a path-like object
""" """
zipfile_ondisk = self.zipfile_ondisk(alpharep) zipfile_ondisk = self.zipfile_ondisk(alpharep)
pathlike = pathlib.Path(str(zipfile_ondisk)) pathlike = FakePath(str(zipfile_ondisk))
zipfile.Path(pathlike) zipfile.Path(pathlike)
@pass_alpharep @pass_alpharep
def test_traverse_pathlike(self, alpharep): def test_traverse_pathlike(self, alpharep):
root = zipfile.Path(alpharep) root = zipfile.Path(alpharep)
root / pathlib.Path("a") root / FakePath("a")
@pass_alpharep @pass_alpharep
def test_parent(self, alpharep): def test_parent(self, alpharep):
@ -539,12 +539,12 @@ class TestPath(unittest.TestCase):
['alpharep', 'path_type', 'subpath'], ['alpharep', 'path_type', 'subpath'],
itertools.product( itertools.product(
alpharep_generators, alpharep_generators,
[str, pathlib.Path], [str, FakePath],
['', 'b/'], ['', 'b/'],
), ),
) )
def test_pickle(self, alpharep, path_type, subpath): 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)) saved_1 = pickle.dumps(zipfile.Path(zipfile_ondisk, at=subpath))
restored_1 = pickle.loads(saved_1) restored_1 = pickle.loads(saved_1)