I was writing test code for a Python project, and needed to spy on the functions of one of the main object’s, called “server”, object instances called “rest_client”. By simply replacing the “rest_client” instance with a mock that passes the actual call to the wrapped object, I’m able to execute the production code of “rest_client” while later on making assertions.
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:
# File: server/server.py
from database import db
connexion_app = connexion.FlaskApp(__name__) # For stock Flask users, use something like "app <span class="pl-k">=</span> Flask(<span class="pl-c1">__name__</span>)" instead
app = connexion_app.app
app.config['SQLALCHEMY_DATABASE_URI'] = config.get_database_uri()
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False