Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 594
satoru Avatar asked Jul 18 '26 14:07

satoru


1 Answers

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

like image 128
hwjp Avatar answered Jul 21 '26 02:07

hwjp



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!