Write code to Unit Test a Python web app

The WebTest module makes it easy to write code to test WSGI-based web apps.

Installation method

You can install it with pip.

sudo pip install webtest

Sample code

The following is an example of a JSON-RPC server implementation using the bottle framework.

Web application side

app.py


from bottle import Bottle, HTTPResponse

HOST='localhost'
PORT=8080
DEBUG=True

app = Bottle()

def makeRes(code, data):
	data['retcode'] = code
	r = HTTPResponse(status=200, body=json.dumps(data))
	r.set_header('Content-Type', 'application/json')
	return r

@app.post('/aikotoba')
def api_aikotoba():
	o = request.json
	if o is None:
		return makeRes('ERR_PARAM', {})
	if not 'kotoba' in o:
		return makeRes('ERR_PARAM', {})
	if o['kotoba']=='Mountain':
		return makeRes('OK', {'henji':'eh?'}
	else:
		return makeRes('OK', {'henji':'Huh?'}

if __name__=='__main__':
	app.run(host=HOST, port=PORT, debug=DEBUG, reloader=True)

UnitTest side

test_app.py


import unittest
import api 
from webtest import TestApp

os.environ['WEBTEST_TARGET_URL'] = 'http://localhost:8080'
test_app = TestApp(api.app)

class ApiTest(unittest.TestCase):
	def test_api_aikotoba1(self):
		res = test_app.post_json('/aikotoba',{
			'kotoba':'Mountain' 
		})
		self.assertEqual(res.json['henji'], 'eh?')
	def test_api_aikotoba2(self):
		res = test_app.post_json('/aikotoba',{
			'kotoba':'river' 
		})
		self.assertEqual(res.json['henji'], 'Huh?')

if __name__ == '__main__':
    unittest.main()

Test implementation

1. Start up the test server.

python app.py

2. Run UnitTest.

python app_test.py

3. Check the result.

The result is output like this.

..
----------------------------------------------------------------------
Ran 2 tests in 0.079s

OK

If the asserts of the UnitTest class do not match, the output will look like the one below.

.F
======================================================================
FAIL: test_api_aikotoba2 (__main__.ApiTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "test_app.py", line 16, in test_api_aikotoba2
    self.assertEqual(res.json['henji'], 'Huh?')
AssertionError: 'Huh?' != 'Huh?'
-Huh?
? ^
+Huh?
? ^


----------------------------------------------------------------------
Ran 2 tests in 0.126s

FAILED (failures=1)

Recommended Posts

Write code to Unit Test a Python web app
I want to write in Python! (2) Let's write a test
How to write a Python class
Write selenium test code in python
Qiita (1) How to write a code name
Write the test in a python docstring
Isn't it okay to write test code?
[Python] What I did to do Unit Test
Steps to develop a web application in Python
Why does Python have to write a colon?
I want to write to a file with Python
Rewrite Python2 code to Python3 (2to3)
python unit test template
Deploy a Python 3.6 / Django / Postgres web app on Azure
I want to write in Python! (1) Code format check
Python Ver. To introduce WebPay with a little code.
(Python) Try to develop a web application using Django
Steps from installing Python 3 to creating a Django app
[Python] How to write a docstring that conforms to PEP8
A program to write Lattice Hinge with Rhinoceros with Python
How to create a kubernetes pod from python code
Deploy a web app created with Streamlit to Heroku
How to unit test a function containing the current time using freezegun in python
How to host web app backend processing in Python using a rental server subdomain
Write to csv with Python
Convert python 3.x code to python 2.x
How to deploy a web app made with Flask to Heroku
Sample to put Python Flask web app on Azure App Service (Web App)
How to launch AWS Batch from a python client app
Write a python program to find the editing distance [python] [Levenshtein distance]
How to write a test for processing that uses BigQuery
To write a test in Go, first design the interface
How to write a metaclass that supports both python2 and python3
Write a binary search in Python
Run the output code on the local web server as "A, pretending to be B" in python
Write a table-driven test in C
[Python] Write to csv file with Python
Python: Introduction to Flask: Creating a number identification app using MNIST
How to write code to access python dashDB on Bluemix or local
Write standard output to a file
Code to randomly generate a score
Write A * (A-star) algorithm in Python
Try to create a python environment with Visual Studio Code & WSL
I wrote the code to write the code of Brainf * ck in python
Simple code to call a python program from Javascript on EC2
Write a pie chart in Python
Write a vim plugin in Python
Slack --APIGateway --Lambda (Python) --How to make a RedShift interactive app
Write a depth-first search in Python
How to make a unit test Part.1 Design pattern for introduction
I wrote a script to extract a web page link in Python
5 Ways to Create a Python Chatbot
[Pytest] [mock] Web development beginners summarized unit test and mock in python.
Write C unit tests in Python
Write a batch script with Python3.5 ~
I wrote a code to convert quaternions to z-y-x Euler angles in Python
I made a web application in Python that converts Markdown to HTML
Let's throw away JavaScript and write a web front end in Python!
Steps to create a Python virtual environment with VS Code on Windows
[Python] Create a linebot to write a name and age on an image
Write a basic headless web scraping "bot" in Python with Beautiful Soup 4