Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Catch BaseException in safe_getattr #2707

Merged
merged 3 commits into from
Aug 31, 2017
Merged
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
7 changes: 5 additions & 2 deletions _pytest/compat.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
import py

import _pytest
from _pytest.outcomes import TEST_OUTCOME


try:
Expand Down Expand Up @@ -221,14 +222,16 @@ def getimfunc(func):


def safe_getattr(object, name, default):
""" Like getattr but return default upon any Exception.
""" Like getattr but return default upon any Exception or any OutcomeException.
Attribute access can potentially fail for 'evil' Python objects.
See issue #214.
It catches OutcomeException because of #2490 (issue #580), new outcomes are derived from BaseException
instead of Exception (for more details check #2707)
"""
try:
return getattr(object, name, default)
except Exception:
except TEST_OUTCOME:
return default


Expand Down
1 change: 1 addition & 0 deletions changelog/2707.bugfix
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Fixed edge-case during collection: attributes which raised ``pytest.fail`` when accessed would abort the entire collection.
27 changes: 26 additions & 1 deletion testing/test_compat.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@
import sys

import pytest
from _pytest.compat import is_generator, get_real_func
from _pytest.compat import is_generator, get_real_func, safe_getattr
from _pytest.outcomes import OutcomeException


def test_is_generator():
Expand Down Expand Up @@ -74,3 +75,27 @@ async def bar():
""")
result = testdir.runpytest()
result.stdout.fnmatch_lines(['*1 passed*'])


class ErrorsHelper(object):
@property
def raise_exception(self):
raise Exception('exception should be catched')

@property
def raise_fail(self):
pytest.fail('fail should be catched')


def test_helper_failures():
helper = ErrorsHelper()
with pytest.raises(Exception):
helper.raise_exception
with pytest.raises(OutcomeException):
helper.raise_fail


def test_safe_getattr():
helper = ErrorsHelper()
assert safe_getattr(helper, 'raise_exception', 'default') == 'default'
assert safe_getattr(helper, 'raise_fail', 'default') == 'default'