satoru
satoru

Reputation: 33215

How to mock database api?

Connecting database (even if it's an in-memory one) slows down my unittests (currently it took more than 5mins).

So I'm considering mocking the database api.

With the real database api, if there's any SQL syntax error or mistyped column name, it would raise exceptions.

While with a mock object, I can't think of any way to do this kind of check.

Is it possible to accomplish this with mock objects?

Upvotes: 3

Views: 2207

Answers (1)

hwjp
hwjp

Reputation: 16071

Sure! You can mock out db-api functions with your own custom functions that behave the way you want:

from sqlite3.dbapi2 import DatabaseError

mock_db_connection = Mock()

def mock_execute(query, params):
    if query == 'select firstname, lastname from student':
        return [('jim', 'brown')]
    elif query == 'select; firstname':
        raise DatabaseError('You have an error in your SQL syntax')

mock_db_connection.execute = mock_execute

# from this point, if you've patched out your db connection with the mock,
# you can make tests against connection.execute...

I'm assuming you're using the mock library.

But really - 5 minutes isn't that long. Personal preference, but I prefer to keep dependencies like this in - it helps you catch api errors. You're never going to mock out an API perfectly, and a database isn't that severe an external dependency...

Upvotes: 3

Related Questions