Writing an API benchmark

With this, we know how to write a simple benchmark. So, how about writing something similar for our API? Let's take a look at how we can modify one of our API tests that we used to validate the functioning of our index API endpoint and see how we can run a benchmark on that.

The following code modifies our existing index API test case to include a benchmark test for the API:

'''
File: test_index_benchmark.py
Description: Benchmark the index API endpoint
'''
import os
import pytest
import sys
import tempfile

sys.path.append('.')
import bugzot

@pytest.fixture(scope='module')
def test_client():
db, bugzot.app.config['DATABASE'] = tempfile.mkstemp()
bugzot.app.config['TESTING'] = True
test_client = bugzot.app.test_client()

with bugzot.app.app_context():
bugzot.db.create_all()

yield test_client

os.close(db)
os.unlink(bugzot.app.config['DATABASE'])

def test_index_benchmark(test_client, benchmark):
resp = benchmark(test_client.get, "/")
assert resp.status_code == 200

In the preceding code, all we did to make the API endpoint benchmark was add a new method, known as test_index_benchmark(), which takes in two fixtures as a parameter. One of the fixtures is responsible for setting up our application instance, and the second fixture—the benchmark fixture—is used to run the benchmark on the client API endpoint and generate the results.

Also, one important thing to note here is how we were able to mix the unit test code with the benchmark code so that we do not need to write two different methods for each class of the test; all of this is made possible by Pytest, which allows us to run the benchmark on the method as well as allow us to validate if the method being tested provides a correct result or not through the use of a single testing method.

Now we know how to write benchmark tests inside the application. But what if we had to debug something that was slow but for which the benchmark operation doesn't flags any concern. What can we do here? Fortunately for us, Python provides a lot of options that allow us to test for any kind of performance anomalies that may happen inside the code. So, let's spend some time looking over them.

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

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