Skip to content

Commit 2d527a7

Browse files
authored
Mock importlib.metadata usage in PackageDAG.from_pkgs() tests (#327)
1 parent 200a36e commit 2d527a7

File tree

1 file changed

+16
-4
lines changed

1 file changed

+16
-4
lines changed

tests/_models/test_dag.py

+16-4
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,15 @@
11
from __future__ import annotations
22

3+
from importlib.metadata import PackageNotFoundError
34
from itertools import chain
45
from typing import TYPE_CHECKING, Any, Callable, Iterator
6+
from unittest.mock import Mock
57

68
import pytest
79

810
from pipdeptree._models import DistPackage, PackageDAG, ReqPackage, ReversedPackageDAG
911

1012
if TYPE_CHECKING:
11-
from unittest.mock import Mock
12-
1313
from tests.our_types import MockGraph
1414

1515

@@ -92,9 +92,16 @@ def sort_map_values(m: dict[str, Any]) -> dict[str, Any]:
9292
assert all(isinstance(v, ReqPackage) for v in chain.from_iterable(t2.values()))
9393

9494

95-
def test_package_dag_from_pkgs(mock_pkgs: Callable[[MockGraph], Iterator[Mock]]) -> None:
95+
def test_package_dag_from_pkgs(
96+
mock_pkgs: Callable[[MockGraph], Iterator[Mock]], monkeypatch: pytest.MonkeyPatch
97+
) -> None:
9698
# when pip's _vendor.packaging.requirements.Requirement's requires() gives a lowercased package name but the actual
9799
# package name in PyPI is mixed case, expect the mixed case version
100+
101+
# Since DistPackage.project_name will try to use importlib.metadata to grab the project name, let's avoid using
102+
# the environment and use the fallback project name (since we control it here anyways).
103+
monkeypatch.setattr("pipdeptree._models.package.metadata", Mock(side_effect=PackageNotFoundError()))
104+
98105
graph: dict[tuple[str, str], list[tuple[str, list[tuple[str, str]]]]] = {
99106
("examplePy", "1.2.3"): [("hellopy", [(">=", "2.0.0")])],
100107
("HelloPy", "2.2.0"): [],
@@ -106,8 +113,13 @@ def test_package_dag_from_pkgs(mock_pkgs: Callable[[MockGraph], Iterator[Mock]])
106113
assert c[0].project_name == "HelloPy"
107114

108115

109-
def test_package_dag_from_pkgs_uses_pep503normalize(mock_pkgs: Callable[[MockGraph], Iterator[Mock]]) -> None:
116+
def test_package_dag_from_pkgs_uses_pep503normalize(
117+
mock_pkgs: Callable[[MockGraph], Iterator[Mock]], monkeypatch: pytest.MonkeyPatch
118+
) -> None:
110119
# ensure that requirement gets matched with a dists even when it's key needs pep503 normalization to match
120+
121+
monkeypatch.setattr("pipdeptree._models.package.metadata", Mock(side_effect=PackageNotFoundError()))
122+
111123
graph: dict[tuple[str, str], list[tuple[str, list[tuple[str, str]]]]] = {
112124
("parent-package", "1.2.3"): [("flufl.lock", [(">=", "2.0.0")])],
113125
("flufl-lock", "2.2.0"): [],

0 commit comments

Comments
 (0)