Can I fix a static method in python?

I have a class in python that contains a static method. I want to mock.patch it to find out if it is called. When I try to do this, I get the error message: AttributeError: path.to.A does not have the attribute 'foo'

My setup can be simplified to:

 class A: @staticMethod def foo(): bla bla 

Now the test code with the error:

 def test(): with mock.patch.object("A", "foo") as mock_helper: mock_helper.return_value = "" A.some_other_static_function_that_could_call_foo() assert mock_helper.call_count == 1 
+5
source share
2 answers

You can always use patch as a decorator, my preferred way to fix things:

 from mock import patch @patch('absolute.path.to.class.A.foo') def test(mock_foo): mock_foo.return_value = '' # ... continue with test here 

EDIT: Your error seems to suggest that you have a problem elsewhere in your code. Perhaps some signal or trigger requiring this method that does not work?

+4
source

I got the same error message when trying to fix a method using the @patch decorator.

Here is the complete error I received.

 Traceback (most recent call last): File "/usr/local/lib/python3.6/site-packages/tornado/testing.py", line 136, in __call__ result = self.orig_method(*args, **kwargs) File "/usr/local/lib/python3.6/unittest/mock.py", line 1171, in patched arg = patching.__enter__() File "/usr/local/lib/python3.6/unittest/mock.py", line 1243, in __enter__ original, local = self.get_original() File "/usr/local/lib/python3.6/unittest/mock.py", line 1217, in get_original "%s does not have the attribute %r" % (target, name) AttributeError: <module 'py-repo.models.Device' from '/usr/share/projects/py-repo/models/Device.py'> does not have the attribute 'get_device_from_db' 

What I eventually did to fix this was a change to the patch decorator that I used

from @patch('py-repo.models.Device.get_device_from_db')

to @patch.object(DeviceModel, 'get_device_from_db')

I'm sorry that I cannot explain why this was a problem, but I'm still pretty new to Python. patch documentation was especially helpful in determining what was available for work. I should not get_device_from_db use the @staticmethod decorator, which can change. Hope this helps.

0
source

All Articles