Created
November 5, 2022 09:28
-
-
Save netaneld122/8d52faf0d2271963b9523ca9fd63a4f3 to your computer and use it in GitHub Desktop.
Patch bounded method of pre-existing instance
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from unittest.mock import patch | |
from contextlib import contextmanager | |
class MyClass: | |
def print_args(self, *args): | |
print(f'original: {self=}, {args=}') | |
@contextmanager | |
def patch_bounded_method(obj, method_name, new_method): | |
def wrapper(*args, **kwargs): | |
return new_method(obj, *args, **kwargs) | |
with patch.object(obj, method_name, wrapper) as p: | |
yield p | |
def main(obj): | |
obj.print_args(1) | |
def mock_method(self, *args): | |
print(f'mock: {self=}, {args=}') | |
with patch_bounded_method(obj, 'print_args', mock_method): | |
obj.print_args(1) | |
if __name__ == '__main__': | |
pre_existing_instance = MyClass() | |
main(pre_existing_instance) | |
""" | |
original: self=<__main__.MyClass object at 0x00000243F389D630>, args=(1,) | |
mock: self=<__main__.MyClass object at 0x00000243F389D630>, args=(1,) | |
""" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment