Chapter 9. Testing with SQLAlchemy ORM
Most testing inside of applications consists of both unit and functional tests; however, with SQLAlchemy, it can be a lot of work to correctly mock out a query statement or a model for unit testing. That work often does not truly lead to much gain over testing against a database during the functional test. This leads people to make wrapper functions for their queries that they can easily mock out during unit tests, or to just test against a database in both their unit and function tests. I personally like to use small wrapper functions when possible or—if that doesn’t make sense for some reason or I’m in legacy code—mock it out.
This chapter covers how to perform functional tests against a database, and how to mock out SQLAlchemy queries and connections.
Testing with a Test Database
For our example application, we are going to have an app.py file that contains our application logic, and a db.py file that contains our data models and session. These files can be found in the CH10/ folder of this book’s example code.
How an application is structured is an implementation detail that can have quite an effect on how you need to do your testing. In db.py, you can see that our database is set up via the DataAccessLayer
class. We’re using this data access class to enable us to initialize a database engine and session whenever we like. You’ll see this pattern commonly used in web frameworks when coupled with SQLAlchemy. The DataAccessLayer
class is ...
Get Essential SQLAlchemy, 2nd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.