Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python unit test mock, get mocked function's input arguments

I want a unit test to assert that a variable action within a function is getting set to its expected value, the only time this variable is used is when it is passed in a call to a library.

Class Monolith(object):     def foo(self, raw_event):         action =  # ... Parse Event         # Middle of function         lib.event.Event(METADATA, action)         # Continue on to use the build event. 

My thought was that I could mock lib.event.Event, and get its input arguments and assert they are of specific value.

>Is this not how mocks work? The mock documentation frustrates me with its inconsistency, half-examples, and plethora of examples that are not related to what I want to do.

like image 814
ThorSummoner Avatar asked Jun 30 '15 04:06

ThorSummoner


People also ask

How do you mock a unit test in Python?

If you want to mock an object for the duration of your entire test function, you can use patch() as a function decorator. These functions are now in their own file, separate from their tests. Next, you'll re-create your tests in a file called tests.py .

What can be mocked for unit testing?

What is mocking? Mocking is a process used in unit testing when the unit being tested has external dependencies. The purpose of mocking is to isolate and focus on the code being tested and not on the behavior or state of external dependencies.

What is Side_effect in mock Python?

side_effect: A function to be called whenever the Mock is called. See the side_effect attribute. Useful for raising exceptions or dynamically changing return values. The function is called with the same arguments as the mock, and unless it returns DEFAULT , the return value of this function is used as the return value.

What is the difference between mock and MagicMock?

With Mock you can mock magic methods but you have to define them. MagicMock has "default implementations of most of the magic methods.". If you don't need to test any magic methods, Mock is adequate and doesn't bring a lot of extraneous things into your tests.


1 Answers

You can use call_args or call_args_list as well.

A quick example would look like:

import mock import unittest  class TestExample(unittest.TestCase):      @mock.patch('lib.event.Event')     def test_example1(self, event_mocked):         args, kwargs = event_mocked.call_args         args = event_mocked.call_args.args  # alternatively          self.assertEqual(args, ['metadata_example', 'action_example']) 

I just quickly written this example for somebody who might need it - I have not actually tested this so there might be minor bugs.
like image 93
akki Avatar answered Sep 18 '22 09:09

akki