summaryrefslogtreecommitdiffstats
path: root/Lib/test/support.py
diff options
context:
space:
mode:
authorAntoine Pitrou <solipsis@pitrou.net>2011-03-15 20:05:36 (GMT)
committerAntoine Pitrou <solipsis@pitrou.net>2011-03-15 20:05:36 (GMT)
commite870623e965ca017d32228486662b285d7b81ed0 (patch)
tree0bcd16d6a7af5bfda29fb93fb5857c834b4b1890 /Lib/test/support.py
parentcdc4f963cc6196d0b00985f6d5d980fab25c5a98 (diff)
parent2c50a09ac47e701768a4e20f8a03d17263e8db8f (diff)
downloadcpython-e870623e965ca017d32228486662b285d7b81ed0.zip
cpython-e870623e965ca017d32228486662b285d7b81ed0.tar.gz
cpython-e870623e965ca017d32228486662b285d7b81ed0.tar.bz2
Merge fix for issue #11501
Diffstat (limited to 'Lib/test/support.py')
-rw-r--r--Lib/test/support.py33
1 files changed, 33 insertions, 0 deletions
diff --git a/Lib/test/support.py b/Lib/test/support.py
index 7a43f97..8d8e187 100644
--- a/Lib/test/support.py
+++ b/Lib/test/support.py
@@ -1467,3 +1467,36 @@ def skip_unless_symlink(test):
ok = can_symlink()
msg = "Requires functional symlink implementation"
return test if ok else unittest.skip(msg)(test)
+
+def patch(test_instance, object_to_patch, attr_name, new_value):
+ """Override 'object_to_patch'.'attr_name' with 'new_value'.
+
+ Also, add a cleanup procedure to 'test_instance' to restore
+ 'object_to_patch' value for 'attr_name'.
+ The 'attr_name' should be a valid attribute for 'object_to_patch'.
+
+ """
+ # check that 'attr_name' is a real attribute for 'object_to_patch'
+ # will raise AttributeError if it does not exist
+ getattr(object_to_patch, attr_name)
+
+ # keep a copy of the old value
+ attr_is_local = False
+ try:
+ old_value = object_to_patch.__dict__[attr_name]
+ except (AttributeError, KeyError):
+ old_value = getattr(object_to_patch, attr_name, None)
+ else:
+ attr_is_local = True
+
+ # restore the value when the test is done
+ def cleanup():
+ if attr_is_local:
+ setattr(object_to_patch, attr_name, old_value)
+ else:
+ delattr(object_to_patch, attr_name)
+
+ test_instance.addCleanup(cleanup)
+
+ # actually override the attribute
+ setattr(object_to_patch, attr_name, new_value)