I have a Python TestCase class where all test methods, except one, need to patch an object the same way. The other method need some other behavior from the same object. I'm using mock, so I did:
@mock.patch('method_to_patch', mock.Mock(return_value=1))
class Tests(TestCase):
@mock.patch('method_to_patch', mock.Mock(return_value=2))
def test_override(self):
(....)
But that's not working. When test_override is run, it still calls the patched behavior from the class decorator.
After a lot of debugging, I found out that during the TestSuite build, the @patch around test_override is being called before the one around Tests, and since mock apply the patches in order, the class decorator is overriding the method decorator.
Is this order correct? I was expecting the opposite and I'm not really sure how to override patching... Maybe with a with statement?
test_overrideto be inTests? I can imagine having anotherTestCasewhich fortest_overrideand similar tests. If you want allmethod_to_patchto do one thing but a different thing fortest_overridethen I can also imagine that it is justified to have anotherTestCaseclass. That would solve your problem too and it makes the code a lot more readable for other developers (compared to "patching patching"). - Simeon Vissertest_overrideto another class isn't really an option, because of the rules we use to structure the tests. They're all tests relative to the same view, so we put 'em in a singleTestCase- Gabe