Commit 3a31f2de by martin-kokos Committed by GitHub

tests: stop using tmp_dir fixture in favor of pytest.tmp_path fixture (#7412)

parent 5a9da19f
......@@ -64,6 +64,12 @@ jobs:
if: ${{ matrix.os == 'Windows' }}
run: echo "$APPDATA\Python\Scripts" >> $GITHUB_PATH
- name: Enable long paths for git on Windows
if: ${{ matrix.os == 'Windows' }}
# Enable handling long path names (+260 char) on the Windows platform
# https://docs.microsoft.com/en-us/windows/win32/fileio/naming-a-file#maximum-path-length-limitation
run: git config --system core.longpaths true
- name: Configure poetry
run: poetry config virtualenvs.in-project true
......
......@@ -55,4 +55,4 @@ def pip_install(
try:
return environment.run_pip(*args)
except EnvCommandError as e:
raise PoetryException(f"Failed to install {path.as_posix()}") from e
raise PoetryException(f"Failed to install {path}") from e
......@@ -5,7 +5,6 @@ import os
import re
import shutil
import sys
import tempfile
from contextlib import suppress
from pathlib import Path
......@@ -28,7 +27,6 @@ from poetry.repositories import RepositoryPool
from poetry.utils.env import EnvManager
from poetry.utils.env import SystemEnv
from poetry.utils.env import VirtualEnv
from poetry.utils.helpers import remove_directory
from tests.helpers import MOCK_DEFAULT_GIT_REVISION
from tests.helpers import TestLocker
from tests.helpers import TestRepository
......@@ -169,8 +167,8 @@ def with_chained_null_keyring(mocker: MockerFixture) -> None:
@pytest.fixture
def config_cache_dir(tmp_dir: str) -> Path:
path = Path(tmp_dir) / ".cache" / "pypoetry"
def config_cache_dir(tmp_path: Path) -> Path:
path = tmp_path / ".cache" / "pypoetry"
path.mkdir(parents=True)
return path
......@@ -219,8 +217,10 @@ def config(
@pytest.fixture()
def config_dir(tmp_dir: str) -> Path:
return Path(tempfile.mkdtemp(prefix="poetry_config_", dir=tmp_dir))
def config_dir(tmp_path: Path) -> Path:
path = tmp_path / "config"
path.mkdir()
return path
@pytest.fixture(autouse=True)
......@@ -296,18 +296,8 @@ def fixture_dir(fixture_base: Path) -> FixtureDirGetter:
@pytest.fixture
def tmp_dir() -> Iterator[str]:
dir_ = tempfile.mkdtemp(prefix="poetry_")
path = Path(dir_)
yield path.resolve().as_posix()
remove_directory(path, force=True)
@pytest.fixture
def tmp_venv(tmp_dir: str) -> Iterator[VirtualEnv]:
venv_path = Path(tmp_dir) / "venv"
def tmp_venv(tmp_path: Path) -> Iterator[VirtualEnv]:
venv_path = tmp_path / "venv"
EnvManager.build_venv(venv_path)
......@@ -348,14 +338,14 @@ def repo(http: type[httpretty.httpretty]) -> TestRepository:
@pytest.fixture
def project_factory(
tmp_dir: str,
tmp_path: Path,
config: Config,
repo: TestRepository,
installed: Repository,
default_python: str,
load_required_fixtures: None,
) -> ProjectFactory:
workspace = Path(tmp_dir)
workspace = tmp_path
def _factory(
name: str | None = None,
......@@ -380,9 +370,7 @@ def project_factory(
project_dir.mkdir(parents=True, exist_ok=True)
if pyproject_content:
with project_dir.joinpath("pyproject.toml").open(
"w", encoding="utf-8"
) as f:
with (project_dir / "pyproject.toml").open("w", encoding="utf-8") as f:
f.write(pyproject_content)
else:
assert name is not None
......@@ -446,10 +434,10 @@ def set_simple_log_formatter() -> None:
@pytest.fixture
def fixture_copier(fixture_base: Path, tmp_dir: str) -> FixtureCopier:
def fixture_copier(fixture_base: Path, tmp_path: Path) -> FixtureCopier:
def _copy(relative_path: str, target: Path | None = None) -> Path:
path = fixture_base.joinpath(relative_path)
target = target or Path(tmp_dir, relative_path)
path = fixture_base / relative_path
target = target or (tmp_path / relative_path)
target.parent.mkdir(parents=True, exist_ok=True)
if target.exists():
......
......@@ -2,7 +2,6 @@ from __future__ import annotations
import os
from pathlib import Path
from typing import TYPE_CHECKING
import pytest
......@@ -12,6 +11,7 @@ from poetry.utils.env import EnvManager
if TYPE_CHECKING:
from collections.abc import Iterator
from pathlib import Path
from tests.helpers import PoetryTestApplication
......@@ -25,8 +25,8 @@ def venv_name(app: PoetryTestApplication) -> str:
@pytest.fixture
def venv_cache(tmp_dir: str) -> Path:
return Path(tmp_dir)
def venv_cache(tmp_path: Path) -> Path:
return tmp_path
@pytest.fixture(scope="module")
......@@ -49,7 +49,7 @@ def venvs_in_cache_dirs(
) -> list[str]:
directories = []
for version in python_versions:
directory = venv_cache.joinpath(f"{venv_name}-py{version}")
directory = venv_cache / f"{venv_name}-py{version}"
directory.mkdir(parents=True, exist_ok=True)
directories.append(directory.name)
return directories
......
......@@ -39,7 +39,7 @@ def test_none_activated(
):
mocker.patch("poetry.utils.env.EnvManager.get", return_value=env)
tester.execute()
expected = "\n".join(venvs_in_cache_dirs).strip()
expected = "\n".join(venvs_in_cache_dirs)
assert tester.io.fetch_output().strip() == expected
......@@ -50,9 +50,7 @@ def test_activated(
venv_activate_37: None,
):
tester.execute()
expected = (
"\n".join(venvs_in_cache_dirs).strip().replace("py3.7", "py3.7 (Activated)")
)
expected = "\n".join(venvs_in_cache_dirs).replace("py3.7", "py3.7 (Activated)")
assert tester.io.fetch_output().strip() == expected
......
from __future__ import annotations
from pathlib import Path
from typing import TYPE_CHECKING
from typing import Any
from typing import Callable
......@@ -17,6 +16,7 @@ from poetry.utils._compat import metadata
if TYPE_CHECKING:
from os import PathLike
from pathlib import Path
from cleo.io.io import IO
from cleo.testers.command_tester import CommandTester
......@@ -64,7 +64,7 @@ def plugin_package(plugin_package_requires_dist: list[str]) -> Package:
@pytest.fixture()
def plugin_distro(plugin_package: Package, tmp_dir: str) -> metadata.Distribution:
def plugin_distro(plugin_package: Package, tmp_path: Path) -> metadata.Distribution:
class MockDistribution(metadata.Distribution):
def read_text(self, filename: str) -> str | None:
if filename == "METADATA":
......@@ -81,7 +81,7 @@ def plugin_distro(plugin_package: Package, tmp_dir: str) -> metadata.Distributio
return None
def locate_file(self, path: PathLike[str]) -> PathLike[str]:
return Path(tmp_dir, path)
return tmp_path / path
return MockDistribution()
......
......@@ -155,18 +155,20 @@ def test_command_new(
package_path: str,
include_from: str | None,
tester: CommandTester,
tmp_dir: str,
tmp_path: Path,
):
path = Path(tmp_dir) / directory
options.append(path.as_posix())
path = tmp_path / directory
options.append(str(path))
tester.execute(" ".join(options))
verify_project_directory(path, package_name, package_path, include_from)
@pytest.mark.parametrize(("fmt",), [(None,), ("md",), ("rst",), ("adoc",), ("creole",)])
def test_command_new_with_readme(fmt: str | None, tester: CommandTester, tmp_dir: str):
def test_command_new_with_readme(
fmt: str | None, tester: CommandTester, tmp_path: Path
):
package = "package"
path = Path(tmp_dir) / package
path = tmp_path / package
options = [path.as_posix()]
if fmt:
......@@ -191,7 +193,7 @@ def test_respect_prefer_active_on_new(
config: Config,
mocker: MockerFixture,
tester: CommandTester,
tmp_dir: str,
tmp_path: Path,
):
from poetry.utils.env import GET_PYTHON_VERSION_ONELINER
......@@ -208,8 +210,8 @@ def test_respect_prefer_active_on_new(
config.config["virtualenvs"]["prefer-active-python"] = prefer_active
package = "package"
path = Path(tmp_dir) / package
options = [path.as_posix()]
path = tmp_path / package
options = [str(path)]
tester.execute(" ".join(options))
pyproject_file = path / "pyproject.toml"
......
......@@ -40,8 +40,8 @@ def installer() -> NoopInstaller:
@pytest.fixture
def env(tmp_dir: str) -> MockEnv:
path = Path(tmp_dir) / ".venv"
def env(tmp_path: Path) -> MockEnv:
path = tmp_path / ".venv"
path.mkdir(parents=True)
return MockEnv(path=path, is_venv=True)
......
......@@ -36,7 +36,9 @@ def demo_wheel() -> Path:
@pytest.fixture
def source_dir(tmp_path: Path) -> Path:
return Path(tmp_path.as_posix())
path = tmp_path / "source"
path.mkdir()
return path
@pytest.fixture
......
......@@ -91,8 +91,8 @@ class Chef(BaseChef):
@pytest.fixture
def env(tmp_dir: str) -> MockEnv:
path = Path(tmp_dir) / ".venv"
def env(tmp_path: Path) -> MockEnv:
path = tmp_path / ".venv"
path.mkdir(parents=True)
return MockEnv(path=path, is_venv=True)
......@@ -169,19 +169,16 @@ def mock_file_downloads(
@pytest.fixture
def copy_wheel(tmp_dir: Path, fixture_dir: FixtureDirGetter) -> Callable[[], Path]:
def copy_wheel(tmp_path: Path, fixture_dir: FixtureDirGetter) -> Callable[[], Path]:
def _copy_wheel() -> Path:
tmp_name = tempfile.mktemp()
Path(tmp_dir).joinpath(tmp_name).mkdir()
(tmp_path / tmp_name).mkdir()
shutil.copyfile(
(
fixture_dir("distributions") / "demo-0.1.2-py2.py3-none-any.whl"
).as_posix(),
(Path(tmp_dir) / tmp_name / "demo-0.1.2-py2.py3-none-any.whl").as_posix(),
fixture_dir("distributions") / "demo-0.1.2-py2.py3-none-any.whl",
tmp_path / tmp_name / "demo-0.1.2-py2.py3-none-any.whl",
)
return Path(tmp_dir) / tmp_name / "demo-0.1.2-py2.py3-none-any.whl"
return tmp_path / tmp_name / "demo-0.1.2-py2.py3-none-any.whl"
return _copy_wheel
......@@ -201,7 +198,7 @@ def test_execute_executes_a_batch_of_operations(
config: Config,
pool: RepositoryPool,
io: BufferedIO,
tmp_dir: str,
tmp_path: Path,
mock_file_downloads: None,
env: MockEnv,
copy_wheel: Callable[[], Path],
......@@ -209,7 +206,7 @@ def test_execute_executes_a_batch_of_operations(
):
wheel_install = mocker.patch.object(WheelInstaller, "install")
config.merge({"cache-dir": tmp_dir})
config.merge({"cache-dir": str(tmp_path)})
artifact_cache = ArtifactCache(cache_dir=config.artifacts_cache_directory)
prepare_spy = mocker.spy(Chef, "_prepare")
......@@ -312,13 +309,13 @@ def test_execute_prints_warning_for_yanked_package(
config: Config,
pool: RepositoryPool,
io: BufferedIO,
tmp_dir: str,
tmp_path: Path,
mock_file_downloads: None,
env: MockEnv,
operations: list[Operation],
has_warning: bool,
):
config.merge({"cache-dir": tmp_dir})
config.merge({"cache-dir": str(tmp_path)})
executor = Executor(env, pool, config, io)
......@@ -345,11 +342,11 @@ def test_execute_prints_warning_for_invalid_wheels(
config: Config,
pool: RepositoryPool,
io: BufferedIO,
tmp_dir: str,
tmp_path: Path,
mock_file_downloads: None,
env: MockEnv,
):
config.merge({"cache-dir": tmp_dir})
config.merge({"cache-dir": str(tmp_path)})
executor = Executor(env, pool, config, io)
......@@ -460,11 +457,11 @@ def test_execute_works_with_ansi_output(
config: Config,
pool: RepositoryPool,
io_decorated: BufferedIO,
tmp_dir: str,
tmp_path: Path,
mock_file_downloads: None,
env: MockEnv,
):
config.merge({"cache-dir": tmp_dir})
config.merge({"cache-dir": str(tmp_path)})
executor = Executor(env, pool, config, io_decorated)
......@@ -497,11 +494,11 @@ def test_execute_works_with_no_ansi_output(
config: Config,
pool: RepositoryPool,
io_not_decorated: BufferedIO,
tmp_dir: str,
tmp_path: Path,
mock_file_downloads: None,
env: MockEnv,
):
config.merge({"cache-dir": tmp_dir})
config.merge({"cache-dir": str(tmp_path)})
executor = Executor(env, pool, config, io_not_decorated)
......@@ -581,7 +578,7 @@ Package operations: 1 install, 0 updates, 0 removals
def test_executor_should_delete_incomplete_downloads(
config: Config,
io: BufferedIO,
tmp_dir: str,
tmp_path: Path,
mocker: MockerFixture,
pool: RepositoryPool,
mock_file_downloads: None,
......@@ -589,7 +586,7 @@ def test_executor_should_delete_incomplete_downloads(
fixture_dir: FixtureDirGetter,
):
fixture = fixture_dir("distributions") / "demo-0.1.0-py2.py3-none-any.whl"
destination_fixture = Path(tmp_dir) / "tomlkit-0.5.3-py2.py3-none-any.whl"
destination_fixture = tmp_path / "tomlkit-0.5.3-py2.py3-none-any.whl"
shutil.copyfile(str(fixture), str(destination_fixture))
mocker.patch(
"poetry.installation.executor.Executor._download_archive",
......@@ -601,10 +598,10 @@ def test_executor_should_delete_incomplete_downloads(
)
mocker.patch(
"poetry.installation.executor.ArtifactCache.get_cache_directory_for_link",
return_value=Path(tmp_dir),
return_value=tmp_path,
)
config.merge({"cache-dir": tmp_dir})
config.merge({"cache-dir": str(tmp_path)})
executor = Executor(env, pool, config, io)
......@@ -1177,7 +1174,7 @@ def test_executor_fallback_on_poetry_create_error_without_wheel_installer(
config: Config,
pool: RepositoryPool,
io: BufferedIO,
tmp_dir: str,
tmp_path: Path,
mock_file_downloads: None,
env: MockEnv,
fixture_dir: FixtureDirGetter,
......@@ -1193,7 +1190,7 @@ def test_executor_fallback_on_poetry_create_error_without_wheel_installer(
config.merge(
{
"cache-dir": tmp_dir,
"cache-dir": str(tmp_path),
"installer": {"modern-installation": False},
}
)
......@@ -1346,7 +1343,6 @@ def test_build_system_requires_not_available(
config: Config,
pool: RepositoryPool,
io: BufferedIO,
tmp_dir: str,
mock_file_downloads: None,
env: MockEnv,
fixture_dir: FixtureDirGetter,
......
......@@ -23,7 +23,7 @@ from poetry.vcs.git.backend import GitRefSpec
if TYPE_CHECKING:
from _pytest.tmpdir import TempdirFactory
from _pytest.tmpdir import TempPathFactory
from dulwich.client import FetchPackResult
from dulwich.client import GitClient
from pytest_mock import MockerFixture
......@@ -79,9 +79,9 @@ def source_directory_name(source_url: str) -> str:
@pytest.fixture(scope="module")
def local_repo(tmpdir_factory: TempdirFactory, source_directory_name: str) -> Repo:
def local_repo(tmp_path_factory: TempPathFactory, source_directory_name: str) -> Repo:
with Repo.init(
tmpdir_factory.mktemp("src") / source_directory_name, mkdir=True
tmp_path_factory.mktemp("src") / source_directory_name, mkdir=True
) as repo:
yield repo
......
......@@ -83,8 +83,8 @@ def env_manager(simple_poetry: Poetry) -> EnvManager:
@pytest.fixture
def tmp_venv(tmp_dir: str, env_manager: EnvManager) -> VirtualEnv:
venv_path = Path(tmp_dir) / "venv"
def tmp_venv(tmp_path: Path, env_manager: EnvManager) -> VirtualEnv:
venv_path = tmp_path / "venv"
env_manager.build_venv(venv_path)
......@@ -222,10 +222,10 @@ if __name__ == '__main__':
def test_builder_falls_back_on_setup_and_pip_for_packages_with_build_scripts(
mocker: MockerFixture, extended_poetry: Poetry, tmp_dir: str
mocker: MockerFixture, extended_poetry: Poetry, tmp_path: Path
) -> None:
pip_install = mocker.patch("poetry.masonry.builders.editable.pip_install")
env = MockEnv(path=Path(tmp_dir) / "foo")
env = MockEnv(path=tmp_path / "foo")
builder = EditableBuilder(extended_poetry, env, NullIO())
builder.build()
......@@ -235,10 +235,10 @@ def test_builder_falls_back_on_setup_and_pip_for_packages_with_build_scripts(
assert [] == env.executed
def test_builder_setup_generation_runs_with_pip_editable(tmp_dir: str) -> None:
def test_builder_setup_generation_runs_with_pip_editable(tmp_path: Path) -> None:
# create an isolated copy of the project
fixture = Path(__file__).parent.parent.parent / "fixtures" / "extended_project"
extended_project = Path(tmp_dir) / "extended_project"
extended_project = tmp_path / "extended_project"
shutil.copytree(fixture, extended_project)
assert extended_project.exists()
......
......@@ -47,7 +47,7 @@ class InvalidPlugin:
@pytest.fixture()
def poetry(tmp_dir: str, config: Config) -> Poetry:
def poetry(tmp_path: Path, config: Config) -> Poetry:
poetry = Poetry(
CWD / "pyproject.toml",
{},
......
......@@ -101,9 +101,9 @@ def test_load_successful(repository: InstalledRepository):
def test_load_successful_with_invalid_distribution(
caplog: LogCaptureFixture, mocker: MockerFixture, env: MockEnv, tmp_dir: str
caplog: LogCaptureFixture, mocker: MockerFixture, env: MockEnv, tmp_path: Path
) -> None:
invalid_dist_info = Path(tmp_dir) / "site-packages" / "invalid-0.1.0.dist-info"
invalid_dist_info = tmp_path / "site-packages" / "invalid-0.1.0.dist-info"
invalid_dist_info.mkdir(parents=True)
mocker.patch(
"poetry.utils._compat.metadata.Distribution.discover",
......
......@@ -12,12 +12,12 @@ if TYPE_CHECKING:
from pytest_mock import MockerFixture
def test_env_site_simple(tmp_dir: str, mocker: MockerFixture):
def test_env_site_simple(tmp_path: Path, mocker: MockerFixture):
# emulate permission error when creating directory
mocker.patch("pathlib.Path.mkdir", side_effect=OSError())
site_packages = SitePackages(Path("/non-existent"), fallbacks=[Path(tmp_dir)])
site_packages = SitePackages(Path("/non-existent"), fallbacks=[tmp_path])
candidates = site_packages.make_candidates(Path("hello.txt"), writable_only=True)
hello = Path(tmp_dir) / "hello.txt"
hello = tmp_path / "hello.txt"
assert len(candidates) == 1
assert candidates[0].as_posix() == hello.as_posix()
......@@ -30,12 +30,11 @@ def test_env_site_simple(tmp_dir: str, mocker: MockerFixture):
assert not (site_packages.path / "hello.txt").exists()
def test_env_site_select_first(tmp_dir: str):
path = Path(tmp_dir)
fallback = path / "fallback"
def test_env_site_select_first(tmp_path: Path):
fallback = tmp_path / "fallback"
fallback.mkdir(parents=True)
site_packages = SitePackages(path, fallbacks=[fallback])
site_packages = SitePackages(tmp_path, fallbacks=[fallback])
candidates = site_packages.make_candidates(Path("hello.txt"), writable_only=True)
assert len(candidates) == 2
......
......@@ -10,6 +10,8 @@ from poetry.utils.pip import pip_install
if TYPE_CHECKING:
from pathlib import Path
from pytest_mock import MockerFixture
from poetry.utils.env import VirtualEnv
......@@ -17,7 +19,7 @@ if TYPE_CHECKING:
def test_pip_install_successful(
tmp_dir: str, tmp_venv: VirtualEnv, fixture_dir: FixtureDirGetter
tmp_path: Path, tmp_venv: VirtualEnv, fixture_dir: FixtureDirGetter
):
file_path = fixture_dir("distributions/demo-0.1.0-py2.py3-none-any.whl")
result = pip_install(file_path, tmp_venv)
......@@ -26,7 +28,7 @@ def test_pip_install_successful(
def test_pip_install_with_keyboard_interrupt(
tmp_dir: str,
tmp_path: Path,
tmp_venv: VirtualEnv,
fixture_dir: FixtureDirGetter,
mocker: MockerFixture,
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment