From 3241fc31030cc2d9cc9870fb388fabcab541fbe5 Mon Sep 17 00:00:00 2001 From: Anton Lodder Date: Thu, 10 Jan 2019 14:13:17 -0500 Subject: [PATCH] Don't fail if hasattr fails when rewriting assertions When rewriting assertions, pytest makes a call to `__name__` on each object in a comparision. If one of the objects has reimplemented `__getattr__`, they could fail trying to fetch `__name__` with an error other than `AttributeError`, which is what `hasattr` catches. In this case, the stack trace for the failed `__getattr__` call will show up in the pytest output, even though it isn't related to the test failing. This change fixes that by catching exceptions that `hasattr` throws. --- src/_pytest/assertion/rewrite.py | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/src/_pytest/assertion/rewrite.py b/src/_pytest/assertion/rewrite.py index 1d2c27ed1..df8b9becb 100644 --- a/src/_pytest/assertion/rewrite.py +++ b/src/_pytest/assertion/rewrite.py @@ -525,7 +525,13 @@ def _format_assertmsg(obj): def _should_repr_global_name(obj): - return not hasattr(obj, "__name__") and not callable(obj) + if callable(obj): + return False + + try: + return not hasattr(obj, "__name__") + except Exception: + return True def _format_boolop(explanations, is_or):