Skip to content

Commit

Permalink
Fix bug where methods on subclasses failed when using Replace.on_class
Browse files Browse the repository at this point in the history
  • Loading branch information
cjw296 committed Feb 29, 2024
1 parent f8d7eb3 commit f4a0c0c
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 1 deletion.
2 changes: 1 addition & 1 deletion testfixtures/replace.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down
30 changes: 30 additions & 0 deletions testfixtures/tests/test_replace.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down

0 comments on commit f4a0c0c

Please sign in to comment.