Download tasks/data/forward/adamchainz__patchy.eae591b/tests/test_patch.diff from Lego-X/ProgramGen: direct link, hf CLI and curl.
- Browser
- Download file 31.4 kB
-
https://huggingface.co/datasets/Lego-X/ProgramGen/resolve/main/tasks/data/forward/adamchainz__patchy.eae591b/tests/test_patch.diff
- Command line
-
hf download hf://datasets/Lego-X/ProgramGen/tasks/data/forward/adamchainz__patchy.eae591b/tests/test_patch.diff
-
curl -L -o test_patch.diff https://huggingface.co/datasets/Lego-X/ProgramGen/resolve/main/tasks/data/forward/adamchainz__patchy.eae591b/tests/test_patch.diff
31.4 kB
diff --git a/tests/__init__.py b/tests/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/tests/conftest.py b/tests/conftest.py
new file mode 100644
--- /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
--- /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
--- /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
--- /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
--- /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
--- /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
--- /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/tests/__init__.py b/tests/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/tests/conftest.py b/tests/conftest.py
new file mode 100644
--- /dev/null
+++ b/tests/conftest.py
+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
--- /dev/null
+++ b/tests/test_cache.py
+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
--- /dev/null
+++ b/tests/test_patch.py
+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
+