Skip to content

Commit

Permalink
issue a warning when Items and Collector form a diamond
Browse files Browse the repository at this point in the history
addresses pytest-dev#8435
  • Loading branch information
RonnyPfannschmidt committed Jun 6, 2021
1 parent 8300b26 commit 9616059
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 0 deletions.
4 changes: 4 additions & 0 deletions changelog/8447.deprecation.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
Warn when inheritance is used to bring Collectors into Items,
it was never sanely supported and triggers hard to debug errors.

Instead of inheritance composition should be used.
14 changes: 14 additions & 0 deletions src/_pytest/nodes.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@
from _pytest.pathlib import absolutepath
from _pytest.pathlib import commonpath
from _pytest.store import Store
from _pytest.warning_types import PytestWarning

if TYPE_CHECKING:
# Imported here due to circular import.
Expand Down Expand Up @@ -610,6 +611,19 @@ class Item(Node):

nextitem = None

def __init_subclass__(cls):
problems = ", ".join(
base.__name__ for base in cls.__bases__ if issubclass(base, Collector)
)
if problems:
warnings.warn(
f"{cls.__name__} is a Item subclass and should not be a collector.\n"
f"however its bases {problems} are collectors\n"
"please split the collection and the items into 2 node types\n"
"TODO: doc link",
PytestWarning,
)

def __init__(
self,
name,
Expand Down
10 changes: 10 additions & 0 deletions testing/test_nodes.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,16 @@ def test_node_from_parent_disallowed_arguments() -> None:
nodes.Node.from_parent(None, config=None) # type: ignore[arg-type]


def test_subclassing_node_with_item_warns() -> None:

with pytest.warns(
PytestWarning, match="SoWrong is a Item subclass and should not be a collector"
):

class SoWrong(nodes.Item, nodes.File):
pass


@pytest.mark.parametrize(
"warn_type, msg", [(DeprecationWarning, "deprecated"), (PytestWarning, "pytest")]
)
Expand Down

0 comments on commit 9616059

Please sign in to comment.