How to test connection to Mysql database (sqlalchemy)

Asked

Viewed 420 times

0

I started learning unit tests recently, Not I know if unit testing is really the term I’m looking for, but how can I "test" the database connection ?

1 answer

0

Connection to the database is usually not a business you test in your unit tests. The Sqlalchemy library certainly has a test for it. You would test, for example, whether a given function returns the most recent database record, or whether another function actually inserts a new record into the database.

Remember that tests using databases are slower, which can discourage other programmers from running them frequently. An alternative to streamline is to replace the production database (Mysql, Postgresql...) with a Sqlite database in memory. Another alternative to greatly improve test performance is to create a service layer that abstracts interaction with the bank, so you can use a mock when you need access to the bank. As a bonus you get more uncoupled code from the persistence layer, which would make it much easier to change databases (from Mysql to Mongodb for example).

To configure Sqlalchemy to run with Sqlite and/or Mysql/Postgresql, you can do so:

import os
from sqlalchemy import create_engine

engine = create_engine(os.environ['DB_URL'])

In production the environment variable would look like this:

DB_URL="postgresql://db-user:db-password@db-host:5432/db-name"

To run the tests would look like this:

DB_URL="sqlite://"

Do not forget to rebuild the database and tables before each test run. The project Factory Alchemist is a good example of how you can run tests using Sqlalchemy database.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.