We have a database view, from now on referred to as View, that lists users we need to send an email to, and when we’ve sent the user an email we acknowledge this by updating the corresponding user in a database table (which is one of the tables the above mentioned database view is build from), from now on referred to as Table.
For my unit tests I needed to emulate this behavior. I found that by extending the database function that updates the Table to also remove the corresponding user in the View, I got a setup that’s easy to reason about and maintain. The code below shows how I extended the database client’s “record_email_sent” function with additional steps.
# File: test_email_client.py
server = Server()
original_record_email_sent = db_client.record_email_sent
def extended_record_email_sent(session, uid):
users = session.query(myDbView).all()
db_client.record_email_sent = extended_record_email_sent
During the unit test setup I used Factory Boy to populate an in-memory SQLite database with data, to be used by the tests.