Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pytest mocker patch Attribute:Error 'function' object has no attribute 'patch'

I'm trying to mock another method I've created using mocker.patch.object. However I get the AttributeError. New to using mocker but haven't seen an example that can help with this condition.

Tried different ways of calling the method from mocker.

within tests/test_unit.py

from pytest_mock import mocker

class TestApp:

 def setup_method(self):
        self.obj = ClassApi()

 def test_class_api_method(self, client):

        return_value = {'name': 'test'}
        mocker.patch.object(self.obj, 'method_to_mock')
        mocker.result(return_value)

within project/services

class ClassApi:

       def method_to_mock(self, input1):
         ...
        return result

AttributeError: 'function' object has no attribute 'patch'

like image 474
brad999 Avatar asked Jun 08 '19 06:06

brad999


1 Answers

I'm not super familiar with Pytest-Mock but based on a look at the docs you should be using mocker as a fixture. So you function should look like this:

 def test_class_api_method(self, client, mocker):

        return_value = {'name': 'test'}
        mocker.patch.object(self.obj, 'method_to_mock')
        mocker.result(return_value)

pytest automatically provides the argument mocker to the test function when it is run so there is no need to import it.

like image 112
pypypy Avatar answered Nov 03 '22 07:11

pypypy