Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions changelog/7587.trivial.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
The dependency on the ``more-itertools`` package has been removed.
7 changes: 3 additions & 4 deletions src/_pytest/fixtures.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import functools
import inspect
import itertools
import sys
import warnings
from collections import defaultdict
Expand Down Expand Up @@ -1305,10 +1304,10 @@ def getfixtureinfo(self, node, func, cls, funcargs=True):
else:
argnames = ()

usefixtures = itertools.chain.from_iterable(
mark.args for mark in node.iter_markers(name="usefixtures")
usefixtures = tuple(
arg for mark in node.iter_markers(name="usefixtures") for arg in mark.args
)
initialnames = tuple(usefixtures) + argnames
initialnames = usefixtures + argnames
fm = node.session._fixturemanager
initialnames, names_closure, arg2fixturedefs = fm.getfixtureclosure(
initialnames, node, ignore_args=self._get_direct_parametrize_args(node)
Expand Down
15 changes: 3 additions & 12 deletions src/_pytest/python_api.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,9 @@
import inspect
import math
import pprint
from collections.abc import Iterable
from collections.abc import Mapping
from collections.abc import Sized
from decimal import Decimal
from itertools import filterfalse
from numbers import Number
from types import TracebackType
from typing import Any
Expand All @@ -18,9 +16,8 @@
from typing import TypeVar
from typing import Union

from more_itertools.more import always_iterable

import _pytest._code
from .types import validate_tup_type
from _pytest.compat import overload
from _pytest.compat import STRING_TYPES
from _pytest.compat import TYPE_CHECKING
Expand All @@ -30,9 +27,6 @@
from typing import Type # noqa: F401 (used in type string)


BASE_TYPE = (type, STRING_TYPES)


def _non_numeric_type_error(value, at):
at_str = " at {}".format(at) if at else ""
return TypeError(
Expand Down Expand Up @@ -677,11 +671,8 @@ def raises( # noqa: F811
documentation for :ref:`the try statement <python:try>`.
"""
__tracebackhide__ = True
for exc in filterfalse(
inspect.isclass, always_iterable(expected_exception, BASE_TYPE)
):
msg = "exceptions must be derived from BaseException, not %s"
raise TypeError(msg % type(exc))

validate_tup_type(expected_exception, BaseException)

message = "DID NOT RAISE {}".format(expected_exception)

Expand Down
15 changes: 3 additions & 12 deletions src/_pytest/recwarn.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
from typing import Tuple
from typing import Union

from .types import validate_tup_type
from _pytest.compat import overload
from _pytest.compat import TYPE_CHECKING
from _pytest.fixtures import yield_fixture
Expand Down Expand Up @@ -214,20 +215,10 @@ def __init__(
) -> None:
super().__init__()

msg = "exceptions must be derived from Warning, not %s"
if expected_warning is None:
expected_warning_tup = None
elif isinstance(expected_warning, tuple):
for exc in expected_warning:
if not issubclass(exc, Warning):
raise TypeError(msg % type(exc))
expected_warning_tup = expected_warning
elif issubclass(expected_warning, Warning):
expected_warning_tup = (expected_warning,)
self.expected_warning = None
else:
raise TypeError(msg % type(expected_warning))

self.expected_warning = expected_warning_tup
self.expected_warning = validate_tup_type(expected_warning, Warning)
self.match_expr = match_expr

def __exit__(
Expand Down
14 changes: 9 additions & 5 deletions src/_pytest/terminal.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,6 @@
import attr
import pluggy
import py.path
from more_itertools import collapse
from wcwidth import wcswidth

import pytest
Expand Down Expand Up @@ -807,10 +806,15 @@ def pytest_sessionstart(self, session: Session) -> None:
)
self._write_report_lines_from_hooks(lines)

def _write_report_lines_from_hooks(self, lines):
lines.reverse()
for line in collapse(lines):
self.write_line(line)
def _write_report_lines_from_hooks(
self, lines: Sequence[Union[str, Sequence[str]]]
) -> None:
for line_or_lines in reversed(lines):
if isinstance(line_or_lines, str):
self.write_line(line_or_lines)
else:
for line in line_or_lines:
self.write_line(line)

@pytest.hookimpl(trylast=True)
def pytest_report_header(self, config: Config) -> List[str]:
Expand Down
34 changes: 34 additions & 0 deletions src/_pytest/types.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
from .compat import TYPE_CHECKING

if TYPE_CHECKING:
from typing import Tuple
from typing import TypeVar
from typing import Union

_T = TypeVar("_T", bound="type")


def collapse_tuples(obj) -> "Tuple":
def walk(node):
if isinstance(node, tuple):
for child in node:
yield from walk(child)
else:
yield node

return tuple(x for x in walk(obj))


def validate_tup_type(
type_or_types: "Union[_T, Tuple[_T, ...]]", base_type: "_T"
) -> "Tuple[_T, ...]":
types = collapse_tuples(type_or_types)
for exc in types:
if not isinstance(exc, type) or not issubclass(exc, base_type):
raise TypeError(
"exceptions must be derived from {}, not {}".format(
base_type.__name__,
exc.__name__ if isinstance(exc, type) else type(exc).__name__,
)
)
return types
30 changes: 27 additions & 3 deletions testing/python/raises.py
Original file line number Diff line number Diff line change
Expand Up @@ -126,9 +126,19 @@ def test_division(example_input, expectation):
result = testdir.runpytest()
result.stdout.fnmatch_lines(["*2 failed*"])

def test_noclass(self):
with pytest.raises(TypeError):
pytest.raises("wrong", lambda: None)
def test_noclass_iterable(self) -> None:
with pytest.raises(
TypeError,
match="^exceptions must be derived from BaseException, not str$",
):
pytest.raises("wrong", lambda: None) # type: ignore[call-overload]

def test_noclass_noniterable(self) -> None:
with pytest.raises(
TypeError,
match="^exceptions must be derived from BaseException, not int$",
):
pytest.raises(41, lambda: None) # type: ignore[call-overload]

def test_invalid_arguments_to_raises(self):
with pytest.raises(TypeError, match="unknown"):
Expand Down Expand Up @@ -283,3 +293,17 @@ def test_raises_context_manager_with_kwargs(self):
with pytest.raises(Exception, foo="bar"):
pass
assert "Unexpected keyword arguments" in str(excinfo.value)

def test_expected_exception_is_not_a_baseexception(self) -> None:
msg = "^exceptions must be derived from BaseException, not {}$"
with pytest.raises(TypeError, match=msg.format("str")):
pytest.raises("hello") # type: ignore[call-overload]

class NotAnException:
pass

with pytest.raises(TypeError, match=msg.format("NotAnException")):
pytest.raises(NotAnException) # type: ignore[type-var]

with pytest.raises(TypeError, match=msg.format("str")):
pytest.raises(("hello", NotAnException)) # type: ignore[arg-type]
22 changes: 14 additions & 8 deletions testing/test_recwarn.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
from typing import Optional

import pytest
from _pytest.recwarn import WarningsChecker
from _pytest.recwarn import WarningsRecorder


Expand Down Expand Up @@ -50,14 +51,19 @@ def test_warn_stacklevel(self) -> None:
warnings.warn("test", DeprecationWarning, 2)

def test_typechecking(self) -> None:
from _pytest.recwarn import WarningsChecker

with pytest.raises(TypeError):
WarningsChecker(5) # type: ignore
with pytest.raises(TypeError):
WarningsChecker(("hi", RuntimeWarning)) # type: ignore
with pytest.raises(TypeError):
WarningsChecker([DeprecationWarning, RuntimeWarning]) # type: ignore
msg = "exceptions must be derived from Warning, not {}"
with pytest.raises(TypeError, match=msg.format("int")):
WarningsChecker(5) # type: ignore[arg-type]
with pytest.raises(TypeError, match=msg.format("str")):
WarningsChecker(("hi", RuntimeWarning)) # type: ignore[arg-type]
with pytest.raises(TypeError, match=msg.format("list")):
WarningsChecker([DeprecationWarning, RuntimeWarning]) # type: ignore[arg-type]

def test_nested_tuples(self) -> None:
wc1 = WarningsChecker((DeprecationWarning, RuntimeWarning))
wc2 = WarningsChecker(((DeprecationWarning,), (RuntimeWarning,))) # type: ignore[arg-type]
assert wc1.expected_warning == (DeprecationWarning, RuntimeWarning)
assert wc1.expected_warning == wc2.expected_warning

def test_invalid_enter_exit(self) -> None:
# wrap this test in WarningsRecorder to ensure warning state gets reset
Expand Down