Mocking SQLAlchemy models in Python

Mocking SQLAlchemy models in Python

I’m developing an API using Python’s Flask framework. The API uses SQLAlchemy, which means that database rows are made available as regular Python classes (referred to as database models) in my Python code.
One of my models looks something like this:

My Data Access Object (DAO) for communicating with the database models looks like this:

While writing tests for the API, I wanted to mock out the database models, so that my tests wouldn’t depend on an actual database. For this task, I found “factory boy” and Python’s own “unittest” to fit my needs quite well. The following is an extract from my test. Pay close attention to the mock – the class I’m mocking reside in “server.models.users”, but I’m mocking the DAO’s reference to it by mocking “server.daos.users.View_users”.


Leave a Reply

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

%d bloggers like this: