Conghao97's picture tcftrees's picture
ProgramGen release
d086025
Raw History Blame Contribute Delete
44.3 kB
diff --git a/src/patchy/__init__.py b/src/patchy/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..9097f62d7d15020c243314bd6456525ba073c1ce --- /dev/null +++ b/src/patchy/__init__.py @@ -0,0 +1,3 @@ +from __future__ import annotations + +from .api import * # noqa diff --git a/src/patchy/api.py b/src/patchy/api.py new file mode 100644 index 0000000000000000000000000000000000000000..d807924f7867002b72bab5fbd3d54e0044839744 --- /dev/null +++ b/src/patchy/api.py @@ -0,0 +1,328 @@ +from __future__ import annotations + +import ast +import inspect +import os +import shutil +import subprocess +from collections.abc import Callable +from functools import wraps +from tempfile import mkdtemp +from textwrap import dedent +from types import CodeType, TracebackType +from typing import Any, TypeVar, cast +from weakref import WeakKeyDictionary + +from .cache import PatchingCache + +if True: + import __future__ + +from pkgutil import resolve_name as pkgutil_resolve_name + +__all__ = ("patch", "mc_patchface", "unpatch", "replace", "temp_patch") + + +# Public API + + +def patch(func: Callable[..., Any] | str, patch_text: str) -> None: + _do_patch(func, patch_text, forwards=True) + + +mc_patchface = patch + + +def unpatch(func: Callable[..., Any] | str, patch_text: str) -> None: + _do_patch(func, patch_text, forwards=False) + + +def replace( + func: Callable[..., Any], + expected_source: str | None, + new_source: str, +) -> None: + if expected_source is not None: + expected_source = dedent(expected_source) + current_source = _get_source(func) + _assert_ast_equal(current_source, expected_source, func.__name__) + + new_source = dedent(new_source) + _set_source(func, new_source) + + +AnyFunc = TypeVar("AnyFunc", bound=Callable[..., Any]) + + +class temp_patch: + def __init__(self, func: Callable[..., Any] | str, patch_text: str) -> None: + self.func = func + self.patch_text = patch_text + + def __enter__(self) -> None: + patch(self.func, self.patch_text) + + def __exit__( + self, + exc_type: type[BaseException] | None, + exc_val: BaseException | None, + exc_tb: TracebackType | None, + ) -> None: + unpatch(self.func, self.patch_text) + + def __call__(self, decorable: AnyFunc) -> AnyFunc: + @wraps(decorable) + def wrapper(*args: Any, **kwargs: Any) -> Any: + with self: + decorable(*args, **kwargs) + + return cast(AnyFunc, wrapper) + + +# Gritty internals + + +def _do_patch( + func: Callable[..., Any] | str, + patch_text: str, + forwards: bool, +) -> None: + if isinstance(func, str): + func = cast(Callable[..., Any], pkgutil_resolve_name(func)) + source = _get_source(func) + patch_text = dedent(patch_text) + + new_source = _apply_patch(source, patch_text, forwards, func.__name__) + + _set_source(func, new_source) + + +_patching_cache = PatchingCache(maxsize=100) + + +def _apply_patch( + source: str, + patch_text: str, + forwards: bool, + name: str, +) -> str: + # Cached ? + try: + return _patching_cache.retrieve(source, patch_text, forwards) + except KeyError: + pass + + # Write out files + tempdir = mkdtemp(prefix="patchy") + try: + source_path = os.path.join(tempdir, name + ".py") + with open(source_path, "w") as source_file: + source_file.write(source) + + patch_path = os.path.join(tempdir, name + ".patch") + with open(patch_path, "w") as patch_file: + patch_file.write(patch_text) + if not patch_text.endswith("\n"): + patch_file.write("\n") + + # Call `patch` command + command = ["patch", "--force"] + if not forwards: + command.append("--reverse") + command.extend([source_path, patch_path]) + result = subprocess.run(command, capture_output=True, text=True) + + if result.returncode != 0: + msg = "Could not {action} the patch {prep} '{name}'.".format( + action=("apply" if forwards else "unapply"), + prep=("to" if forwards else "from"), + name=name, + ) + msg += f" The message from `patch` was:\n{result.stdout}\n{result.stderr}" + msg += f"\nThe code to patch was:\n{source}\nThe patch was:\n{patch_text}" + raise ValueError(msg) + + with open(source_path) as source_file: + new_source = source_file.read() + finally: + shutil.rmtree(tempdir) + + _patching_cache.store(source, patch_text, forwards, new_source) + + return new_source + + +def _get_flags_mask() -> int: + result = 0 + for name in __future__.all_feature_names: + result |= getattr(__future__, name).compiler_flag + return result + + +FEATURE_MASK = _get_flags_mask() + + +# Stores the source of functions that have had their source changed +_source_map: WeakKeyDictionary[Callable[..., Any], str] = WeakKeyDictionary() + + +def _get_source(func: Callable[..., Any]) -> str: + real_func = _get_real_func(func) + try: + return _source_map[real_func] + except KeyError: + source = inspect.getsource(func) + source = dedent(source) + return source + + +def _class_name(func: Callable[..., Any]) -> str | None: + split_name = func.__qualname__.split(".") + try: + class_name = split_name[-2] + except IndexError: + return None + else: + if class_name == "<locals>": + return None + return class_name + + +def _set_source(func: Callable[..., Any], func_source: str) -> None: + # Fetch the actual function we are changing + real_func = _get_real_func(func) + # Figure out any future headers that may be required + feature_flags = real_func.__code__.co_flags & FEATURE_MASK + + class_name = _class_name(func) + + def _compile( + code: str | ast.Module, + flags: int = 0, + ) -> CodeType | ast.Module: + result: CodeType | ast.Module = compile( + code, "<patchy>", "exec", flags=feature_flags | flags, dont_inherit=True + ) + return result + + def _parse(code: str) -> ast.Module: + result = _compile(code, flags=ast.PyCF_ONLY_AST) + assert isinstance(result, ast.Module) + return result + + def _process_freevars() -> tuple[str, ast.AST, list[str]]: + """ + Wrap the new function in a __patchy_freevars__ method that provides all + freevars of the original function. + + Because the new function must use exectaly the same freevars as the + original, also append to the new function with a body of code to force + use of those freevars (in the case the the patch drops use of any + freevars): + + def __patchy_freevars__(): + eg_free_var_spam = object() <- added in wrapper + eg_free_var_ham = object() <- added in wrapper + + def patched_func(): + return some_global(eg_free_var_ham) + eg_free_var_spam <- appended to new func body + eg_free_var_ham <- appended to new func body + + return patched_func + """ + _def = "def __patchy_freevars__():" + fvs = func.__code__.co_freevars + fv_body = [f" {fv} = object()" for fv in fvs] + fv_force_use_body = [f" {fv}" for fv in fvs] + if fv_force_use_body: + fv_force_use_ast = _parse("\n".join([_def] + fv_force_use_body)) + fv_force_use = fv_force_use_ast.body[0].body # type: ignore [attr-defined] + else: + fv_force_use = [] + _ast = _parse(func_source).body[0] + _ast.body = _ast.body + fv_force_use # type: ignore [attr-defined] + return _def, _ast, fv_body + + def _process_method() -> ast.Module: + """ + Wrap the new method in a class to ensure the same mangling as would + have been performed on the original method: + + def __patchy_freevars__(): + + class SomeClass(object): + def patched_func(self): + return some_globals(self.__some_mangled_prop) + + return SomeClass.patched_func + """ + + _def, _ast, fv_body = _process_freevars() + _global = ( + "" + if class_name in func.__code__.co_freevars + else f" global {class_name}\n" + ) + class_src = f"{_global} class {class_name}(object):\n pass" + ret = f" return {class_name}.{func.__name__}" + to_parse = "\n".join([_def] + fv_body + [class_src, ret]) + new_source = _parse(to_parse) + new_source.body[0].body[-2].body[0] = _ast # type: ignore [attr-defined] + return new_source + + def _process_function() -> ast.Module: + _def, _ast, fv_body = _process_freevars() + name = func.__name__ + ret = f" return {name}" + _global = [] if name in func.__code__.co_freevars else [f" global {name}"] + to_parse = "\n".join([_def] + _global + fv_body + [" pass", ret]) + new_source = _parse(to_parse) + new_source.body[0].body[-2] = _ast # type: ignore [attr-defined] + return new_source + + if class_name: + new_source = _process_method() + else: + new_source = _process_function() + + # Compile and retrieve the new Code object + localz: dict[str, Any] = {} + new_code = cast(CodeType, _compile(new_source)) + + exec( + new_code, + dict(func.__globals__), + localz, + ) + new_func = localz["__patchy_freevars__"]() + + # Put the new Code object in place + real_func.__code__ = new_func.__code__ + # Store the modified source. This used to be attached to the function but + # that is a bit naughty + _source_map[real_func] = func_source + + +def _get_real_func(func: Callable[..., Any]) -> Callable[..., Any]: + """ + Duplicates some of the logic implicit in inspect.getsource(). Basically + some function-esque things, such as classmethods, aren't functions but we + can peel back the layers to the underlying function very easily. + """ + if inspect.ismethod(func): + return func.__func__ + else: + return func + + +def _assert_ast_equal(current_source: str, expected_source: str, name: str) -> None: + current_ast = ast.parse(current_source) + expected_ast = ast.parse(expected_source) + if ast.dump(current_ast) != ast.dump(expected_ast): + msg = ( + f"The code of '{name}' has changed from expected.\n" + f"The current code is:\n{current_source}\n" + f"The expected code is:\n{expected_source}" + ) + raise ValueError(msg) diff --git a/src/patchy/cache.py b/src/patchy/cache.py new file mode 100644 index 0000000000000000000000000000000000000000..2777df92f6415108e7383be658192d7da0ffe595 --- /dev/null +++ b/src/patchy/cache.py @@ -0,0 +1,30 @@ +from __future__ import annotations + +import random + + +class PatchingCache: + def __init__(self, maxsize: int) -> None: + self.maxsize = maxsize + self._cache: dict[tuple[str, str, bool], str] = {} + + def clear(self) -> None: + self._cache = {} + + def retrieve(self, source: str, patch_text: str, forwards: bool) -> str: + return self._cache[(source, patch_text, forwards)] + + def store( + self, source: str, patch_text: str, forwards: bool, new_source: str + ) -> None: + if len(self._cache) + 2 > self.maxsize: + # Delete a random 25%, at least 2 + delete_count = max(2, len(self._cache) // 4) + to_delete = random.sample(list(self._cache.keys()), delete_count) + for key in to_delete: + del self._cache[key] + + # Cache in both directions - makes reversal faster + self._cache[(source, patch_text, forwards)] = new_source + other_direction = not forwards + self._cache[(new_source, patch_text, other_direction)] = source diff --git a/tests/__init__.py b/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tests/conftest.py b/tests/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..5b5feb5d35ae1f5cbdc44f54c28668405a8423db --- /dev/null +++ b/tests/conftest.py @@ -0,0 +1,10 @@ +from __future__ import annotations + +import pytest + +import patchy.api + + +@pytest.fixture(autouse=True) +def clear_cache(): + patchy.api._patching_cache.clear() diff --git a/tests/test_cache.py b/tests/test_cache.py new file mode 100644 index 0000000000000000000000000000000000000000..533ff689a01128cf1fd2c139cd0d45186304e330 --- /dev/null +++ b/tests/test_cache.py @@ -0,0 +1,36 @@ +from __future__ import annotations + +import pytest + +from patchy.cache import PatchingCache + + +def test_store_retrieve(): + cache = PatchingCache(maxsize=100) + cache.store("a", "b", True, "c") + assert cache.retrieve("a", "b", True) == "c" + assert cache.retrieve("c", "b", False) == "a" + + +def test_missing_key_error(): + cache = PatchingCache(maxsize=100) + with pytest.raises(KeyError): + cache.retrieve("a", "b", True) + + +def test_clear(): + cache = PatchingCache(maxsize=100) + cache.store("a", "b", True, "c") + cache.clear() + with pytest.raises(KeyError): + cache.retrieve("a", "b", True) + + +def test_culling(): + cache = PatchingCache(maxsize=4) + cache.store("a", "b", True, "c") + assert len(cache._cache) == 2 + cache.store("a", "d", True, "e") + assert len(cache._cache) == 4 + cache.store("a", "f", True, "g") + assert len(cache._cache) <= 4 diff --git a/tests/test_patch.py b/tests/test_patch.py new file mode 100644 index 0000000000000000000000000000000000000000..92a927a099ee9e0869ced2dd9ea33cf46673fcbb --- /dev/null +++ b/tests/test_patch.py @@ -0,0 +1,953 @@ +from __future__ import annotations + +import sys +from collections.abc import Callable +from textwrap import dedent + +import pytest + +import patchy.api + +if True: + import __future__ + + +def test_patch(): + def sample() -> int: + return 1 + + assert sample() == 1 + + patchy.patch( + sample, + """\ + @@ -1,2 +1,2 @@ + def sample() -> int: + - return 1 + + return 9001 + """, + ) + assert sample() == 9001 + + +def test_mc_patchface(): + def sample() -> int: + return 1 + + assert sample() == 1 + + patchy.mc_patchface( + sample, + """\ + @@ -2,1 +2,1 @@ + - return 1 + + return 2 + """, + ) + assert sample() == 2 + + +def test_patch_simple_no_newline(): + def sample() -> int: + return 1 + + assert sample() == 1 + + patchy.patch( + sample, + """\ + @@ -2,1 +2,1 @@ + - return 1 + + return 2""", + ) + assert sample() == 2 + + +def test_patch_invalid(): + """ + We need to balk on empty patches + """ + + def sample() -> int: + return 1 + + bad_patch = """garbage + """ + with pytest.raises(ValueError) as excinfo: + patchy.patch(sample, bad_patch) + + msg = str(excinfo.value) + # GNU patch + expected = dedent( + """\ + Could not apply the patch to 'sample'. The message from `patch` was: + + patch: **** Only garbage was found in the patch input. + + The code to patch was: + def sample() -> int: + return 1 + + The patch was: + garbage + """ + ) + # BSD patch + expected2_fragment = "I can't seem to find a patch in there anywhere." + assert msg == expected or expected2_fragment in msg + assert sample() == 1 + + +def test_patch_invalid_hunk(): + """ + We need to balk on patches that fail on application + """ + + def sample() -> int: + return 1 + + bad_patch = """\ + @@ -1,2 +1,2 @@ + def sample() -> int: + - return 2 + + return 23""" + with pytest.raises(ValueError) as excinfo: + patchy.patch(sample, bad_patch) + + msg = str(excinfo.value) + assert ( + # GNU patch + "Hunk #1 FAILED" in msg + # BSD patch + or "1 out of 1 hunks failed" in msg + ) + assert sample() == 1 + + +def test_patch_invalid_hunk_2(): + """ + We need to balk on patches that fail on application + """ + + def sample(x: int) -> int: + if x == 1: + print("yes") + # or + elif x == 2: + print("no") + return 1 + + assert sample(1) == 1 + assert sample(2) == 1 + + bad_patch = """\ + @@ -1,3 +1,3 @@ + def sample(x: int) -> int: + - if x == 1: + + if x == 2: + # or + @@ -3,3 +3,3 @@ + # or + - elif x == 3: + + elif x == 4: + print("no") + """ + with pytest.raises(ValueError) as excinfo: + patchy.patch(sample, bad_patch) + + msg = str(excinfo.value) + assert ( + # GNU patch + "Hunk #2 FAILED" in msg + # BSD patch + or "1 out of 2 hunks failed" in msg + ) + assert sample(0) == 1 + + +def test_patch_twice(): + def sample() -> int: + return 1 + + assert sample() == 1 + + patchy.patch( + sample, + """\ + @@ -1,2 +1,2 @@ + def sample() -> int: + - return 1 + + return 2""", + ) + patchy.patch( + sample, + """\ + @@ -1,2 +1,2 @@ + def sample() -> int: + - return 2 + + return 3 + """, + ) + + assert sample() == 3 + + +def test_patch_mutable_default_arg(): + def foo(append: str | None = None, mutable: list[str] = []) -> int: # noqa: B006 + if append is not None: + mutable.append(append) + return len(mutable) + + assert foo() == 0 + assert foo("v1") == 1 + assert foo("v2") == 2 + assert foo(mutable=[]) == 0 + + def_line = ( + "def foo(append: str | None = None, mutable: list[str] = [])" + + " -> int: # noqa: B006" + ) + patchy.patch( + foo, + f"""\ + @@ -1,2 +1,3 @@ + {def_line} + + len(mutable) + if append is not None: + """, + ) + + assert foo() == 2 + assert foo("v3") == 3 + assert foo(mutable=[]) == 0 + + +def test_patch_instancemethod(): + class Artist: + def method(self) -> str: + return "Chalk" + + assert Artist().method() == "Chalk" + + patchy.patch( + Artist.method, + """\ + @@ -1,2 +1,2 @@ + def method(self) -> str: + - return "Chalk" + + return "Cheese" + """, + ) + + assert Artist().method() == "Cheese" + + +def test_patch_instancemethod_freevars(): + def free_func(v: str) -> str: + return v + " on toast" + + class Artist: + def method(self) -> str: + filling = "Chalk" + return free_func(filling) + + assert Artist().method() == "Chalk on toast" + + patchy.patch( + Artist.method, + """\ + @@ -1,3 +1,3 @@ + def method(self) -> str: + - filling = "Chalk" + + filling = "Cheese" + return free_func(filling) + """, + ) + + assert Artist().method() == "Cheese on toast" + + +def test_patch_init_module_level(tmp_path): + """ + Module level classes do not have a freevar for their class name, whilst + classes defined in a scope do... + """ + example_py = tmp_path / "patch_init_module_level.py" + example_py.write_text( + dedent( + """\ + class Person(object): + def __init__(self) -> None: + self.base_prop = 'yo' + + + class Artist(Person): + def __init__(self) -> None: + super().__init__() + self.prop = 'old' + """ + ) + ) + + sys.path.insert(0, str(tmp_path)) + try: + import patch_init_module_level as mod + finally: + sys.path.pop(0) + Artist = mod.Artist + + patchy.patch( + Artist.__init__, + """\ + @@ -1,3 +1,3 @@ + def __init__(self) -> None: + super().__init__() + - self.prop = 'old' + + self.prop = 'new' + """, + ) + + a = Artist() + assert mod.Artist == Artist + assert a.base_prop == "yo" + assert a.prop == "new" + + +def test_patch_recursive_module_level(tmp_path): + """ + Module level recursive functions do not have a freevar for their name, + whilst functions defined in a scope do... + """ + example_py = tmp_path / "patch_recursive_module_level.py" + example_py.write_text( + dedent( + """\ + def factorial(n): + if n == 1: + return 1 + else: + return n * factorial(n-1) + """ + ) + ) + sys.path.insert(0, str(tmp_path)) + try: + import patch_recursive_module_level as mod + finally: + sys.path.pop(0) + factorial = mod.factorial + + assert factorial(10) == 3628800 + + patchy.patch( + factorial, + """\ + @@ -2,4 +2,4 @@ + - if n == 1: + - return 1 + - else: + - return n * factorial(n-1) + + if n <= 1: + + return n + + else: + + return factorial(n-1) + factorial(n-2) + """, + ) + + assert factorial(10) == 55 + assert factorial == mod.factorial + + +def test_patch_init_super_new(): + class Person: + def __init__(self) -> None: + self.base_prop = "yo" + + class Artist(Person): + def __init__(self) -> None: + super().__init__() + self.prop = "old" + + assert Artist().prop == "old" + + patchy.patch( + Artist.__init__, + """\ + @@ -1,3 +1,3 @@ + def __init__(self) -> None: + super().__init__() + - self.prop = "old" + + self.prop = "new" + """, + ) + + a = Artist() + assert a.base_prop == "yo" + assert a.prop == "new" + + +def test_patch_freevars(): + def free_func(v: str) -> str: + return v + " on toast" + + def sample() -> str: + filling = "Chalk" + return free_func(filling) + + assert sample() == "Chalk on toast" + + patchy.patch( + sample, + """\ + @@ -1,3 +1,3 @@ + def sample() -> str: + - filling = "Chalk" + + filling = "Cheese" + return free_func(filling) + """, + ) + + assert sample() == "Cheese on toast" + + +def test_patch_freevars_order(): + def tastes_good(v: str) -> str: + return v + " tastes good" + + def tastes_bad(v: str) -> str: + return v + " tastes bad" + + def sample() -> str: + return ", ".join([tastes_good("Cheese"), tastes_bad("Chalk")]) + + assert sample() == "Cheese tastes good, Chalk tastes bad" + + patchy.patch( + sample, + """\ + @@ -1,2 +1,2 @@ + def sample() -> str: + - return ", ".join([tastes_good("Cheese"), tastes_bad("Chalk")]) + + return ", ".join([tastes_bad("Chalk"), tastes_good("Cheese")]) + """, + ) + + assert sample() == "Chalk tastes bad, Cheese tastes good" + + +def test_patch_freevars_remove(): + def tastes_good(v: str) -> str: + return v + " tastes good" + + def tastes_bad(v: str) -> str: + return v + " tastes bad" + + def sample() -> str: + return ", ".join([tastes_bad("Chalk"), tastes_good("Cheese")]) + + assert sample() == "Chalk tastes bad, Cheese tastes good" + + patchy.patch( + sample, + """\ + @@ -1,2 +1,2 @@ + def sample() -> str: + - return ", ".join([tastes_bad("Chalk"), tastes_good("Cheese")]) + + return ", ".join([tastes_good("Cheese")]) + """, + ) + + assert sample() == "Cheese tastes good" + + +def test_patch_freevars_nested(): + def free_func(v: str) -> str: + return v + " on toast" + + def sample() -> Callable[[], str]: + filling = "Chalk" + + def _inner_func() -> str: + return free_func(filling) + + return _inner_func + + assert sample()() == "Chalk on toast" + + patchy.patch( + sample, + """\ + @@ -1,4 +1,4 @@ + def sample() -> Callable[[], str]: + - filling = "Chalk" + + filling = "Cheese" + + def _inner_func(): + """, + ) + + assert sample()() == "Cheese on toast" + + +@pytest.mark.xfail(raises=NameError) +def test_patch_freevars_re_close(): + def nasty_filling() -> str: + return "Chalk" + + def nice_filling() -> str: + return "Cheese" + + def sample() -> str: + filling = nasty_filling() + return filling + " on toast" + + assert nasty_filling() == "Chalk" + assert nice_filling() == "Cheese" + assert sample() == "Chalk on toast" + + patchy.patch( + sample, + """\ + @@ -1,3 +1,3 @@ + def sample() -> str: + - filling = nasty_filling() + + filling = nice_filling() + return filling + ' on toast' + """, + ) + + assert sample() == "Cheese on toast" + + +def test_patch_instancemethod_twice(): + class Artist: + def method(self) -> str: + return "Chalk" + + assert Artist().method() == "Chalk" + + patchy.patch( + Artist.method, + """\ + @@ -1,2 +1,2 @@ + def method(self) -> str: + - return "Chalk" + + return "Cheese" + """, + ) + + patchy.patch( + Artist.method, + """\ + @@ -1,2 +1,2 @@ + def method(self) -> str: + - return "Cheese" + + return "Crackers" + """, + ) + + assert Artist().method() == "Crackers" + + +def test_patch_instancemethod_mangled(): + class Artist: + def __mangled_name(self, v: str) -> str: + return v + " on toast" + + def method(self) -> str: + filling = "Chalk" + return self.__mangled_name(filling) + + assert Artist().method() == "Chalk on toast" + + patchy.patch( + Artist.method, + """\ + @@ -1,3 +1,3 @@ + def method(self) -> str: + - filling = "Chalk" + + filling = "Cheese" + return self.__mangled_name(filling) + """, + ) + + assert Artist().method() == "Cheese on toast" + + +def test_patch_instancemethod_mangled_freevars(): + def _Artist__mangled_name(v: str) -> str: + return v + " on " + + def plain_name(v: str) -> str: + return v + "toast" + + class Artist: + def method(self) -> str: + filling = "Chalk" + return plain_name( + __mangled_name(filling) # type: ignore [name-defined] # noqa: F821 + ) + + assert Artist().method() == "Chalk on toast" + + patchy.patch( + Artist.method, + """\ + @@ -1,3 +1,3 @@ + def method(self) -> str: + - filling = "Chalk" + + filling = "Cheese" + return plain_name(__mangled_name(filling)) # noqa: F821 + """, + ) + + assert Artist().method() == "Cheese on toast" + + +def test_patch_instancemethod_mangled_tabs(tmp_path): + (tmp_path / "tabs_mangled.py").write_text( + dedent( + """\ + class Artist: + \tdef __mangled_name(self, v: str) -> str: + \t\treturn v + ' on toast' + + \tdef method(self) -> str: + \t\tfilling = 'Chalk' + \t\treturn self.__mangled_name(filling) + """ + ) + ) + sys.path.insert(0, str(tmp_path)) + try: + from tabs_mangled import Artist + finally: + sys.path.pop(0) + + patchy.patch( + Artist.method, + """\ + @@ -1,3 +1,3 @@ + def method(self) -> str: + -\tfilling = 'Chalk' + +\tfilling = 'Cheese' + \treturn __mangled_name(filling) + """, + ) + + assert Artist().method() == "Cheese on toast" + + +def test_patch_init(): + class Artist: + def __init__(self) -> None: + self.prop = "old" + + assert Artist().prop == "old" + + patchy.patch( + Artist.__init__, + """\ + @@ -1,2 +1,2 @@ + def __init__(self) -> None: + - self.prop = "old" + + self.prop = "new" + """, + ) + + a = Artist() + assert a.prop == "new" + + +def test_patch_init_change_arg(): + class Artist: + def __init__(self) -> None: + self.prop = "old" + + assert Artist().prop == "old" + + patchy.patch( + Artist.__init__, + """\ + @@ -1,2 +1,2 @@ + -def __init__(self) -> None: + - self.prop = "old" + +def __init__(self, arg: str) -> None: + + self.prop = arg + """, + ) + + a = Artist("new") # type: ignore [call-arg] + assert a.prop == "new" + + +def test_patch_classmethod(): + class Emotion: + def __init__(self, name: str) -> None: + self.name = name + + @classmethod + def create(cls, name: str) -> Emotion: + return cls(name) + + assert Emotion.create("alright").name == "alright" + + patchy.patch( + Emotion.create, + """\ + @@ -1,3 +1,4 @@ + @classmethod + def create(cls, name: str) -> Emotion: + + name = name.title() + return cls(name)""", + ) + + assert Emotion.create("Happy").name == "Happy" + assert Emotion.create("happy").name == "Happy" + + +def test_patch_classmethod_twice(): + class Emotion: + def __init__(self, name: str) -> None: + self.name = name + + @classmethod + def create(cls, name: str) -> Emotion: + return cls(name) + + assert Emotion.create("alright").name == "alright" + + patchy.patch( + Emotion.create, + """\ + @@ -1,3 +1,4 @@ + @classmethod + def create(cls, name: str) -> Emotion: + + name = name.title() + return cls(name)""", + ) + + patchy.patch( + Emotion.create, + """\ + @@ -1,4 +1,4 @@ + @classmethod + def create(cls, name: str) -> Emotion: + - name = name.title() + + name = name.lower() + return cls(name)""", + ) + + assert Emotion.create("happy").name == "happy" + assert Emotion.create("Happy").name == "happy" + assert Emotion.create("HAPPY").name == "happy" + + +def test_patch_staticmethod(): + class Doge: + @staticmethod + def bark() -> str: + return "Woof" + + assert Doge.bark() == "Woof" + + patchy.patch( + Doge.bark, + """\ + @@ -1,3 +1,3 @@ + @staticmethod + def bark() -> str: + - return "Woof" + + return "Wow\"""", + ) + + assert Doge.bark() == "Wow" + + +def test_patch_staticmethod_twice(): + class Doge: + @staticmethod + def bark() -> str: + return "Woof" + + assert Doge.bark() == "Woof" + + patchy.patch( + Doge.bark, + """\ + @@ -1,3 +1,3 @@ + @staticmethod + def bark() -> str: + - return "Woof" + + return "Wow\"""", + ) + + patchy.patch( + Doge.bark, + """\ + @@ -1,3 +1,3 @@ + @staticmethod + def bark() -> str: + - return "Wow" + + return "Wowowow\"""", + ) + + assert Doge.bark() == "Wowowow" + + +def test_patch_future_python(tmp_path): + (tmp_path / "future_user.py").write_text( + dedent( + """\ + from __future__ import annotations + + + def sample() -> None: + pass + """ + ) + ) + sys.path.insert(0, str(tmp_path)) + try: + from future_user import sample + finally: + sys.path.pop(0) + + assert sample.__code__.co_flags & __future__.annotations.compiler_flag + + patchy.patch( + sample, + """\ + @@ -1,2 +1,3 @@ + def sample() -> None: + + pass + pass + """, + ) + + assert sample.__code__.co_flags & __future__.annotations.compiler_flag + + +def test_patch_future_instancemethod(tmp_path): + (tmp_path / "future_instancemethod.py").write_text( + dedent( + """\ + from __future__ import annotations + + class Sample: + def meth(self) -> None: + pass + """ + ) + ) + sys.path.insert(0, str(tmp_path)) + try: + from future_instancemethod import Sample + finally: + sys.path.pop(0) + + assert Sample.meth.__code__.co_flags & __future__.annotations.compiler_flag + + patchy.patch( + Sample.meth, + """\ + @@ -1,2 +1,3 @@ + def meth(self) -> None: + + pass + pass + """, + ) + + assert Sample.meth.__code__.co_flags & __future__.annotations.compiler_flag + + +def test_patch_nonlocal_fails(): + variab = 20 # noqa: F841 + + def get_function() -> Callable[[], int]: + variab = 15 + + def sample() -> int: + nonlocal variab + multiple = 3 + return variab * multiple + + return sample + + sample = get_function() + + assert sample() == 15 * 3 + + patchy.patch( + sample, + """\ + @@ -2,3 +2,3 @@ + nonlocal variab # noqa: F824 + - multiple = 3 + + multiple = 4 + """, + ) + + assert sample() == 15 * 4 + + +def test_patch_by_path(tmp_path): + package = tmp_path / "patch_by_path_pkg" + package.mkdir() + (package / "__init__.py").write_text("") + (package / "mod.py").write_text( + dedent( + """\ + class Foo: + def sample(self) -> int: + return 1 + """ + ) + ) + sys.path.insert(0, str(tmp_path)) + try: + patchy.patch( + "patch_by_path_pkg.mod.Foo.sample", + """\ + @@ -2,1 +2,1 @@ + - return 1 + + return 2 + """, + ) + from patch_by_path_pkg.mod import Foo + finally: + sys.path.pop(0) + + assert Foo().sample() == 2 + + +def test_patch_by_path_already_imported(tmp_path): + package = tmp_path / "patch_by_path_pkg2" + package.mkdir() + (package / "__init__.py").write_text("") + (package / "mod.py").write_text( + dedent( + """\ + class Foo: + def sample(self) -> int: + return 1 + """ + ) + ) + sys.path.insert(0, str(tmp_path)) + try: + from patch_by_path_pkg2.mod import Foo + + assert Foo().sample() == 1 + patchy.patch( + "patch_by_path_pkg2.mod.Foo.sample", + """\ + @@ -2,1 +2,1 @@ + - return 1 + + return 2 + """, + ) + finally: + sys.path.pop(0) + + assert Foo().sample() == 2 diff --git a/tests/test_patch_then_unpatch.py b/tests/test_patch_then_unpatch.py new file mode 100644 index 0000000000000000000000000000000000000000..3a1962d54c104a8d26f9b4e2f1ee08afaec28510 --- /dev/null +++ b/tests/test_patch_then_unpatch.py @@ -0,0 +1,45 @@ +from __future__ import annotations + +from typing import Any + +import patchy.api + + +def test_patch_unpatch(): + def sample() -> int: + return 1 + + assert sample() == 1 + + patch_text = """\ + @@ -1,2 +1,2 @@ + def sample() -> int: + - return 1 + + return 9001 + """ + + patchy.patch(sample, patch_text) + assert sample() == 9001 + + # Check that we use the cache + orig_mkdtemp = patchy.api.mkdtemp # type: ignore [attr-defined] + + def mkdtemp(*args: Any, **kwargs: Any) -> None: # pragma: no cover + raise AssertionError( + "mkdtemp should not be called, the unpatch should be cached." + ) + + try: + patchy.api.mkdtemp = mkdtemp # type: ignore [attr-defined,assignment] + patchy.unpatch(sample, patch_text) + finally: + patchy.api.mkdtemp = orig_mkdtemp # type: ignore [attr-defined] + assert sample() == 1 + + # Check that we use the cache going forwards again + try: + patchy.api.mkdtemp = mkdtemp # type: ignore [attr-defined,assignment] + patchy.patch(sample, patch_text) + finally: + patchy.api.mkdtemp = orig_mkdtemp # type: ignore [attr-defined] + assert sample() == 9001 diff --git a/tests/test_replace.py b/tests/test_replace.py new file mode 100644 index 0000000000000000000000000000000000000000..5f4e8b9d5855ee5a1a3d7a9f7f047472f5e71342 --- /dev/null +++ b/tests/test_replace.py @@ -0,0 +1,153 @@ +from __future__ import annotations + +import pytest + +import patchy.api + + +def test_replace(): + def sample() -> int: + return 1 + + assert sample() == 1 + + patchy.replace( + sample, + """\ + def sample() -> int: + return 1 + """, + """\ + def sample() -> int: + return 42 + """, + ) + + assert sample() == 42 + + +def test_replace_only_cares_about_ast(): + def sample() -> int: + return 1 + + assert sample() == 1 + + patchy.replace( + sample, "def sample() -> int: return 1", "def sample() -> int: return 42" + ) + + assert sample() == 42 + + +def test_replace_twice(): + def sample() -> int: + return 1 + + assert sample() == 1 + + patchy.replace( + sample, "def sample() -> int: return 1", "def sample() -> int: return 2" + ) + patchy.replace( + sample, "def sample() -> int: return 2", "def sample() -> int: return 3" + ) + + assert sample() == 3 + + +def test_replace_mutable_default_arg(): + def foo(append: str | None = None, mutable: list[str] = []) -> int: # noqa: B006 + if append is not None: + mutable.append(append) + return len(mutable) + + assert foo() == 0 + assert foo("v1") == 1 + assert foo("v2") == 2 + assert foo(mutable=[]) == 0 + + patchy.replace( + foo, + """\ + def foo(append: str | None = None, mutable: list[str] = []) -> int: + if append is not None: + mutable.append(append) + return len(mutable) + """, + """\ + def foo(append: str | None = None, mutable: list[str] = []) -> int: + len(mutable) + if append is not None: + mutable.append(append) + return len(mutable) + """, + ) + + assert foo() == 2 + assert foo("v3") == 3 + assert foo(mutable=[]) == 0 + + +def test_replace_instancemethod(): + class Artist: + def method(self) -> str: + return "Chalk" + + assert Artist().method() == "Chalk" + + patchy.replace( + Artist.method, + """\ + def method(self) -> str: + return 'Chalk' + """, + """\ + def method(self) -> str: + return 'Cheese' + """, + ) + + assert Artist().method() == "Cheese" + + +def test_replace_unexpected_source(): + def sample() -> int: + return 2 + + assert sample() == 2 + + with pytest.raises(ValueError) as excinfo: + patchy.replace( + sample, + """\ + def sample() -> int: + return 1 + """, + """\ + def sample() -> int: + return 42 + """, + ) + + msg = str(excinfo.value) + assert "The code of 'sample' has changed from expected" in msg + assert "return 2" in msg + assert "return 1" in msg + + +def test_replace_no_expected_source(): + def sample() -> int: + return 2 + + assert sample() == 2 + + patchy.replace( + sample, + None, + """\ + def sample() -> int: + return 42 + """, + ) + + assert sample() == 42 diff --git a/tests/test_temp_patch.py b/tests/test_temp_patch.py new file mode 100644 index 0000000000000000000000000000000000000000..4ab762b5a922d30dcda7ccd84a5d076c0f99a9f1 --- /dev/null +++ b/tests/test_temp_patch.py @@ -0,0 +1,74 @@ +from __future__ import annotations + +import sys +from textwrap import dedent + +import patchy.api + + +def test_context_manager(): + def sample() -> int: + return 1234 + + patch_text = """\ + @@ -1,2 +1,2 @@ + def sample() -> int: + - return 1234 + + return 5678 + """ + + assert sample() == 1234 + with patchy.temp_patch(sample, patch_text): + assert sample() == 5678 + assert sample() == 1234 + + +def test_decorator(): + def sample() -> int: + return 3456 + + patch_text = """\ + @@ -1,2 +1,2 @@ + def sample() -> int: + - return 3456 + + return 7890 + """ + + @patchy.temp_patch(sample, patch_text) + def decorated() -> None: + assert sample() == 7890 + + assert sample() == 3456 + decorated() + assert sample() == 3456 + + +def test_patch_by_path(tmp_path): + package = tmp_path / "tmp_by_path_pkg" + package.mkdir() + (package / "__init__.py").write_text("") + (package / "mod.py").write_text( + dedent( + """\ + class Foo(object): + def sample(self): + return 1 + """ + ) + ) + patch_text = """\ + @@ -2,1 +2,1 @@ + - return 1 + + return 2 + """ + + sys.path.insert(0, str(tmp_path)) + try: + with patchy.temp_patch("tmp_by_path_pkg.mod.Foo.sample", patch_text): + from tmp_by_path_pkg.mod import Foo + + assert Foo().sample() == 2 + finally: + sys.path.pop(0) + + assert Foo().sample() == 1 diff --git a/tests/test_unpatch.py b/tests/test_unpatch.py new file mode 100644 index 0000000000000000000000000000000000000000..a53c5a36115ab622a24abc4154180331b11e118d --- /dev/null +++ b/tests/test_unpatch.py @@ -0,0 +1,76 @@ +from __future__ import annotations + +import pytest + +import patchy.api + + +def test_unpatch(): + def sample() -> int: + return 9001 + + sample() + + patchy.unpatch( + sample, + """\ + @@ -1,2 +1,2 @@ + def sample() -> int: + - return 1 + + return 9001 + """, + ) + assert sample() == 1 + + +def test_unpatch_invalid_unreversed(): + """ + We need to balk on patches that fail on application + """ + + def sample() -> int: + return 1 + + # This patch would make sense forwards but doesn't backwards + bad_patch = """\ + @@ -1,2 +1,2 @@ + def sample() -> int: + - return 1 + + return 2""" + with pytest.raises(ValueError) as excinfo: + patchy.unpatch(sample, bad_patch) + + msg = str(excinfo.value) + assert ( + # GNU patch + "Unreversed patch detected!" in msg + # BSD patch + or msg.startswith("Could not unapply the patch") + ) + assert sample() == 1 + + +def test_unpatch_invalid_hunk(): + """ + We need to balk on patches that fail on application + """ + + def sample() -> int: + return 1 + + bad_patch = """\ + @@ -1,2 +1,2 @@ + def sample() -> int: + - return 3 + + return 2""" + with pytest.raises(ValueError) as excinfo: + patchy.unpatch(sample, bad_patch) + + msg = str(excinfo.value) + assert ( + # GNU patch + "Hunk #1 FAILED" in msg + # BSD patch + or "1 out of 1 hunks failed" in msg + ) + assert sample() == 1
diff --git a/src/patchy/__init__.py b/src/patchy/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..9097f62d7d15020c243314bd6456525ba073c1ce
--- /dev/null
+++ b/src/patchy/__init__.py
@@ -0,0 +1,3 @@
+from __future__ import annotations
+
+from .api import * # noqa
diff --git a/src/patchy/api.py b/src/patchy/api.py
new file mode 100644
index 0000000000000000000000000000000000000000..d807924f7867002b72bab5fbd3d54e0044839744
--- /dev/null
+++ b/src/patchy/api.py
@@ -0,0 +1,328 @@
+from __future__ import annotations
+
+import ast
+import inspect
+import os
+import shutil
+import subprocess
+from collections.abc import Callable
+from functools import wraps
+from tempfile import mkdtemp
+from textwrap import dedent
+from types import CodeType, TracebackType
+from typing import Any, TypeVar, cast
+from weakref import WeakKeyDictionary
+
+from .cache import PatchingCache
+
+if True:
+ import __future__
+
+from pkgutil import resolve_name as pkgutil_resolve_name
+
+__all__ = ("patch", "mc_patchface", "unpatch", "replace", "temp_patch")
+
+
+# Public API
+
+
+def patch(func: Callable[..., Any] | str, patch_text: str) -> None:
+ _do_patch(func, patch_text, forwards=True)
+
+
+mc_patchface = patch
+
+
+def unpatch(func: Callable[..., Any] | str, patch_text: str) -> None:
+ _do_patch(func, patch_text, forwards=False)
+
+
+def replace(
+ func: Callable[..., Any],
+ expected_source: str | None,
+ new_source: str,
+) -> None:
+ if expected_source is not None:
+ expected_source = dedent(expected_source)
+ current_source = _get_source(func)
+ _assert_ast_equal(current_source, expected_source, func.__name__)
+
+ new_source = dedent(new_source)
+ _set_source(func, new_source)
+
+
+AnyFunc = TypeVar("AnyFunc", bound=Callable[..., Any])
+
+
+class temp_patch:
+ def __init__(self, func: Callable[..., Any] | str, patch_text: str) -> None:
+ self.func = func
+ self.patch_text = patch_text
+
+ def __enter__(self) -> None:
+ patch(self.func, self.patch_text)
+
+ def __exit__(
+ self,
+ exc_type: type[BaseException] | None,
+ exc_val: BaseException | None,
+ exc_tb: TracebackType | None,
+ ) -> None:
+ unpatch(self.func, self.patch_text)
+
+ def __call__(self, decorable: AnyFunc) -> AnyFunc:
+ @wraps(decorable)
+ def wrapper(*args: Any, **kwargs: Any) -> Any:
+ with self:
+ decorable(*args, **kwargs)
+
+ return cast(AnyFunc, wrapper)
+
+
+# Gritty internals
+
+
+def _do_patch(