From 69a44f5f9df7499974aa17afc7638959ba6ca70a Mon Sep 17 00:00:00 2001 From: Bartosz Sokorski Date: Thu, 16 Jan 2025 14:30:32 +0100 Subject: [PATCH] Apply use-pathlib rules --- pyproject.toml | 2 + src/poetry/config/config.py | 2 +- src/poetry/inspection/info.py | 5 +- src/poetry/masonry/builders/editable.py | 2 +- src/poetry/packages/locker.py | 4 +- src/poetry/utils/env/env_manager.py | 8 +- src/poetry/utils/env/virtual_env.py | 2 +- src/poetry/utils/helpers.py | 9 +- tests/console/commands/env/helpers.py | 6 +- .../console/commands/self/test_add_plugins.py | 4 +- .../commands/self/test_remove_plugins.py | 2 +- .../commands/self/test_self_command.py | 4 +- tests/console/commands/test_config.py | 12 +-- tests/console/commands/test_init.py | 4 +- tests/installation/test_chef.py | 9 +- tests/installation/test_executor.py | 2 +- tests/installation/test_wheel_installer.py | 3 +- .../masonry/builders/test_editable_builder.py | 2 +- tests/packages/test_locker.py | 88 ++++++------------- tests/utils/env/test_env.py | 2 +- tests/utils/env/test_env_manager.py | 22 ++--- tests/utils/test_cache.py | 6 +- 22 files changed, 84 insertions(+), 116 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index e6037c56bb2..0db513cb155 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -105,6 +105,7 @@ extend-exclude = [ # External to the project's coding standards "tests/fixtures/git/*", "tests/fixtures/project_with_setup*/*", + "tests/fixtures/extended_with_no_setup/*" ] fix = true line-length = 88 @@ -119,6 +120,7 @@ extend-select = [ "N", # pep8-naming "PIE", # flake8-pie "PGH", # pygrep + "PTH", # flake8-use-pathlib "RUF", # ruff checks "SIM", # flake8-simplify "T20", # flake8-print diff --git a/src/poetry/config/config.py b/src/poetry/config/config.py index 22906db6a19..1302d98bb13 100644 --- a/src/poetry/config/config.py +++ b/src/poetry/config/config.py @@ -110,7 +110,7 @@ class Config: "virtualenvs": { "create": True, "in-project": None, - "path": os.path.join("{cache-dir}", "virtualenvs"), + "path": os.path.join("{cache-dir}", "virtualenvs"), # noqa: PTH118 "options": { "always-copy": False, "system-site-packages": False, diff --git a/src/poetry/inspection/info.py b/src/poetry/inspection/info.py index 23a64604aa4..7a075a754c9 100644 --- a/src/poetry/inspection/info.py +++ b/src/poetry/inspection/info.py @@ -353,9 +353,8 @@ def _find_dist_info(path: Path) -> Iterator[Path]: """ pattern = "**/*.*-info" # Sometimes pathlib will fail on recursive symbolic links, so we need to work - # around it and use the glob module instead. Note that this does not happen with - # pathlib2 so it's safe to use it for Python < 3.4. - directories = glob.iglob(path.joinpath(pattern).as_posix(), recursive=True) + # around it and use the glob module instead. This bug is fixed in Python 3.13. + directories = glob.iglob(path.joinpath(pattern).as_posix(), recursive=True) # noqa: PTH207 for d in directories: yield Path(d) diff --git a/src/poetry/masonry/builders/editable.py b/src/poetry/masonry/builders/editable.py index 6a077af7d77..0d2d5d138f9 100644 --- a/src/poetry/masonry/builders/editable.py +++ b/src/poetry/masonry/builders/editable.py @@ -102,7 +102,7 @@ def _setup_build(self) -> None: pip_install(self._path, self._env, upgrade=True, editable=True) finally: if not has_setup: - os.remove(setup) + setup.unlink() def _add_pth(self) -> list[Path]: paths = { diff --git a/src/poetry/packages/locker.py b/src/poetry/packages/locker.py index f87c490d70f..e9de0babe38 100644 --- a/src/poetry/packages/locker.py +++ b/src/poetry/packages/locker.py @@ -244,7 +244,7 @@ def _write_lock_data(self, data: TOMLDocument) -> None: # we do that part for ourselves here, which only takes about 10 ms. # get original line endings - with open(self.lock, encoding="utf-8", newline="") as f: + with self.lock.open(encoding="utf-8", newline="") as f: line = f.readline() linesep = "\r\n" if line.endswith("\r\n") else "\n" @@ -254,7 +254,7 @@ def _write_lock_data(self, data: TOMLDocument) -> None: content = content.replace("\r\n", "\n") elif linesep == "\r\n": content = re.sub(r"(? bool: def is_sane(self) -> bool: # A virtualenv is considered sane if "python" exists. - return os.path.exists(self.python) + return self.python.exists() def _run(self, cmd: list[str], **kwargs: Any) -> str: kwargs["env"] = self.get_temp_environ(environ=kwargs.get("env")) diff --git a/src/poetry/utils/helpers.py b/src/poetry/utils/helpers.py index c5facf140f6..7d934e18b81 100644 --- a/src/poetry/utils/helpers.py +++ b/src/poetry/utils/helpers.py @@ -91,11 +91,12 @@ def _on_rm_error( def _on_rm_error(func: Callable[[str], None], path: str, exc_info: Any) -> None: - if not os.path.exists(path): + path_p = Path(path) + if not path_p.exists(): return - os.chmod(path, stat.S_IWRITE) - func(path) + path_p.chmod(stat.S_IWRITE) + func(str(path_p)) def remove_directory(path: Path, force: bool = False) -> None: @@ -107,7 +108,7 @@ def remove_directory(path: Path, force: bool = False) -> None: Internally, all arguments are passed to `shutil.rmtree`. """ if path.is_symlink(): - return os.unlink(path) + return path.unlink() kwargs: dict[str, Any] = {} if force: diff --git a/tests/console/commands/env/helpers.py b/tests/console/commands/env/helpers.py index 4337281e83c..d93d0983d43 100644 --- a/tests/console/commands/env/helpers.py +++ b/tests/console/commands/env/helpers.py @@ -1,7 +1,5 @@ from __future__ import annotations -import os - from pathlib import Path from typing import TYPE_CHECKING from typing import Any @@ -38,8 +36,8 @@ def check_output(cmd: list[str], *args: Any, **kwargs: Any) -> str: return f"{version.major}.{version.minor}" if "import sys; print(sys.executable)" in python_cmd: - executable = cmd[0] - basename = os.path.basename(executable) + executable = Path(cmd[0]) + basename = executable.name return f"/usr/bin/{basename}" if "print(sys.base_prefix)" in python_cmd: diff --git a/tests/console/commands/self/test_add_plugins.py b/tests/console/commands/self/test_add_plugins.py index 7687a7b8785..cd4ae13a237 100644 --- a/tests/console/commands/self/test_add_plugins.py +++ b/tests/console/commands/self/test_add_plugins.py @@ -194,7 +194,7 @@ def test_add_existing_plugin_warns_about_no_operation( installed: TestRepository, ) -> None: pyproject = SelfCommand.get_default_system_pyproject_file() - with open(pyproject, "w", encoding="utf-8", newline="") as f: + with pyproject.open("w", encoding="utf-8", newline="") as f: f.write( f"""\ [tool.poetry] @@ -236,7 +236,7 @@ def test_add_existing_plugin_updates_if_requested( installed: TestRepository, ) -> None: pyproject = SelfCommand.get_default_system_pyproject_file() - with open(pyproject, "w", encoding="utf-8", newline="") as f: + with pyproject.open("w", encoding="utf-8", newline="") as f: f.write( f"""\ [tool.poetry] diff --git a/tests/console/commands/self/test_remove_plugins.py b/tests/console/commands/self/test_remove_plugins.py index 6e525e78906..6a102f95683 100644 --- a/tests/console/commands/self/test_remove_plugins.py +++ b/tests/console/commands/self/test_remove_plugins.py @@ -37,7 +37,7 @@ def install_plugin(installed: Repository) -> None: ) content = Factory.create_pyproject_from_package(package) system_pyproject_file = SelfCommand.get_default_system_pyproject_file() - with open(system_pyproject_file, "w", encoding="utf-8", newline="") as f: + with system_pyproject_file.open("w", encoding="utf-8", newline="") as f: f.write(content.as_string()) lock_content = { diff --git a/tests/console/commands/self/test_self_command.py b/tests/console/commands/self/test_self_command.py index e38cee61873..c7cc65f8eb4 100644 --- a/tests/console/commands/self/test_self_command.py +++ b/tests/console/commands/self/test_self_command.py @@ -45,8 +45,8 @@ def test_generate_system_pyproject_carriage_returns( cmd.system_pyproject.write_text(example_system_pyproject + "\n", encoding="utf-8") cmd.generate_system_pyproject() - with open( - cmd.system_pyproject, newline="", encoding="utf-8" + with cmd.system_pyproject.open( + newline="", encoding="utf-8" ) as f: # do not translate newlines generated = f.read() diff --git a/tests/console/commands/test_config.py b/tests/console/commands/test_config.py index a6585c29145..fd07bdbb1d0 100644 --- a/tests/console/commands/test_config.py +++ b/tests/console/commands/test_config.py @@ -53,7 +53,7 @@ def test_list_displays_default_value_if_not_set( tester.execute("--list") cache_dir = json.dumps(str(config_cache_dir)) - venv_path = json.dumps(os.path.join("{cache-dir}", "virtualenvs")) + venv_path = json.dumps(os.path.join("{cache-dir}", "virtualenvs")) # noqa: PTH118 expected = f"""cache-dir = {cache_dir} installer.max-workers = null installer.no-binary = null @@ -85,7 +85,7 @@ def test_list_displays_set_get_setting( tester.execute("--list") cache_dir = json.dumps(str(config_cache_dir)) - venv_path = json.dumps(os.path.join("{cache-dir}", "virtualenvs")) + venv_path = json.dumps(os.path.join("{cache-dir}", "virtualenvs")) # noqa: PTH118 expected = f"""cache-dir = {cache_dir} installer.max-workers = null installer.no-binary = null @@ -138,7 +138,7 @@ def test_unset_setting( tester.execute("virtualenvs.path --unset") tester.execute("--list") cache_dir = json.dumps(str(config_cache_dir)) - venv_path = json.dumps(os.path.join("{cache-dir}", "virtualenvs")) + venv_path = json.dumps(os.path.join("{cache-dir}", "virtualenvs")) # noqa: PTH118 expected = f"""cache-dir = {cache_dir} installer.max-workers = null installer.no-binary = null @@ -169,7 +169,7 @@ def test_unset_repo_setting( tester.execute("repositories.foo.url --unset ") tester.execute("--list") cache_dir = json.dumps(str(config_cache_dir)) - venv_path = json.dumps(os.path.join("{cache-dir}", "virtualenvs")) + venv_path = json.dumps(os.path.join("{cache-dir}", "virtualenvs")) # noqa: PTH118 expected = f"""cache-dir = {cache_dir} installer.max-workers = null installer.no-binary = null @@ -298,7 +298,7 @@ def test_list_displays_set_get_local_setting( tester.execute("--list") cache_dir = json.dumps(str(config_cache_dir)) - venv_path = json.dumps(os.path.join("{cache-dir}", "virtualenvs")) + venv_path = json.dumps(os.path.join("{cache-dir}", "virtualenvs")) # noqa: PTH118 expected = f"""cache-dir = {cache_dir} installer.max-workers = null installer.no-binary = null @@ -337,7 +337,7 @@ def test_list_must_not_display_sources_from_pyproject_toml( tester.execute("--list") cache_dir = json.dumps(str(config_cache_dir)) - venv_path = json.dumps(os.path.join("{cache-dir}", "virtualenvs")) + venv_path = json.dumps(os.path.join("{cache-dir}", "virtualenvs")) # noqa: PTH118 expected = f"""cache-dir = {cache_dir} installer.max-workers = null installer.no-binary = null diff --git a/tests/console/commands/test_init.py b/tests/console/commands/test_init.py index 68f3e39faa3..7a98e7c43dd 100644 --- a/tests/console/commands/test_init.py +++ b/tests/console/commands/test_init.py @@ -936,10 +936,10 @@ def test_init_existing_pyproject_consistent_linesep( [tool.black] line-length = 88 """.replace("\n", linesep) - with open(pyproject_file, "w", newline="", encoding="utf-8") as f: + with pyproject_file.open("w", newline="", encoding="utf-8") as f: f.write(existing_section) tester.execute(inputs=init_basic_inputs) - with open(pyproject_file, newline="", encoding="utf-8") as f: + with pyproject_file.open(newline="", encoding="utf-8") as f: content = f.read() init_basic_toml = init_basic_toml.replace("\n", linesep) assert f"{existing_section}{linesep}{init_basic_toml}" in content diff --git a/tests/installation/test_chef.py b/tests/installation/test_chef.py index 9a659bc0a2a..7d9207bcb70 100644 --- a/tests/installation/test_chef.py +++ b/tests/installation/test_chef.py @@ -1,6 +1,5 @@ from __future__ import annotations -import os import shutil import tempfile @@ -77,7 +76,7 @@ def test_prepare_directory( assert wheel.parent.parent == Path(tempfile.gettempdir()) # cleanup generated tmp dir artifact - os.unlink(wheel) + wheel.unlink() def test_prepare_directory_with_extensions( @@ -99,7 +98,7 @@ def test_prepare_directory_with_extensions( assert wheel.name == f"extended-0.1-{env.supported_tags[0]}.whl" # cleanup generated tmp dir artifact - os.unlink(wheel) + wheel.unlink() def test_prepare_directory_editable( @@ -122,7 +121,7 @@ def test_prepare_directory_editable( assert "simple_project.pth" in z.namelist() # cleanup generated tmp dir artifact - os.unlink(wheel) + wheel.unlink() def test_prepare_directory_script( @@ -168,4 +167,4 @@ def __get__( assert wheel.parent.parent == Path(tempfile.gettempdir()) # cleanup generated tmp dir artifact - os.unlink(wheel) + wheel.unlink() diff --git a/tests/installation/test_executor.py b/tests/installation/test_executor.py index a7bff526612..4b947cef4d1 100644 --- a/tests/installation/test_executor.py +++ b/tests/installation/test_executor.py @@ -594,7 +594,7 @@ def verify_installed_distribution( record_file = distribution._path.joinpath( # type: ignore[attr-defined] "RECORD" ) - with open(record_file, encoding="utf-8", newline="") as f: + with record_file.open(encoding="utf-8", newline="") as f: reader = csv.reader(f) rows = list(reader) assert all(len(row) == 3 for row in rows) diff --git a/tests/installation/test_wheel_installer.py b/tests/installation/test_wheel_installer.py index 98e3f4cf97e..ef5abc6b32f 100644 --- a/tests/installation/test_wheel_installer.py +++ b/tests/installation/test_wheel_installer.py @@ -54,8 +54,7 @@ def test_default_installation_dist_info_dir_content(default_installation: Path) def test_installer_file_contains_valid_version(default_installation: Path) -> None: installer_file = default_installation / "demo-0.1.0.dist-info" / "INSTALLER" - with open(installer_file, encoding="utf-8") as f: - installer_content = f.read() + installer_content = installer_file.read_text(encoding="utf-8") match = re.match(r"Poetry (?P.*)", installer_content) assert match parse_constraint(match.group("version")) # must not raise an error diff --git a/tests/masonry/builders/test_editable_builder.py b/tests/masonry/builders/test_editable_builder.py index 29221576eaa..8f984d49e60 100644 --- a/tests/masonry/builders/test_editable_builder.py +++ b/tests/masonry/builders/test_editable_builder.py @@ -194,7 +194,7 @@ def test_builder_installs_proper_files_for_standard_packages( """ assert metadata == dist_info.joinpath("METADATA").read_text(encoding="utf-8") - with open(dist_info.joinpath("RECORD"), encoding="utf-8", newline="") as f: + with dist_info.joinpath("RECORD").open(encoding="utf-8", newline="") as f: reader = csv.reader(f) records = list(reader) diff --git a/tests/packages/test_locker.py b/tests/packages/test_locker.py index d5ef0764330..efe05d422d9 100644 --- a/tests/packages/test_locker.py +++ b/tests/packages/test_locker.py @@ -82,11 +82,9 @@ def test_is_locked_group_and_markers( ) -> None: if lock_version: locker.set_lock_data(root, {}) - with locker.lock.open("r", encoding="utf-8") as f: - content = f.read() + content = locker.lock.read_text(encoding="utf-8") content = content.replace(locker._VERSION, lock_version) - with locker.lock.open("w", encoding="utf-8") as f: - f.write(content) + locker.lock.write_text(content, encoding="utf-8") assert locker.is_locked_groups_and_markers() is (lock_version == "2.1") @@ -139,8 +137,7 @@ def test_lock_file_data_is_ordered( locker.set_lock_data(root, packages) - with locker.lock.open(encoding="utf-8") as f: - content = f.read() + content = locker.lock.read_text(encoding="utf-8") expected = f"""\ # {GENERATED_COMMENT} @@ -279,8 +276,7 @@ def test_locker_properly_loads_extras(locker: Locker) -> None: content-hash = "c3d07fca33fba542ef2b2a4d75bf5b48d892d21a830e2ad9c952ba5123a52f77" """ - with open(locker.lock, "w", encoding="utf-8") as f: - f.write(content) + locker.lock.write_text(content, encoding="utf-8") packages = locker.locked_repository().packages @@ -343,8 +339,7 @@ def test_locker_properly_loads_nested_extras(locker: Locker) -> None: content-hash = "123456789" """ - with open(locker.lock, "w", encoding="utf-8") as f: - f.write(content) + locker.lock.write_text(content, encoding="utf-8") repository = locker.locked_repository() assert len(repository.packages) == 3 @@ -409,8 +404,7 @@ def test_locker_properly_loads_extras_legacy(locker: Locker) -> None: content-hash = "123456789" """ - with open(locker.lock, "w", encoding="utf-8") as f: - f.write(content) + locker.lock.write_text(content, encoding="utf-8") repository = locker.locked_repository() assert len(repository.packages) == 2 @@ -450,8 +444,7 @@ def test_locker_properly_loads_subdir(locker: Locker) -> None: python-versions = "*" content-hash = "115cf985d932e9bf5f540555bbdd75decbb62cac81e399375fc19f6277f8c1d8" """ - with open(locker.lock, "w", encoding="utf-8") as f: - f.write(content) + locker.lock.write_text(content, encoding="utf-8") repository = locker.locked_repository() assert len(repository.packages) == 1 @@ -510,8 +503,7 @@ def test_locker_properly_loads_groups_and_markers( python-versions = "*" content-hash = "115cf985d932e9bf5f540555bbdd75decbb62cac81e399375fc19f6277f8c1d8" """ - with open(locker.lock, "w", encoding="utf-8") as f: - f.write(content) + locker.lock.write_text(content, encoding="utf-8") packages = locker.locked_packages() @@ -605,8 +597,7 @@ def test_locker_properly_assigns_metadata_files(locker: Locker) -> None: {file = "demo-1.0-py3-none-any.whl", hash = "sha256"}, ] """ - with open(locker.lock, "w", encoding="utf-8") as f: - f.write(content) + locker.lock.write_text(content, encoding="utf-8") repository = locker.locked_repository() assert len(repository.packages) == 5 @@ -644,9 +635,7 @@ def test_lock_packages_with_null_description( locker.set_lock_data(root, {package_a: transitive_info}) - with locker.lock.open(encoding="utf-8") as f: - content = f.read() - + content = locker.lock.read_text(encoding="utf-8") expected = f"""\ # {GENERATED_COMMENT} @@ -708,8 +697,7 @@ def test_lock_file_should_not_have_mixed_types( content-hash = "115cf985d932e9bf5f540555bbdd75decbb62cac81e399375fc19f6277f8c1d8" """ - with locker.lock.open(encoding="utf-8") as f: - content = f.read() + content = locker.lock.read_text(encoding="utf-8") assert content == expected @@ -740,8 +728,7 @@ def test_reading_lock_file_should_raise_an_error_on_invalid_data( python-versions = "*" content-hash = "115cf985d932e9bf5f540555bbdd75decbb62cac81e399375fc19f6277f8c1d8" """ - with locker.lock.open("w", encoding="utf-8") as f: - f.write(content) + locker.lock.write_text(content, encoding="utf-8") with pytest.raises(RuntimeError) as e: _ = locker.lock_data @@ -769,8 +756,7 @@ def test_reading_lock_file_should_raise_an_error_on_missing_metadata( url = "https://foo.bar" reference = "legacy" """ - with locker.lock.open("w", encoding="utf-8") as f: - f.write(content) + locker.lock.write_text(content, encoding="utf-8") with pytest.raises(RuntimeError) as e: _ = locker.lock_data @@ -795,8 +781,7 @@ def test_locking_legacy_repository_package_should_include_source_section( locker.set_lock_data(root, packages) - with locker.lock.open(encoding="utf-8") as f: - content = f.read() + content = locker.lock.read_text(encoding="utf-8") expected = f"""\ # {GENERATED_COMMENT} @@ -836,8 +821,7 @@ def test_locker_should_emit_warnings_if_lock_version_is_newer_but_allowed( """ caplog.set_level(logging.WARNING, logger="poetry.packages.locker") - with open(locker.lock, "w", encoding="utf-8") as f: - f.write(content) + locker.lock.write_text(content, encoding="utf-8") _ = locker.lock_data @@ -867,8 +851,7 @@ def test_locker_should_raise_an_error_if_lock_version_is_newer_and_not_allowed( """ caplog.set_level(logging.WARNING, logger="poetry.packages.locker") - with open(locker.lock, "w", encoding="utf-8") as f: - f.write(content) + locker.lock.write_text(content, encoding="utf-8") with pytest.raises(RuntimeError, match="^The lock file is not compatible"): _ = locker.lock_data @@ -885,8 +868,7 @@ def test_locker_should_raise_an_error_if_no_lock_version( """ caplog.set_level(logging.WARNING, logger="poetry.packages.locker") - with open(locker.lock, "w", encoding="utf-8") as f: - f.write(content) + locker.lock.write_text(content, encoding="utf-8") with pytest.raises(RuntimeError, match="^The lock file is not compatible"): _ = locker.lock_data @@ -921,8 +903,7 @@ def test_root_extras_dependencies_are_ordered( content-hash = "115cf985d932e9bf5f540555bbdd75decbb62cac81e399375fc19f6277f8c1d8" """ - with locker.lock.open(encoding="utf-8") as f: - content = f.read() + content = locker.lock.read_text(encoding="utf-8") assert content == expected @@ -961,8 +942,7 @@ def test_extras_dependencies_are_ordered( content-hash = "115cf985d932e9bf5f540555bbdd75decbb62cac81e399375fc19f6277f8c1d8" """ - with locker.lock.open(encoding="utf-8") as f: - content = f.read() + content = locker.lock.read_text(encoding="utf-8") assert content == expected @@ -981,8 +961,7 @@ def test_locker_should_neither_emit_warnings_nor_raise_error_for_lower_compatibl """ caplog.set_level(logging.WARNING, logger="poetry.packages.locker") - with open(locker.lock, "w", encoding="utf-8") as f: - f.write(content) + locker.lock.write_text(content, encoding="utf-8") _ = locker.lock_data @@ -1033,8 +1012,7 @@ def test_locker_dumps_groups_and_markers( locker.set_lock_data(root, packages) - with locker.lock.open(encoding="utf-8") as f: - content = f.read() + content = locker.lock.read_text(encoding="utf-8") expected = f"""\ # {GENERATED_COMMENT} @@ -1164,8 +1142,7 @@ def test_locker_dumps_dependency_information_correctly( locker.set_lock_data(root, packages) - with locker.lock.open(encoding="utf-8") as f: - content = f.read() + content = locker.lock.read_text(encoding="utf-8") expected = f"""\ # {GENERATED_COMMENT} @@ -1213,8 +1190,7 @@ def test_locker_dumps_subdir( locker.set_lock_data(root, {package_git_with_subdirectory: transitive_info}) - with locker.lock.open(encoding="utf-8") as f: - content = f.read() + content = locker.lock.read_text(encoding="utf-8") expected = f"""\ # {GENERATED_COMMENT} @@ -1265,8 +1241,7 @@ def test_locker_dumps_dependency_extras_in_correct_order( locker.set_lock_data(root, {package_a: transitive_info}) - with locker.lock.open(encoding="utf-8") as f: - content = f.read() + content = locker.lock.read_text(encoding="utf-8") expected = f"""\ # {GENERATED_COMMENT} @@ -1322,8 +1297,7 @@ def test_locked_repository_uses_root_dir_of_package( content-hash = "115cf985d932e9bf5f540555bbdd75decbb62cac81e399375fc19f6277f8c1d8" """ - with open(locker.lock, "w", encoding="utf-8") as f: - f.write(content) + locker.lock.write_text(content, encoding="utf-8") create_dependency_patch = mocker.patch( "poetry.factory.Factory.create_dependency", autospec=True @@ -1436,8 +1410,7 @@ def test_lock_file_resolves_file_url_symlinks( locker.set_lock_data(root, packages) - with locker.lock.open(encoding="utf-8") as f: - content = f.read() + content = locker.lock.read_text(encoding="utf-8") expected = f"""\ # {GENERATED_COMMENT} @@ -1488,13 +1461,11 @@ def test_lockfile_is_not_rewritten_if_only_poetry_version_changed( content-hash = "115cf985d932e9bf5f540555bbdd75decbb62cac81e399375fc19f6277f8c1d8" """ - with open(locker.lock, "w", encoding="utf-8") as f: - f.write(old_content) + locker.lock.write_text(old_content, encoding="utf-8") assert not locker.set_lock_data(root, {}) - with locker.lock.open(encoding="utf-8") as f: - content = f.read() + content = locker.lock.read_text(encoding="utf-8") assert content == old_content @@ -1504,8 +1475,7 @@ def test_lockfile_keep_eol( ) -> None: sep = "\n" if os.linesep == "\r\n" else "\r\n" - with open(locker.lock, "wb") as f: - f.write((sep * 10).encode()) + locker.lock.write_bytes((sep * 10).encode()) packages = {Package("test", version="0.0.1"): transitive_info} diff --git a/tests/utils/env/test_env.py b/tests/utils/env/test_env.py index 97eda471416..14c3eeec1ea 100644 --- a/tests/utils/env/test_env.py +++ b/tests/utils/env/test_env.py @@ -102,7 +102,7 @@ def test_env_get_supported_tags_matches_inside_virtualenv( @pytest.mark.skipif(os.name == "nt", reason="Symlinks are not support for Windows") def test_env_has_symlinks_on_nix(tmp_path: Path, tmp_venv: VirtualEnv) -> None: - assert os.path.islink(tmp_venv.python) + assert tmp_venv.python.is_symlink() def test_run_with_keyboard_interrupt( diff --git a/tests/utils/env/test_env_manager.py b/tests/utils/env/test_env_manager.py index 6b476b37456..6f3da59ee76 100644 --- a/tests/utils/env/test_env_manager.py +++ b/tests/utils/env/test_env_manager.py @@ -42,7 +42,9 @@ def build_venv(path: Path | str, **__: Any) -> None: - os.mkdir(str(path)) + if isinstance(path, str): + path = Path(path) + path.mkdir() def check_output_wrapper( @@ -64,8 +66,8 @@ def check_output(cmd: list[str], *args: Any, **kwargs: Any) -> str: return f"{version.major}.{version.minor}" if "import sys; print(sys.executable)" in python_cmd: - executable = cmd[0] - basename = os.path.basename(executable) + executable = Path(cmd[0]) + basename = executable.name return f"/usr/bin/{basename}" if "print(sys.base_prefix)" in python_cmd: @@ -210,7 +212,7 @@ def test_activate_fails_when_python_cannot_be_found( if "VIRTUAL_ENV" in os.environ: del os.environ["VIRTUAL_ENV"] - os.mkdir(tmp_path / f"{venv_name}-py3.7") + (tmp_path / f"{venv_name}-py3.7").mkdir() config.merge({"virtualenvs": {"path": str(tmp_path)}}) @@ -234,7 +236,7 @@ def test_activate_activates_existing_virtualenv_no_envs_file( if "VIRTUAL_ENV" in os.environ: del os.environ["VIRTUAL_ENV"] - os.mkdir(tmp_path / f"{venv_name}-py3.7") + (tmp_path / f"{venv_name}-py3.7").mkdir() config.merge({"virtualenvs": {"path": str(tmp_path)}}) @@ -275,7 +277,7 @@ def test_activate_activates_same_virtualenv_with_envs_file( doc[venv_name] = {"minor": "3.7", "patch": "3.7.1"} envs_file.write(doc) - os.mkdir(tmp_path / f"{venv_name}-py3.7") + (tmp_path / f"{venv_name}-py3.7").mkdir() config.merge({"virtualenvs": {"path": str(tmp_path)}}) @@ -316,7 +318,7 @@ def test_activate_activates_different_virtualenv_with_envs_file( doc[venv_name] = {"minor": "3.7", "patch": "3.7.1"} envs_file.write(doc) - os.mkdir(tmp_path / f"{venv_name}-py3.7") + (tmp_path / f"{venv_name}-py3.7").mkdir() config.merge({"virtualenvs": {"path": str(tmp_path)}}) @@ -362,7 +364,7 @@ def test_activate_activates_recreates_for_different_patch( doc[venv_name] = {"minor": "3.7", "patch": "3.7.0"} envs_file.write(doc) - os.mkdir(tmp_path / f"{venv_name}-py3.7") + (tmp_path / f"{venv_name}-py3.7").mkdir() config.merge({"virtualenvs": {"path": str(tmp_path)}}) @@ -414,8 +416,8 @@ def test_activate_does_not_recreate_when_switching_minor( doc[venv_name] = {"minor": "3.7", "patch": "3.7.0"} envs_file.write(doc) - os.mkdir(tmp_path / f"{venv_name}-py3.7") - os.mkdir(tmp_path / f"{venv_name}-py3.6") + (tmp_path / f"{venv_name}-py3.7").mkdir() + (tmp_path / f"{venv_name}-py3.6").mkdir() config.merge({"virtualenvs": {"path": str(tmp_path)}}) diff --git a/tests/utils/test_cache.py b/tests/utils/test_cache.py index 09c5c98e75c..60f96483d8d 100644 --- a/tests/utils/test_cache.py +++ b/tests/utils/test_cache.py @@ -168,11 +168,9 @@ def test_detect_corrupted_cache_key_file( # original content: 9999999999"value" if isinstance(corrupt_payload, str): - with open(key1_path, "w", encoding="utf-8") as f: - f.write(corrupt_payload) # write corrupt data + key1_path.write_text(corrupt_payload, encoding="utf-8") # write corrupt data else: - with open(key1_path, "wb") as f: - f.write(corrupt_payload) # write corrupt data + key1_path.write_bytes(corrupt_payload) # write corrupt data assert poetry_file_cache.get("key1") is None