The Open Event Server is based on the micro-framework Flask from its initial phases. After implementing API documentation, we decided to implement the Dredd testing in the Open Event API.
After isolating each request in Dredd testing, the real challenge is now to bind the database engine to the Dredd Hooks. And as we have been using Flask-SQLAlchemy db.Model Baseclass for building all the models and Flask, being a micro framework itself, came to our rescue as we could easily bind the database engine to the Flask app. Conventionally dredd hooks are written in pure Python, but we will running them as a self contained Flask app itself.
How to initialise this flask app in our dredd hooks. The Flask app can be initialised in the before_all hook easily as shown below:
def before_all(transaction): app = Flask(__name__) app.config.from_object('config.TestingConfig')
The database can be binded to the app as follows:
def before_all(transaction): app = Flask(__name__) app.config.from_object('config.TestingConfig') db.init_app(app) Migrate(app, db)
The challenge now is how to bind the application context when applying the database fixtures. In a normal Flask application this can be done as following:
with app.app_context(): #perform your operation
While for unit tests in python:
with app.test_request_context(): #perform tests
But as all the hooks are separate from each other, Dredd-hooks-python supports idea of a single stash list where you can store all the desired variables(a list or the name stash is not necessary).
The app and db can be added to stash as shown below:
@hooks.before_all def before_all(transaction): app = Flask(__name__) app.config.from_object('config.TestingConfig') db.init_app(app) Migrate(app, db) stash['app'] = app stash['db'] = db
These variables stored in the stash can be used efficiently as below:
@hooks.before_each def before_each(transaction): with stash['app'].app_context(): db.engine.execute("drop schema if exists public cascade") db.engine.execute("create schema public") db.create_all()
and many other such examples.
Related Links:
1. Testing Your API Documentation With Dredd: https://matthewdaly.co.uk/blog/2016/08/08/testing-your-api-documentation-with-dredd/
2. Dredd Tutorial: https://help.apiary.io/api_101/dredd-tutorial/
3. Dredd Docs: http://dredd.readthedocs.io/