mirror of
https://github.com/kevin1024/vcrpy.git
synced 2025-12-08 16:53:23 +00:00
Automatically decorate dynamically added methods with auto_decorate
This commit is contained in:
@@ -283,6 +283,8 @@ class TestVCRClass(VCR().test_case()):
|
|||||||
|
|
||||||
def no_decoration(self):
|
def no_decoration(self):
|
||||||
assert httplib.HTTPConnection == _HTTPConnection
|
assert httplib.HTTPConnection == _HTTPConnection
|
||||||
|
self.test_dynamically_added()
|
||||||
|
assert httplib.HTTPConnection == _HTTPConnection
|
||||||
|
|
||||||
def test_one(self):
|
def test_one(self):
|
||||||
with force_reset():
|
with force_reset():
|
||||||
@@ -293,3 +295,11 @@ class TestVCRClass(VCR().test_case()):
|
|||||||
|
|
||||||
def test_two(self):
|
def test_two(self):
|
||||||
assert httplib.HTTPConnection != _HTTPConnection
|
assert httplib.HTTPConnection != _HTTPConnection
|
||||||
|
|
||||||
|
|
||||||
|
def test_dynamically_added(self):
|
||||||
|
assert httplib.HTTPConnection != _HTTPConnection
|
||||||
|
|
||||||
|
|
||||||
|
TestVCRClass.test_dynamically_added = test_dynamically_added
|
||||||
|
del test_dynamically_added
|
||||||
|
|||||||
19
vcr/util.py
19
vcr/util.py
@@ -98,13 +98,24 @@ def auto_decorate(
|
|||||||
decorator,
|
decorator,
|
||||||
predicate=lambda name, value: isinstance(value, types.FunctionType)
|
predicate=lambda name, value: isinstance(value, types.FunctionType)
|
||||||
):
|
):
|
||||||
|
def maybe_decorate(attribute, value):
|
||||||
|
if predicate(attribute, value):
|
||||||
|
value = decorator(value)
|
||||||
|
return value
|
||||||
|
|
||||||
class DecorateAll(type):
|
class DecorateAll(type):
|
||||||
|
|
||||||
|
def __setattr__(cls, attribute, value):
|
||||||
|
return super(DecorateAll, cls).__setattr__(
|
||||||
|
attribute, maybe_decorate(attribute, value)
|
||||||
|
)
|
||||||
|
|
||||||
def __new__(cls, name, bases, attributes_dict):
|
def __new__(cls, name, bases, attributes_dict):
|
||||||
for attribute, value in attributes_dict.items():
|
new_attributes_dict = dict(
|
||||||
if predicate(attribute, value):
|
(attribute, maybe_decorate(attribute, value))
|
||||||
attributes_dict[attribute] = decorator(value)
|
for attribute, value in attributes_dict.items()
|
||||||
|
)
|
||||||
return super(DecorateAll, cls).__new__(
|
return super(DecorateAll, cls).__new__(
|
||||||
cls, name, bases, attributes_dict
|
cls, name, bases, new_attributes_dict
|
||||||
)
|
)
|
||||||
return DecorateAll
|
return DecorateAll
|
||||||
|
|||||||
Reference in New Issue
Block a user