Badgeyay backend is now shifted to REST-API and to test functions used in REST-API, we need some testing technology which will test each and every function used in the API. For our purposes, we chose the popular unit tests Python test suite.
In this blog, I’ll be discussing how I have written unit tests to test Badgeyay REST-API.
First, let’s understand what is unittests and why we have chosen it. Then we will move onto writing API tests for Badgeyay. These tests have a generic structure and thus the code I mention would work in other REST API testing scenarios, often with little to no modifications.
Let’s get started and understand API testing step by step.
What is Unittests?
Unitests is a Python unit testing framework which supports test automation, sharing of setup and shutdown code for tests, aggregation of tests into collections, and independence of the tests from the reporting framework. The unittest module provides classes that make it easy to support these qualities for a set of tests.
We get two primary benefits from unit testing, with a majority of the value going to the first:
- Guides your design to be loosely coupled and well fleshed out. If doing test driven development, it limits the code you write to only what is needed and helps you to evolve that code in small steps.
- Provides fast automated regression for re-factors and small changes to the code.
- Unit testing also gives you living documentation about how small pieces of the system work.
We should always strive to write comprehensive tests that cover the working code pretty well.
Below is the code snippet for which I have written unit tests in one of my pull requests.
To test this function, I basically created a mock object which could simulate the behavior of real objects in a controlled way, so in this case a mock object may simulate the behavior of the output function and return something like an JSON response without hitting the real REST API. Now the next challenge is to parse the JSON response and feed the specific value of the response JSON to the Python automation script. So Python reads the JSON as a dictionary object and it really simplifies the way JSON needs to be parsed and used.
And here’s the content of the backend/tests/test_basic.py file.
And finally, we can verify that everything works by running nosetests .