Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mock variable in function

For unit testing, I want to mock a variable inside a function, such as:

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

I my unit test, I don't want to be dependent on what get_complex_data_structure() would return, and therefore want to set the value of foo manually.

How do I accomplish this? Is this the place for @patch.object?

like image 261
Daniel Larsson Avatar asked Sep 03 '14 16:09

Daniel Larsson


People also ask

Can you mock a variable?

If you need to mock a global variable for all of your tests, you can use the setupFiles in your Jest config and point it to a file that mocks the necessary variables. This way, you will have the global variable mocked globally for all test suites.

Can we mock a variable in Python?

With a module variable you can can either set the value directly or use mock.

What does @patch do in Python?

patch() uses this parameter to pass the mocked object into your test. From there, you can modify the mock or make assertions as necessary. Technical Detail: patch() returns an instance of MagicMock , which is a Mock subclass. MagicMock is useful because it implements most magic methods for you, such as .


2 Answers

Just use @patch() to mock out 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 then calls get_complex_data_structure() a mock object is returned and stored in the local name foo; the very same object that mocked_function.return_value references in the above test; you can use that value to test if do_work() got passed the right object, for example.

like image 171
Martijn Pieters Avatar answered Sep 16 '22 11:09

Martijn Pieters


Assuming that get_complex_data_structure is a function1, you can just patch it using any of the various mock.patch utilities:

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 stop methods.2


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

like image 28
mgilson Avatar answered Sep 16 '22 11:09

mgilson