How to use unittest.mock to bully arbitrary ConfigParser calls in unit test

I am trying to start using unittest.mock action / assert pattern instead of mox record / play / check pattern.

# foo.py def op_1(param): pass def op_2(param): pass def do_stuff(param_1, param_2): global config global log try: op_1(param_1) if config.getboolean('section','option'): op_2(param_2) except: log.error("an error occured") 

And here is an example of what my unittest file looks like.

 # test_foo.py class TestFoo(unittest.TestCase): def test_do_stuff(self): param_1 = None param_2 = None foo.config = MagicMock() foo.config.getboolean('section','option', return_value = True) foo.op_1 = MagicMock() foo.op_2 = MagicMock() do_stuff(param_1, param_2) foo.op_1.assert_called_once_with(param_1) foo.op_2.assert_called_once_with(param_2) foo.config.getboolean.assert_called_once_with('section','option') 

Does this test conduct to check the items below / Am I using mock correctly?

  • do_stuff call returns without errors
  • op_1 is called with parameter_1
  • op_2 is called with parameter_2
  • the parser object was configured, but the specific calls do not matter.
+4
source share
1 answer

Turns out I misused return_value .

When I need a mock.Mock or mock.MagicMock object to return a value, it should always return that value regardless of the arguments passed. Although it might be nice to give a different behavior based on the arguments passed (a possible function request).

How I did it:

 foo.config.getboolean = mock.MagicMock(return_value = True) 

And then I can do it:

 self.assertGreaterThan(len(foo.config.mock_calls), 0) self.assertGreaterThan(len(foo.config.getboolean(str(),str())), 0) 
+3
source

All Articles