Testing a Flask REST API using Factory Boy and an in-memory sqlite database

Testing a Flask REST API using Factory Boy and an in-memory sqlite database

I’m developing a REST API using Python’s Flask microframework. As I wanted to do test driven development to ensure good test coverage, I needed a working testing framework. After checking out a few different options, I found one that works well for my use case. I thought I’d share my setup in case it may be of help to others.

First, this is how I create the server:

Note that the function parameter is an object that contain a function name “get_database_uri”. By doing it this way, we’ll have control over which database our server will be using. For testing, we’ll pass an object with an “get_database_uri” function that return “sqlite:///:memory:”. For production, the “get_database_uri” will return connection info for a real database.

Next, the database module::

To run the application, something like this would suffice:

Now, for the interesting part. The setup below create a server with an in-memory sqlite database backend. This means that our tests will run using an in-memory database, which is both really fast and easy. We’ll use Factory Boy for populating the database with test data. I’m using the flask_testing extension, and the code is based on it’s documentation. Here’s the test code:

 

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: