Jossy
Jossy

Reputation: 1021

How should I unit test MySQL queries?

I'm building some unit tests for my Python module which interfaces with a MySQL database via SQLAlchemy. From reading around I gather the best way to do this is to create a test database that I can query as if it was the real thing. I've done this however how should I test the existing queries in the module as they currently all point at the live database?

The only idea I'd come up with was to do something like the following:

def run_query(engine, db_name='live_db')
    engine.execute(f'SELECT * FROM {db_name}.<table_name>')

I could then pass in test_db when I run the function from unittest. Is there a better way?

Upvotes: 5

Views: 5126

Answers (1)

Vivek Srivastava
Vivek Srivastava

Reputation: 207

For a scalable testing approach, I would suggest having an intermediate DAL Layer than should decide to which DB the query should be routed.

Testing with a Test Database

Upvotes: 4

Related Questions