Fix the stubborn test about cyclic references left by pytest.raises
In Python 2, a context manager's __exit__() leaves sys.exc_info with the exception values even when it was supposed to suppress the exception, so we explicitly call sys.exc_clear() which removes the traceback and allow the object to be released. Also updated the test to not depend on the immediate destruction of the object but instead to ensure it is not being tracked as a cyclic reference. Fix #1965
This commit is contained in:
@@ -1,4 +1,6 @@
|
||||
import pytest
|
||||
import sys
|
||||
|
||||
|
||||
class TestRaises:
|
||||
def test_raises(self):
|
||||
@@ -98,10 +100,13 @@ class TestRaises:
|
||||
assert False, "Expected pytest.raises.Exception"
|
||||
|
||||
@pytest.mark.parametrize('method', ['function', 'with'])
|
||||
def test_raises_memoryleak(self, method):
|
||||
import weakref
|
||||
def test_raises_cyclic_reference(self, method):
|
||||
"""
|
||||
Ensure pytest.raises does not leave a reference cycle (#1965).
|
||||
"""
|
||||
import gc
|
||||
|
||||
class T:
|
||||
class T(object):
|
||||
def __call__(self):
|
||||
raise ValueError
|
||||
|
||||
@@ -112,5 +117,12 @@ class TestRaises:
|
||||
with pytest.raises(ValueError):
|
||||
t()
|
||||
|
||||
t = weakref.ref(t)
|
||||
assert t() is None
|
||||
# ensure both forms of pytest.raises don't leave exceptions in sys.exc_info()
|
||||
assert sys.exc_info() == (None, None, None)
|
||||
|
||||
del t
|
||||
|
||||
# ensure the t instance is not stuck in a cyclic reference
|
||||
for o in gc.get_objects():
|
||||
assert type(o) is not T
|
||||
|
||||
|
||||
Reference in New Issue
Block a user