Latest news about Bitcoin and all cryptocurrencies. Your daily crypto news habit.
A little background: over the last few months, I have been contributing in open source organization FOSSASIA, where Iâm working on a project called BadgeYaY. It is a badge generator with a simple web UI to add data and generate printable badges in PDF.
Badgeyay back-end 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 unit tests 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 Unit tests?
Unit tests 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 unit test module provides classes that make it easy to support these qualities for a set of tests.
Why Unit 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.
Now, here is glimpse of how I wrote unit tests for testing code in the REST-API back-end of Badgeyay. Using unit tests python package and requests modules, we can test REST API in test automation.
Below is the code snippet for which I have written unit tests in one of my pull requests.
def output(response_type, message, download_link): if download_link == ââ: response = [ { âtypeâ: response_type, âmessageâ: message } ] else: response = [ { âtypeâ: response_type, âmessageâ: message, âdownload_linkâ: download_link } ] return jsonify({âresponseâ: response})
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.
#!/usr/bin/env python3
âââTests for Basic Functionsâââimport sysimport jsonimport unittest
sys.path.append(â../..â)from app.main import *
class TestFunctions(unittest.TestCase): âââTest case for the client methods.âââ def setup(self): app.app.config[âTESTINGâ] = True self.app = app.app.test_client() # Test of Output function def test_output(self): with app.test_request_context(): # mock object out = output(âerrorâ, âTest Errorâ, âlocal_hostâ) # Passing the mock object response = [ { âtypeâ: âerrorâ, âmessageâ: âTest Errorâ, âdownload_linkâ: âlocal_hostâ } ] data = json.loads(out.get_data(as_text=True) # Assert response self.assertEqual(data[âresponseâ], response)
if __name__ == â__main__â: unittest.main()
And finally, we can verify that everything works by running nosetests .
This is how I wrote unit tests in BadgeYaY repository.
With that, I have reached the end of our discussion on writing Unit Tests for REST API in Python Web Application. I wrote this post as a solution to this issue in BadgeYaY project. If you liked this post, consider having a look at my other work on GitHub đ.
Sources : Unit testing framework
PS: Iâm new to blogging, so constructive criticism is not only welcomed, but very much wanted!
Writing Unit Tests for REST API in Python was originally published in Hacker Noon on Medium, where people are continuing the conversation by highlighting and responding to this story.
Disclaimer
The views and opinions expressed in this article are solely those of the authors and do not reflect the views of Bitcoin Insider. Every investment and trading move involves risk - this is especially true for cryptocurrencies given their volatility. We strongly advise our readers to conduct their own research when making a decision.