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.
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 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.
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.
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.
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'])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With