4

I am developing unit tests to an existing library, and I would like to test if the arguments a function is called with match certain criteria. In my case the function to test is:

class ...
 def function(self):
 thing = self.method1(self.THING)
 thing_obj = self.method2(thing)
 self.method3(thing_obj, 1, 2, 3, 4)

For the unit tests I have patched the methods 1, 2 and 3 in the following way:

import unittest
from mock import patch, Mock
class ...
 def setUp(self):
 patcher1 = patch("x.x.x.method1")
 self.object_method1_mock = patcher1.start()
 self.addCleanup(patcher1.stop)
 ...
 def test_funtion(self)
 # ???

In the unit test I would like to extract the arguments 1, 2, 3, 4 and compare them e.g. see if the 3rd argument is smaller than the fourth one ( 2 < 3). How would I go on about this with mock or another library?

Aran-Fey
44.1k13 gold badges113 silver badges161 bronze badges
asked Jun 1, 2018 at 11:34

1 Answer 1

5

You can get the most recent call arguments from a mock using the call_args attribute. If you want to compare the arguments of the self.method3() call, then you should be able to do something like this:

def test_function(self):
 # Call function under test etc. 
 ...
 # Extract the arguments for the last invocation of method3
 arg1, arg2, arg3, arg4, arg5 = self.object_method3_mock.call_args[0]
 # Perform assertions
 self.assertLess(arg3, arg4)

More info here on call_args and also call_args_list.

answered Jun 6, 2018 at 14:43
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.