Variable layout in a function

For unit testing, I want to mock a variable inside a function, for example:

def function_to_test(self):
    foo = get_complex_data_structure()  # Do not test this
    do_work(foo)  # Test this

      

I am my unit test, I don't want to be dependent on what is get_complex_data_structure()

returned and so I want to manually set the value of foo.

How to do it? Is this the place for @patch.object

?

+3


source to share


2 answers


Just use @patch()

to mock get_complex_data_structure()

:

@patch('module_under_test.get_complex_data_structure')
def test_function_to_test(self, mocked_function):
    foo_mock = mocked_function.return_value

      



When the test function calls get_complex_data_structure()

, the mock object is returned and stored in the local name foo

; the same object that is mocked_function.return_value

referenced in the above test; you can use this value to check if the do_work()

correct object passed eg.

+6


source


Assuming get_complex_data_structure is function 1 you can just fix it using any of the mock.patch utility :

with mock.patch.object(the_module, 'get_complex_data_structure', return_value=something)
  val = function_to_test()
  ...

      

they can be used as decorators or context managers, or explicitly started and stopped using the start

and methods stop

. 2




1 If it's not a function, you can always output that code into a simple utility function that returns a complex data structure
2 There are a million ways to use mocks - it pays to read the docs to figure out all the ways you can set the return value, etc. ...

+4


source







All Articles