Best Python code snippet using localstack_python
patch.py
Source:patch.py
...17 if isinstance(cls, type):18 return cls19 # method is a module-level function20 return inspect.getmodule(method)21def create_patch_proxy(target: Callable, new: Callable):22 """23 Creates a proxy that calls `new` but passes as first argument the target.24 """25 @functools.wraps(target)26 def proxy(*args, **kwargs):27 return new(target, *args, **kwargs)28 return proxy29class Patch:30 obj: Any31 name: str32 new: Any33 def __init__(self, obj: Any, name: str, new: Any) -> None:34 super().__init__()35 self.obj = obj36 self.name = name37 self.old = getattr(self.obj, name)38 self.new = new39 self.is_applied = False40 def apply(self):41 setattr(self.obj, self.name, self.new)42 self.is_applied = True43 def undo(self):44 setattr(self.obj, self.name, self.old)45 self.is_applied = False46 def __enter__(self):47 self.apply()48 return self49 def __exit__(self, exc_type, exc_val, exc_tb):50 self.undo()51 return self52 @staticmethod53 def function(target: Callable, fn: Callable, pass_target: bool = True):54 obj = get_defining_object(target)55 name = target.__name__56 is_class_instance = not inspect.isclass(obj) and not inspect.ismodule(obj)57 if is_class_instance:58 # special case: If the defining object is not a class, but a class instance,59 # then we need to bind the patch function to the target object. Also, we need60 # to ensure that the final patched method has the same name as the original61 # method on the defining object (required for restoring objects with patched62 # methods from persistence, to avoid AttributeError).63 fn.__name__ = name64 fn = types.MethodType(fn, obj)65 if pass_target:66 new = create_patch_proxy(target, fn)67 else:68 new = fn69 return Patch(obj, name, new)70class Patches:71 patches: List[Patch]72 def __init__(self, patches: List[Patch] = None) -> None:73 super().__init__()74 self.patches = []75 if patches:76 self.patches.extend(patches)77 def apply(self):78 for p in self.patches:79 p.apply()80 def undo(self):...
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!