Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit b1e5844

Browse files
committed
Issue #9815: assertRaises now tries to clear references to local variables in the exception's traceback.
2 parents a171979 + 9681022 commit b1e5844

3 files changed

Lines changed: 37 additions & 0 deletions

File tree

Lib/unittest/case.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
import warnings
1010
import collections
1111
import contextlib
12+
import traceback
1213

1314
from . import result
1415
from .util import (strclass, safe_repr, _count_diff_all_purpose,
@@ -178,6 +179,8 @@ def __exit__(self, exc_type, exc_value, tb):
178179
self.obj_name))
179180
else:
180181
self._raiseFailure("{} not raised".format(exc_name))
182+
else:
183+
traceback.clear_frames(tb)
181184
if not issubclass(exc_type, self.expected):
182185
# let unexpected exceptions pass through
183186
return False

Lib/unittest/test/test_assertions.py

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import datetime
22
import warnings
3+
import weakref
34
import unittest
45
from itertools import product
56

@@ -97,6 +98,36 @@ def _raise(e):
9798
else:
9899
self.fail("assertRaises() didn't let exception pass through")
99100

101+
def test_assertRaises_frames_survival(self):
102+
# Issue #9815: assertRaises should avoid keeping local variables
103+
# in a traceback alive.
104+
class A:
105+
pass
106+
wr = None
107+
108+
class Foo(unittest.TestCase):
109+
110+
def foo(self):
111+
nonlocal wr
112+
a = A()
113+
wr = weakref.ref(a)
114+
try:
115+
raise IOError
116+
except IOError:
117+
raise ValueError
118+
119+
def test_functional(self):
120+
self.assertRaises(ValueError, self.foo)
121+
122+
def test_with(self):
123+
with self.assertRaises(ValueError):
124+
self.foo()
125+
126+
Foo("test_functional").run()
127+
self.assertIsNone(wr())
128+
Foo("test_with").run()
129+
self.assertIsNone(wr())
130+
100131
def testAssertNotRegex(self):
101132
self.assertNotRegex('Ala ma kota', r'r+')
102133
try:

Misc/NEWS

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -60,6 +60,9 @@ Core and Builtins
6060
Library
6161
-------
6262

63+
- Issue #9815: assertRaises now tries to clear references to local variables
64+
in the exception's traceback.
65+
6366
- Issue #19940: ssl.cert_time_to_seconds() now interprets the given time
6467
string in the UTC timezone (as specified in RFC 5280), not the local
6568
timezone.

0 commit comments

Comments
 (0)