Skip to content

Commit

Permalink
replace dangerous monkeypatch with mocker.patch
Browse files Browse the repository at this point in the history
  • Loading branch information
xiacunshun committed Apr 10, 2024
1 parent b5ba32f commit 18f832e
Show file tree
Hide file tree
Showing 4 changed files with 23 additions and 16 deletions.
4 changes: 2 additions & 2 deletions src/pipdeptree/_discovery.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,8 @@ def get_installed_distributions(
cmd = "import sys; print(sys.path)"

args = [str(py_path), "-c", cmd]
result = subprocess.run(args, stdout=subprocess.PIPE, check=False) # noqa: S603
original_dists = distributions(path=ast.literal_eval(result.stdout.decode("utf-8")))
result = subprocess.run(args, stdout=subprocess.PIPE, check=False, text=True) # noqa: S603
original_dists = distributions(path=ast.literal_eval(result.stdout))
elif local_only and in_venv:
venv_site_packages = [p for p in sys.path if p.startswith(sys.prefix)]
original_dists = distributions(path=venv_site_packages)
Expand Down
7 changes: 5 additions & 2 deletions tests/_models/test_package.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from __future__ import annotations

import sys
from importlib.metadata import PackageNotFoundError
from pathlib import Path
from typing import TYPE_CHECKING, Any
Expand All @@ -26,11 +27,13 @@ def test_guess_version_setuptools(mocker: MockerFixture) -> None:
assert result == "?"


def test_package_as_frozen_repr(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
def test_package_as_frozen_repr(tmp_path: Path, mocker: MockerFixture) -> None:
file_path = tmp_path / "foo.egg-link"
with Path(file_path).open("w") as f:
f.write("/A/B/foo")
monkeypatch.syspath_prepend(str(tmp_path))
mock_path = sys.path.copy()
mock_path.append(str(tmp_path))
mocker.patch("pipdeptree._discovery.sys.path", mock_path)
json_text = '{"dir_info": {"editable": true}}'
foo = Mock(metadata={"Name": "foo"}, version="20.4.1")
foo.read_text = Mock(return_value=json_text)
Expand Down
17 changes: 9 additions & 8 deletions tests/test_discovery.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
from pytest_mock import MockerFixture


def test_local_only(tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capfd: pytest.CaptureFixture[str]) -> None:
def test_local_only(tmp_path: Path, mocker: MockerFixture, capfd: pytest.CaptureFixture[str]) -> None:
venv_path = str(tmp_path / "venv")
result = virtualenv.cli_run([venv_path, "--activators", ""])
venv_site_packages = site.getsitepackages([venv_path])
Expand All @@ -27,10 +27,11 @@ def test_local_only(tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capfd: pyte
f.write("Metadata-Version: 2.3\n" "Name: foo\n" "Version: 1.2.5\n")

cmd = [str(result.creator.exe.parent / "python3"), "--local-only"]
monkeypatch.setattr(sys, "prefix", venv_path)
for s in venv_site_packages:
monkeypatch.syspath_prepend(s)
monkeypatch.setattr(sys, "argv", cmd)
mocker.patch("pipdeptree._discovery.sys.prefix", venv_path)
sys_path = sys.path.copy()
mock_path = sys_path + venv_site_packages
mocker.patch("pipdeptree._discovery.sys.path", mock_path)
mocker.patch("pipdeptree._discovery.sys.argv", cmd)
main()
out, _ = capfd.readouterr()
found = {i.split("==")[0] for i in out.splitlines()}
Expand All @@ -41,16 +42,16 @@ def test_local_only(tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capfd: pyte
assert found == expected


def test_user_only(tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capfd: pytest.CaptureFixture[str]) -> None:
def test_user_only(tmp_path: Path, mocker: MockerFixture, capfd: pytest.CaptureFixture[str]) -> None:
fake_dist = Path(tmp_path) / "foo-1.2.5.dist-info"
fake_dist.mkdir()
fake_metadata = Path(fake_dist) / "METADATA"
with Path(fake_metadata).open("w") as f:
f.write("Metadata-Version: 2.3\n" "Name: foo\n" "Version: 1.2.5\n")

monkeypatch.setattr(site, "getusersitepackages", Mock(return_value=str(tmp_path)))
cmd = [sys.executable, "--user-only"]
monkeypatch.setattr(sys, "argv", cmd)
mocker.patch("pipdeptree._discovery.site.getusersitepackages", Mock(return_value=str(tmp_path)))
mocker.patch("pipdeptree._discovery.sys.argv", cmd)
main()
out, _ = capfd.readouterr()
found = {i.split("==")[0] for i in out.splitlines()}
Expand Down
11 changes: 7 additions & 4 deletions tests/test_non_host.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,13 @@
if TYPE_CHECKING:
from pathlib import Path

from pytest_mock import MockerFixture


@pytest.mark.parametrize("args_joined", [True, False])
def test_custom_interpreter(
tmp_path: Path,
mocker: MockerFixture,
monkeypatch: pytest.MonkeyPatch,
capfd: pytest.CaptureFixture[str],
args_joined: bool,
Expand All @@ -25,7 +28,7 @@ def test_custom_interpreter(
monkeypatch.chdir(tmp_path)
py = str(result.creator.exe.relative_to(tmp_path))
cmd += [f"--python={result.creator.exe}"] if args_joined else ["--python", py]
monkeypatch.setattr(sys, "argv", cmd)
mocker.patch("pipdeptree._discovery.sys.argv", cmd)
main()
out, _ = capfd.readouterr()
found = {i.split("==")[0] for i in out.splitlines()}
Expand All @@ -43,16 +46,16 @@ def test_custom_interpreter(

def test_custom_interpreter_with_local_only(
tmp_path: Path,
monkeypatch: pytest.MonkeyPatch,
mocker: MockerFixture,
capfd: pytest.CaptureFixture[str],
) -> None:
venv_path = str(tmp_path / "venv")

result = virtualenv.cli_run([venv_path, "--system-site-packages", "--activators", ""])

cmd = ["", f"--python={result.creator.exe}", "--local-only"]
monkeypatch.setattr(sys, "prefix", venv_path)
monkeypatch.setattr(sys, "argv", cmd)
mocker.patch("pipdeptree._discovery.sys.prefix", venv_path)
mocker.patch("pipdeptree._discovery.sys.argv", cmd)
main()
out, _ = capfd.readouterr()
found = {i.split("==")[0] for i in out.splitlines()}
Expand Down

0 comments on commit 18f832e

Please sign in to comment.