eniem
eniem

Reputation: 65

Python unittest check function call args

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?

Upvotes: 4

Views: 7526

Answers (1)

Will Keeling
Will Keeling

Reputation: 22994

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.

Upvotes: 5

Related Questions