How to Mock a Rest API in Python
How to Mock a Rest API in Python
In this article, we discuss how to mock a REST API with request-mock and Python and perform unit tests.
Join the DZone community and get the full member experience.Join For Free
A few posts ago, we published a blog about how to use the Jira API. We did not write any unit tests for the application we wrote, and that is exactly what we are going to do now. More specifically, we will focus on how we can unit test a REST API.
Why Unit Tests Anyway?
Our main focus when writing software is building new features and fixing bugs. Of course, we need to test what we built, but we get the most joyful moment when our newly developed feature works. The next step is to write unit tests… But, we already know it is working, so why spend so much effort on it? It is much more fun to start with the next feature, right? So, we skip writing unit tests. But what happens when we need to extend the feature we wrote with some new functionality?
How are we going to ensure we did not break the original feature? What if we want to refactor the code we have written? These are the moments we are glad when we notice someone took the effort to write unit tests. Unit tests will give us the confidence that we didn't break anything when we changed some code (assuming the unit tests are well written and provide enough code coverage). It is therefore also common practice to run the unit tests as part of your CI/CD pipeline.
If you do not like writing unit tests after developing a new feature, you can also consider writing your unit tests first, letting them fail, and when you implement your code, the unit tests will pass (TDD: Test Driven Development). This way, when you have reached your uppermost moment of joy (It works!), you also have your unit tests passed (All the unit tests passed!). That doubles your moment of joy ;-) .
Create Your First Unit Test
We will build upon the sources of the Jira time report generator. We are using Python 3.7 and PyCharm as an IDE. First, let’s create a
test directory and right-click the directory in PyCharm. Choose
New - Python File and
Python unit test. This creates the following default file:
Running this unit test obviously fails (True does not equal False), but we do have set up the basics for writing our own unit tests now.
Mocking a Rest API
We want to unit test the
get_updated_issues function and this provides us a first challenge: the
get_updated_issues function contains a call to the Jira Rest API. We do not want our unit test to be dependent on a third-party service, and therefore, we need a way to mock the Rest API. There are several options to mock a REST API, but we will make use of the requests-mock Python library, which fits our needs.
requests-mock Python library:
Test Single Page Response
get_updated_issues function will request the issues that are updated in a certain time period. In our unit test, we will verify the behavior when one page with results is retrieved (the Rest API supports pagination, but that is something for a next unit test):
Let’s take a closer look at what is happening here. We have defined the Jira JSON response in file
issues_one_page.json. At line 2 and 3, we read the contents of the file into variable
mock_response. On line 5, we define the expected result with variable
expected_result when the function
get_updated_issues returns. At lines 11 to 13, the magic happens.
We register the URI we call from within the
get_updated_issues function with the
Mocker we defined. The third parameter of
register_uri defines the response, which should be returned from the mocked API call. At line 15, we call the
get_updated_issues function, and at the end, we verify whether the response equals the expected result.
Test Paginated Response
The Jira API supports pagination. We added some functionality to the
get_updated_issues function in order to handle paginated responses. The JSON response contains three fields for this:
startAt: indicates from which result the page should be retrieved.
maxResults: the number of maximum results that are returned within one response.
total: the total number of results.
maxResults for retrieving issues is, at the time of writing, 50. If we would like to test this against a real Jira server, we would have to create at least 51 issues. But for testing with our unit test, we can easily change the response in order that field
maxResults returns 2 for example, which makes it a lot easier to test. Our paginated unit test looks as follows:
The unit test looks quite similar to the one for the single page response. We defined two mock responses this time, because the Jira API will be called twice and we want to return two different responses. The
expected_result variable contains the combined result of both API calls. The real difference can be seen at line 17. Instead of defining a single mock response, we now define a list of mock responses. When the API is called more than the defined responses, the latest defined mock response is returned again.
The unit tests above all pass. But do they fail when something is wrong? We can therefore change the following line in the
This will ensure that only the response of the first API call will be added to the returned issues list, but not the response of succeeding API calls. Run both tests again. The
test_get_updated_issues_one_page passes, but the
Test Multiple URI’s
The Jira work logs are to be retrieved per issue. We need to register more than one URI with different responses for each issue. The response of the
get_work_logs function returns a list of
WorkLog objects which we can assert.
Writing unit tests is absolutely necessary when you want to develop software in a professional manner. In this post, we took a look at how to unit test a Rest API by means of the
requests-mock Python library. We only scratched the surface of what this library has to offer, but our first impressions are very good.
Published at DZone with permission of Gunter Rotsaert , DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.