Gabriel
Gabriel

Reputation: 10884

Confirming function calls inside a function I'm unittesting with mock module

I have a function I'm writing unit tests for. I'm trying to assert that a number of functions were called with the proper arguments given the input argument. For example, the function I'm unit testing is in a file called validate.py

def function_to_test(arg1):
    print 'return2: ', _sub_function_1()
    arg1 = _sub_function_1(arg1)
    arg1 = _sub_function_2(arg1)
    arg1 = _sub_function_3(arg1)
    return arg1


def _sub_function_1(arg1):
    pass

def _sub_function_2(arg1):
    pass

def _sub_function_3(arg1):
    pass

I have my unit tests in a file called dotest.py,

import validate
import unittest
import mock

class TestFunctionToTest(unittest.TestCase):

    @mock.patch('validate._sub_function_1')
    def test_basic(self, m_sub_function_1):
        m_sub_function_1 = mock.Mock(return_value='rv_sf1')
        dum_arg1 = 'dum'
        out = validate.function_to_test(dum_arg1)
        print 'called?: ', m_sub_function_1.called

if __name__ == '__main__':
    unittest.main()

The results of running this test are,

run -i dotest.py
return2:  <MagicMock name='_sub_function_1()' id='4502266128'>
called?:  False
.
----------------------------------------------------------------------
Ran 1 test in 0.001s

OK

For some reason the return value defined for the mock function is not being recognized in the call to _sub_function_1. I want to check if this function is actually called in function_to_test. Any insight from the mock gurus?

Upvotes: 2

Views: 1924

Answers (1)

Simeon Visser
Simeon Visser

Reputation: 122376

First of all, the self argument seems to be missing in your test_basic. Furthermore, your code doesn't call function_to_test. Personally I write the argument to mock.patch as a string so it would become:

class TestFunctionToTest(unittest.TestCase):

    @mock.patch('validate._sub_function_1')
    def test_basic(self, m_sub_function_1):
        m_sub_function_1.return_value = 'rv_sf1'
        function_to_test(...)

This should print: return2: rv_sf1. You can then assert it has been called with the correct arguments:

m_sub_function1.assert_called_with(...)

Upvotes: 1

Related Questions