models/package: have `version_spec` only exist in `ReqPackage` (#303)

This commit is contained in:
Kemal Zebari 2023-11-27 20:09:42 -08:00 committed by GitHub
parent d63f879c1e
commit ced8bd8c2f
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 38 additions and 6 deletions

View File

@ -39,10 +39,6 @@ class Package(ABC):
def as_dict(self) -> dict[str, str | None]:
raise NotImplementedError
@property
def version_spec(self) -> None | str:
return None
def render(
self,
parent: DistPackage | ReqPackage | None = None,

View File

@ -4,8 +4,10 @@ import json
from itertools import chain
from typing import TYPE_CHECKING, Any
from pipdeptree._models import ReqPackage
if TYPE_CHECKING:
from pipdeptree._models import DistPackage, PackageDAG, ReqPackage
from pipdeptree._models import DistPackage, PackageDAG
def render_json_tree(tree: PackageDAG) -> str:
@ -37,7 +39,7 @@ def render_json_tree(tree: PackageDAG) -> str:
d: dict[str, str | list[Any] | None] = node.as_dict() # type: ignore[assignment]
if parent:
d["required_version"] = node.version_spec if node.version_spec else "Any"
d["required_version"] = node.version_spec if isinstance(node, ReqPackage) and node.version_spec else "Any"
else:
d["required_version"] = d["installed_version"]

View File

@ -0,0 +1,34 @@
from __future__ import annotations
from typing import TYPE_CHECKING, Callable, Iterator
import pytest
from pipdeptree._models.dag import PackageDAG
from pipdeptree._render.json_tree import render_json_tree
if TYPE_CHECKING:
from unittest.mock import Mock
from tests.our_types import MockGraph
@pytest.mark.parametrize(
("version_spec_tuple", "expected_version_spec"),
[
pytest.param((), "Any"),
pytest.param((">=", "2.0.0"), ">=2.0.0"),
],
)
def test_json_tree_given_req_package_with_version_spec(
mock_pkgs: Callable[[MockGraph], Iterator[Mock]],
version_spec_tuple: tuple[str, str],
expected_version_spec: str,
) -> None:
graph: dict[tuple[str, str], list[tuple[str, list[tuple[str, str]]]]] = {
("a", "1.2.3"): [("b", [version_spec_tuple])],
("b", "2.2.0"): [],
}
package_dag = PackageDAG.from_pkgs(list(mock_pkgs(graph)))
json_tree_str = render_json_tree(package_dag)
assert json_tree_str.find(expected_version_spec) != -1