From f4a0c0c0dc2973768e7c43d997ef4a8e5ced7e89 Mon Sep 17 00:00:00 2001 From: Chris Withers Date: Thu, 29 Feb 2024 09:28:00 +0000 Subject: [PATCH] Fix bug where methods on subclasses failed when using Replace.on_class --- testfixtures/replace.py | 2 +- testfixtures/tests/test_replace.py | 30 ++++++++++++++++++++++++++++++ 2 files changed, 31 insertions(+), 1 deletion(-) diff --git a/testfixtures/replace.py b/testfixtures/replace.py index a5c51ba..7077045 100644 --- a/testfixtures/replace.py +++ b/testfixtures/replace.py @@ -148,7 +148,7 @@ def _find_container(self, attribute, name: str, break_on_static: bool): for referrer in get_referrers(attribute): if break_on_static and isinstance(referrer, staticmethod): return None, referrer - elif isinstance(referrer, dict) and '__dict__' in referrer: + elif isinstance(referrer, dict): if referrer.get(name) is attribute: for container in get_referrers(referrer): if isinstance(container, type): diff --git a/testfixtures/tests/test_replace.py b/testfixtures/tests/test_replace.py index a0b7d6b..6db9b25 100644 --- a/testfixtures/tests/test_replace.py +++ b/testfixtures/tests/test_replace.py @@ -764,6 +764,36 @@ def method(self, x): compare(sample.method(1), expected=2) assert SampleClass.__dict__['method'] is original + def test_method_on_subclass(self): + + class SampleClass: + + def method_a(self, x): + return x*2 + + class SampleSubClass(SampleClass): + """ + Some doc! + """ + + def method_b(self, x): + return x*3 + + original_a = SampleClass.__dict__['method_a'] + original_b = SampleSubClass.__dict__['method_b'] + sample = SampleSubClass() + + with Replacer() as replace: + replace.on_class(SampleSubClass.method_a, lambda self, x: x*4) + replace.on_class(SampleSubClass.method_b, lambda self, x: x*5) + compare(sample.method_a(1), expected=4) + compare(sample.method_b(1), expected=5) + + compare(sample.method_a(1), expected=2) + compare(sample.method_b(1), expected=3) + assert SampleClass.__dict__['method_a'] is original_a + assert SampleSubClass.__dict__['method_b'] is original_b + def test_attributes_on_class(self): class SampleClass: