From 531d76daa4a871df5b2a46cae132851c29abf027 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Sun, 31 Dec 2023 12:11:02 +0200 Subject: [PATCH] [7.4.x] Improve reporting from __iter__ exceptions (#11749) --- changelog/7966.bugfix.rst | 1 + src/_pytest/assertion/util.py | 2 +- testing/test_assertrewrite.py | 19 +++++++++++++++++++ 3 files changed, 21 insertions(+), 1 deletion(-) create mode 100644 changelog/7966.bugfix.rst diff --git a/changelog/7966.bugfix.rst b/changelog/7966.bugfix.rst new file mode 100644 index 0000000000..849bdb06e9 --- /dev/null +++ b/changelog/7966.bugfix.rst @@ -0,0 +1 @@ +Removed unhelpful error message from assertion rewrite mechanism when exceptions are raised in ``__iter__`` methods. Now they are treated un-iterable instead. diff --git a/src/_pytest/assertion/util.py b/src/_pytest/assertion/util.py index fc5dfdbd5b..39ca5403e0 100644 --- a/src/_pytest/assertion/util.py +++ b/src/_pytest/assertion/util.py @@ -132,7 +132,7 @@ def isiterable(obj: Any) -> bool: try: iter(obj) return not istext(obj) - except TypeError: + except Exception: return False diff --git a/testing/test_assertrewrite.py b/testing/test_assertrewrite.py index fbf2854953..f64d7733cd 100644 --- a/testing/test_assertrewrite.py +++ b/testing/test_assertrewrite.py @@ -686,6 +686,25 @@ def myany(x) -> bool: assert msg is not None assert " < 0" in msg + def test_assert_handling_raise_in__iter__(self, pytester: Pytester) -> None: + pytester.makepyfile( + """\ + class A: + def __iter__(self): + raise ValueError() + + def __eq__(self, o: object) -> bool: + return self is o + + def __repr__(self): + return "" + + assert A() == A() + """ + ) + result = pytester.runpytest() + result.stdout.fnmatch_lines(["*E*assert == "]) + def test_formatchar(self) -> None: def f() -> None: assert "%test" == "test" # type: ignore[comparison-overlap]