Search code examples
testingflaskmockingflask-restful

How to mock function call in flask-restul resource method


I developed an API using Flask-restful. I have an API with resource named 'Server'. This resource has a method get to process request to '/server' url. In this method I have a call method of another class 'Connector' that get data from another service:

 class Server(Resource):
    def get(self):
     ...
        status, body = connector.get_servers(page, size) # call method of another class
     ...
    return body, status

I want to test developed API. I wrote some tests:

from application import create_app
from unittest import TestCase

class TestServerResource(TestCase):

def setUp(self):
    self.app = create_app()
    self.client = self.app.test_client

def test_bad_url(self):
    res = self.client().get('/server')
    self.assertEqual(res.status_code, 400)

# Test of get method Server resources described above
def test_pagination(self):
    res = self.client().get('/server?page=1&size=1') # request to my API
    self.assertEqual(res.status_code, 200)

In method 'test_pagination' I am testing method 'get' of my resource, but call of method of another class is in this method. Therefore I have a question: how I can mock call of 'connector.get_servers()' in test?

Thanks.


Solution

  • I have found a solution. To mock method call in other method we can user 'patch' decorator from unittest.mock

    For example described below this will look in the following way:

    from unittest.mock import patch
    
    # Test of get method Server resources described above
    @patch('path_to_method_we_want_to_mock.method')
    def test_pagination(self, mock):
       mock.return_value = <new value> # set value which mocked method return
       res = self.client().get('/server?page=1&size=1') # request to my API
       self.assertEqual(res.status_code, 200)
    

    Now in method get() calling of get_servers method will return mock.return_value.

    Also using of some patch decorators is possible:

    @patch('application.servers_connector.ServersConnector.get_server_by_id')
    @patch('application.rent_connector.RentConnector.get_rents_for_user')
    def test_rent_for_user(self, rent_mock, server_mock):
         ...