[TIP] Mocking a cursor for use with Psycopg2

Chris Withers chris at simplistix.co.uk
Fri Mar 21 11:16:09 PDT 2014

On 14/03/2014 15:07, Tiemo Kieft wrote:
> 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.

Unless you deploy on sqlite in production, you have a real risk of 
different behaviour in yours tests than in your real environment.

> 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.

My approach is to have a clean application abstraction where all unit 
tests run inside a transaction that is rolled back at the end of the test.

Each run does create a clean database with requisite schema, but that is 
only done once per run.



Simplistix - Content Management, Batch Processing & Python Consulting
             - http://www.simplistix.co.uk

More information about the testing-in-python mailing list