10000 add code to debug monkey patches applied through localstack.utils.patch by thrau · Pull Request #10957 · localstack/localstack · GitHub
[go: up one dir, main page]

Skip to content

add code to debug monkey patches applied through localstack.utils.patch #10957

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jun 5, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
50 changes: 50 additions & 0 deletions localstack-core/localstack/utils/patch.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,29 @@ def get_defining_object(method):
return inspect.getmodule(method)


def to_metadata_string(obj: Any) -> str:
"""
Creates a string that helps humans understand where the given object comes from. Examples::

to_metadata_string(func_thread.run) == "function(localstack.utils.threads:FuncThread.run)"

:param obj: a class, module, method, function or object
:return: a string representing the objects origin
"""
if inspect.isclass(obj):
return f"class({obj.__module__}:{obj.__name__})"
if inspect.ismodule(obj):
return f"module({obj.__name__})"
if inspect.ismethod(obj):
return f"method({obj.__module__}:{obj.__qualname__})"
if inspect.isfunction(obj):
# TODO: distinguish bound method
return f"function({obj.__module__}:{obj.__qualname__})"
if isinstance(obj, object):
return f"object({obj.__module__}:{obj.__class__.__name__})"
return str(obj)


def create_patch_proxy(target: Callable, new: Callable):
"""
Creates a proxy that calls `new` but passes as first argument the target.
Expand All @@ -37,6 +60,9 @@ def proxy(*args, **kwargs):
args = args[1:]
return new(target, *args, **kwargs)

# keep track of the real proxy subject (i.e., the new function that is used as patch)
proxy.__subject__ = new

_is_bound_method = inspect.ismethod(target)
if _is_bound_method:
proxy = types.MethodType(proxy, target.__self__)
Expand All @@ -45,6 +71,16 @@ def proxy(*args, **kwargs):


class Patch:
applied_patches: List["Patch"] = []
"""Bookkeeping for patches that are applied. You can use this to debug patches. For instance,
you could write something like::

for patch in Patch.applied_patches:
print(patch)

Which will output in a human readable format information about the currently active patches.
"""

obj: Any
name: str
new: Any
Expand All @@ -60,10 +96,12 @@ def __init__(self, obj: Any, name: str, new: Any) -> None:
def apply(self):
setattr(self.obj, self.name, self.new)
self.is_applied = True
Patch.applied_patches.append(self)

def undo(self):
setattr(self.obj, self.name, self.old)
self.is_applied = False
Patch.applied_patches.remove(self)

def __enter__(self):
self.apply()
Expand Down Expand Up @@ -95,6 +133,17 @@ def function(target: Callable, fn: Callable, pass_target: bool = True):

return Patch(obj, name, new)

def __str__(self):
try:
# try to unwrap the original underlying function that is used as patch (basically undoes what
# ``create_patch_proxy`` does)
new = self.new.__subject__
except AttributeError:
new = self.new

old = self.old
return f"Patch({to_metadata_string(old)} -> {to_metadata_string(new)}, applied={self.is_applied})"


class Patches:
patches: List[Patch]
Expand Down Expand Up @@ -166,6 +215,7 @@ def my_patch(self, *args):
:returns: the same function, but with a patch created
"""

@functools.wraps(target)
def wrapper(fn):
fn.patch = Patch.function(target, fn, pass_target=pass_target)
fn.patch.apply()
Expand Down
12 changes: 12 additions & 0 deletions tests/unit/utils/test_patch.py
Original file line number Diff line number Diff line change
Expand Up @@ -190,3 +190,15 @@ def test_get_defining_object():

# static method (= function defined by a class)
assert get_defining_object(MyEchoer.do_static_echo) == MyEchoer


def test_to_string():
@patch(MyEchoer.do_echo)
def monkey(self, *args):
return f"monkey: {args[-1]}"

applied = [str(p) for p in Patch.applied_patches]

value = "Patch(function(tests.unit.utils.test_patch:MyEchoer.do_echo) -> function(tests.unit.utils.test_patch:test_to_string.<locals>.monkey), applied=True)"
assert value in applied
assert str(monkey.patch) == value
Loading
0