[TIP] Mocking a cursor for use with Psycopg2

Tiemo Kieft t.kieft at infinitesimal.nl
Fri Mar 14 08:07:42 PDT 2014

The following was sent to me instead of the mailing list:

> I suppose. So I could just have the setup function generate a sqllite database?

Ideally you’d have each unit test running in a clean environment, which means creating a new database per test case.

I use SQLAlchemy to talk to PG, personally I try to avoid DB calls in unit tests whenever possible, but mocking a whole SA session is a bit much. In cases where I can’t avoid hitting the DB without mocking the entire SA session I just create a fresh sqlite in-memory DB for each test.

For these cases I have a DatabaseTestCaseMixin that creates a sqlite DB, including schema in it’s setUp(), this ensures a clean DB for each test case, it will however make your tests slower.

- Tiemo

More information about the testing-in-python mailing list