[Answered ]-Mocking a method with another reusable method with arguments in python

2👍

So, After some thoughts, I decided to use mock .return_value.

@patch('classToTest._get_xml')
    def computetest(self, get_xml):
        get_xml.return_value = _get_fake_xml('filenam.xml')
        test = ClassToTest()
        toassert = test.compute()

I wonder thought if there is a way to add the arguments in the patch decorator.

👤momigi

0👍

Could you put it in a closure? You could return a function from your _get_fake_xml method that still has access to _get_fake_xml‘s scope like this:

from mock import patch
class ClassTest():

    @patch('classToTest._get_xml', _get_fake_xml(mock.Mock(), 'filenam.xml'))
    def computetest(self):
        test = ClassToTest()
        toassert = test.compute()

        #assert whatever
        #self.assert(...)

    def _get_fake_xml(self, objects, filename):
        py_file = os.path.abspath(__file__)
        py_dir = os.path.dirname(py_file)
        xml_file = os.path.join(py_dir, filename)
        xml_tree = objectify.parse(xml_file)
        # don't know much about mock, but I include *a in case this is passed self
        return lambda *a: xml_tree.getroot()

Leave a comment