Write tests with Falcon, Python's lightweight web framework

What is Falcon

Python web framework https://falconframework.org/

I had to create a simple API server in Python at work, so I chose Falcon, which is fast and has no extra features.

Install

Premise that Python and PyPy are installed

pip install falcon

Easy. Currently (2016/12) v1.1

Is it a little different when you put it on your Mac? Details are official. https://falcon.readthedocs.io/en/stable/user/install.html

API sample that returns a simple json

Below is a sample API that returns json when accessing / hoge / {id} with get


# api.py

import falcon
import json

class HogeResource(object):
    def on_get(self, req, resp, id):
        """Handles GET requests"""
        resp.status = falcon.HTTP_200
        resp.body = json.dumps({ 
                      "result": true, 
                      "message": "success!",
                    })

api = falcon.API()
hoge = HogeResource()

api.add_route('/hoge/{id}', hoge)

All you have to do is pass an instance of the class that defines url and on_get (or on_post, on_put, etc.) to the instance of falcon.API () with add_route. Easy!

You can also validate using @ falcon.before


def validate(req, resp, resource, params):
    try:
        params['id'] = int(params['id'])
    except ValueError:
        raise falcon.HTTPBadRequest('Invalid ID',
                                    'ID was not valid.')
class HogeResource(object):

    @falcon.before(validate)
    def on_get(self, req, resp, id):
        #..Abbreviation..

Operation check

This time we use gunicorn as the WSGI server

When I wrote the above code with the file name api.py

pip install gunicorn
gunicorn api:main

curl localhost:8000/hoge/12345

test

Tests are also supported so I wrote it http://falcon.readthedocs.io/en/stable/api/testing.html



#api_test.py

import falcon
import falcon.testing as testing

from api import api

class TestHogeResource(testing.TestCase):

    def setUp(self):
        super(testing.TestCase, self).setUp()
        self.api = api

    def test_hoge(self):
        result = self.simulate_get("/hoge/12345")
        self.assertEqual(result.status, falcon.HTTP_200)

    def test_hoge_error(self):
        result = self.simulate_get("/hoge/moge")
        self.assertEqual(result.status, falcon.HTTP_400)

Run the test

Install and use testtools

pip install testtools
python -m testtools.run api_test.py

> Ran 2 tests in 0.001s
> OK

Recommended Posts

Write tests with Falcon, Python's lightweight web framework
Web API with Python + Falcon
Created a new corona app in Kyoto with Python's web framework Dash
Let's make a web framework with Python! (1)
Let's make a web framework with Python! (2)
Introduction to Tornado (1): Python web framework started with Tornado
Effortlessly write tests involving DB connections with DATA-DOG/go-txdb