Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I patch a static method in python?

Tags:

python

I've a class in python that contains a static method. I want to mock.patch it in order to see if it was called. When trying to do it I get an error: 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 that fails with 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
like image 273
eldad levy Avatar asked Aug 24 '15 23:08

eldad levy


1 Answers

You can always use patch as a decorator, my preferred way of patching 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 hint that you have a problem elsewhere in your code. Possibly some signal or trigger that requires this method that is failing?

like image 139
veggie1 Avatar answered Oct 12 '22 14:10

veggie1