Mocking synchronous calls

If you are using Requests to perform all the calls--or you are using a library that is based on Requests and that does not customize it too much, this isolation work is easier to do, thanks to the transport adapters we saw earlier in this chapter.

The requests-mock project (https://requests-mock.readthedocs.io) implements an adapter that will let you mock network calls in your tests.

Earlier in this chapter, we saw an example of a Flask app that was an HTTP endpoint to serve some content on its /api endpoint.

That application used a Request session that was created by a setup_connector() function and retrieved in a view by a get_connector() function.

In the following test, we're mounting the ;requests_mock adapter into that session by calling session.mount() with a fresh requests_mock.Adapter() instance:

    import json 
import unittest
from flask_application import app, get_connector
from flask_webtest import TestApp
import requests_mock

class TestAPI(unittest.TestCase):
def setUp(self):
self.app = TestApp(app)
# mocking the request calls
session = get_connector(app)
self.adapter = requests_mock.Adapter()
session.mount('http://', self.adapter)

def test_api(self):
mocked_value = json.dumps({'some': 'data'})
self.adapter.register_uri('GET', 'http://127.0.0.1:5000
/api', text=mocked_value)
res = self.app.get('/api')
self.assertEqual(res.json['result']['some'], 'data')

Using this adapter offers the ability to manually register responses through ;register_uri for some given endpoints on the remote service (here http://127.0.0.1:5000/api). The adapter will intercept the call and immediately return the mocked value.

In the test_api() test, it will let us try out the application view and make sure it uses the provided JSON data when it calls the external service.

The requests-mock will also let you match requests using regular expressions, so it's a pretty powerful adapter to use in your tests to avoid a network dependency when they run.

That said, mocking responses from other services is still a fair amount of work and quite painful to maintain. It also means you need to keep an eye on how the other services are evolving over time, so your tests are not based on a mock that's not a reflection of the real API anymore.

Using mocks is encouraged to build good functional tests coverage, but make sure you are doing integration tests as well, where the service is tested in a deployment where it calls other services for real.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset