Python Unit Test Best Practice To Avoid Monkey Patching Bug
I have just encountered a bug with my unit test, because I was essentially monkey patching in the set up like so: def test_some_class_to_string(): some_class = SomeClass()
Solution 1:
Use a library like mock
to assist you with doing this. Say you have a class defined like this:
class A:
def __init__(self, x):
self.x = x
self.y = 6
Now, instead of simply creating an instance of A
and doing whatever you want with it, create a mock object that is an instrumented version of an instance of A
:
>>> m = unittest.mock.Mock(spec_set=A)
>>> m.z = 9
Traceback (most recent call last):
File "tmp.py", line 11, in <module>
m.z = 9
File ".../unittest/mock.py", line 684, in __setattr__
raise AttributeError("Mock object has no attribute '%s'" % name)
AttributeError: Mock object has no attribute 'z'
Solution 2:
You can try an assertion before the assignement:
def test_some_class_to_string():
some_class = SomeClass()
assert some_class.foo and some_class.bar
some_class.foo = 'bar'
some_class.monkey_patched = 'baz'
assert str(some_class) == 'barbaz'
Post a Comment for "Python Unit Test Best Practice To Avoid Monkey Patching Bug"