mirror of
https://github.com/python/cpython.git
synced 2025-10-04 22:20:46 +00:00
[3.6] bpo-30197: Enhance functions swap_attr() and swap_item() in test.support. (GH-1341) (#1345)
They now work when delete replaced attribute or item inside the with
statement. The old value of the attribute or item (or None if it doesn't
exist) now will be assigned to the target of the "as" clause, if there is
one.
(cherry picked from commit d1a1def7bf
)
This commit is contained in:
parent
e005dd9a6d
commit
712114b3f9
4 changed files with 46 additions and 13 deletions
|
@ -282,17 +282,34 @@ class TestSupport(unittest.TestCase):
|
|||
|
||||
def test_swap_attr(self):
|
||||
class Obj:
|
||||
x = 1
|
||||
pass
|
||||
obj = Obj()
|
||||
with support.swap_attr(obj, "x", 5):
|
||||
obj.x = 1
|
||||
with support.swap_attr(obj, "x", 5) as x:
|
||||
self.assertEqual(obj.x, 5)
|
||||
self.assertEqual(x, 1)
|
||||
self.assertEqual(obj.x, 1)
|
||||
with support.swap_attr(obj, "y", 5) as y:
|
||||
self.assertEqual(obj.y, 5)
|
||||
self.assertIsNone(y)
|
||||
self.assertFalse(hasattr(obj, 'y'))
|
||||
with support.swap_attr(obj, "y", 5):
|
||||
del obj.y
|
||||
self.assertFalse(hasattr(obj, 'y'))
|
||||
|
||||
def test_swap_item(self):
|
||||
D = {"item":1}
|
||||
with support.swap_item(D, "item", 5):
|
||||
self.assertEqual(D["item"], 5)
|
||||
self.assertEqual(D["item"], 1)
|
||||
D = {"x":1}
|
||||
with support.swap_item(D, "x", 5) as x:
|
||||
self.assertEqual(D["x"], 5)
|
||||
self.assertEqual(x, 1)
|
||||
self.assertEqual(D["x"], 1)
|
||||
with support.swap_item(D, "y", 5) as y:
|
||||
self.assertEqual(D["y"], 5)
|
||||
self.assertIsNone(y)
|
||||
self.assertNotIn("y", D)
|
||||
with support.swap_item(D, "y", 5):
|
||||
del D["y"]
|
||||
self.assertNotIn("y", D)
|
||||
|
||||
class RefClass:
|
||||
attribute1 = None
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue