Learn to implement Tornado HTTP endpoints as a layer on business logic. Tune it to assist debugging, and write unit and integration tests.
At Slang Labs, we are building a platform for programmers to easily and quickly add multilingual, multimodal Voice Augmented eXperiences (VAX) to their mobile and web apps. Think of an assistant like Alexa or Siri, but running inside your app and tailored for your app.
The platform is powered by a collection of microservices. For implementing these services, we chose Tornado because it has AsyncIO APIs. It is not heavyweight. Yet, it is mature and has a number of configurations, hooks, and a nice testing framework.
This blog post covers some of the best practices we learned while building these services; how to:
As an example, we will build a CRUD microservice for an address-book using Tornado:
In case of an error (i.e. when return status code is 4xx or 5xx), the response body has JSON describing the error.
By the end of this blog post, you will know how to implement and test these endpoints.
Clone the GitHub repo and inspect the content:
The service endpoints and tests are implemented in the highlighted files in the listing above.
Setup a virtual environment, and install the dependencies from requirements.txt. Run tests as a sanity check.
The address service will be implemented in two layers:
The Service Layer exposes the function APIs for various CRUD operations to be used by the Web Framework layer.
Since the focus of this article is on the Web Framework layer, the Service layer is implemented as simple stubs.
In the AddressBookService class uses an in-memory dictionary to store the addresses. In reality, it will a lot more complicated, and using some databases. Nonetheless, it is functioning. It is enough for implementing and testing the Web Framework layer.
For implementing a service, you need to define following in Tornado:
A request handler is needed for every endpoint regex. For address-book service, there are two handlers needed:
Both of these inherit from BaseRequestHandler that has common functionalities. For example, Tornado returns HTTP response by default, but the address-book service must return JSON.
The BaseRequestHandler utilizes the following Tornado hooks:
You will see how initialize and serve_traceback are tied to the handlers in the next section.
These handlers define a set of valid endpoint URLs. A default handler can be defined to handle all invalid URLs. The prepare method is called for all HTTP methods.
All request handlers need to be tied into a tornado.web.Application. That requires the following:
The make_addrservice_app function creates an AddressBookService object, uses it to make tornado.web.Application, and then returns both the service and app.
In the debug mode, serve_traceback is set True. When an exception happens, the error returned to the client also has the exception string. We have found this very useful in debugging. Without requiring to scan through server logs and to attach a debugger to the server, the exception string at the client offers good pointers to the cause.
The application (that has routes to various request handlers) is started as an HTTP server with following steps:
When the server is stopped, the server is stopped and all pending requests are completed:
Let’s run the server and try some requests.
There is no /xyz endpoint, so it returns 404:
Add an address entry, the returned location is the id to query later:
Use the id in the Location field in the previous request to query it:
Let’s change the name:
Manual testing is tedious and error-prone. Tornado provides testing infrastructure. It starts the HTTP server and runs the tests. It does necessary plumbing to route the HTTP requests to the server it started.
Test classes should inherit from AsyncHTTPTestCase, and implement a get_app method, which returns the tornado.web.Application. It is similar to what is done in server.py. Code duplication can be kept at a minimum by reusing make_addrservice_app function in get_app.
Tornado creates a new IOLoop for each test. When it is not appropriate to use a new loop, you should override get_new_ioloop method.
For address book service, except default handler, all handlers use the service (business logic) module. That module has only simple stubs in this blog post, but in reality, it will be way more complex. So only default handler is independent and qualifies for the unit tests. All other handlers should be covered in the integration tests (next section).
The whole life cycle of an address entry tested manually earlier can be automated as integration tests. It will be a lot easier and faster to run all those tests in seconds every time you make a code change.
Let’s run these tests:
Let’s check code coverage:
As you can see, it is pretty good coverage.
Notice that addrservice/tornado/server.py was omitted from code coverage. It has the code that runs the HTTP server, but Tornado test infra has its own mechanism of running the HTTP server. This is the only file that can not be covered by unit and integration tests. Including it will skew the overall coverage metrics.
In this article, you learned about how to put together a microservice and tests using Tornado: