Home > Mobile >  Is it possible to check the call parameters in the test?
Is it possible to check the call parameters in the test?

Time:03-05

is it possible to check in the test with what parameters the method is called and what result it returns, if we call the main method run which calls the method I'm interested in - self.get_request().

file.py

class A:
 def run():
    some logic...
    request = self.get_request()
    some logic...
    return response

test.py

from file.py import A
def test():
   """
   Inside this test, I want to check the parameters and the value returned by the
   get_request method, but I don't want to check it separately
   I want to check it by calling the parent method - run
   """
   instance = A()
   response = instance.run()
   assertions logic for instance.get_request..

I know that it is possible to mock a method and then we have access to the number of calls, parameters, etc. If what I'm asking is possible in some way through mock, I just want to add that my mock would have to have the same logic as the method it mocks (be the same).

CodePudding user response:

What you are asking for is probably the wraps argument that can be used in patch - this allows you to mock a function, while it still retains the previous (or some other) functionality (note that the argument itself is described under Mock). As with any mock, this does allow you to test the calls and call args, but does not allow you to check the return value of the function. This has to be tested via its side effects (in your case via the returned response which should depend on the return value of get_request).

Here is an illustration for your case:

from unittest import mock

class A:
    def run(self):
        request = self.get_request(21)
        return request

    def get_request(self, foo):
        return foo * 2

def test_run():
    instance = A()
    with mock.patch.object(instance, "get_request", wraps=instance.get_request) as mocked:
        assert instance.run() == 42
        mocked.assert_called_once_with(21)

In this case the mock calls the real get_request method and returns its result, while recording the call and the call args.
I added some argument to get_request for demonstration, and returned the result of the call directly in run - in your case this will differ of course, but the idea should be the same.

  • Related