Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

testing python applications that use mysql

I want to write some unittests for an application that uses MySQL. However, I do not want to connect to a real mysql database, but rather to a temporary one that doesn't require any SQL server at all.

Any library (I could not find anything on google)? Any design pattern? Note that DIP doesn't work since I will still have to test the injected class.

like image 578
Alexandru Avatar asked Jul 06 '09 17:07

Alexandru


People also ask

Can Python interact with MySQL?

MySQL server will provide all the services required for handling your database. Once the server is up and running, you can connect your Python application with it using MySQL Connector/Python.

How do I know if Python is connected to MySQL?

The is_connected() is the method of the MySQLConnection class through which we can verify is our Python application connected to MySQL.

Can I use MySQL in Pycharm?

Open the database tool window View -> Tool Windows -> Database> and open the dialog called Data Sources and Dialog. Now, select MySQL database for adding a new data source.

Can I use MySQL in Jupyter notebook?

In this post you will learn two easy ways to use Python and SQL from the Jupyter notebooks interface and create SQL queries with a few lines of code. These two methods are almost database-agnostic, so you can use them for any SQL database of your choice: MySQL, Postgres, Snowflake, MariaDB, Azure, etc.


2 Answers

There isn't a good way to do that. You want to run your queries against a real MySQL server, otherwise you don't know if they will work or not.

However, that doesn't mean you have to run them against a production server. We have scripts that create a Unit Test database, and then tear it down once the unit tests have run. That way we don't have to maintain a static test database, but we still get to test against the real server.

like image 115
Christopher Avatar answered Nov 13 '22 04:11

Christopher


I've used python-mock and mox for such purposes (extremely lightweight tests that absolutely cannot require ANY SQL server), but for more extensive/in-depth testing, starting and populating a local instance of MySQL isn't too bad either.

Unfortunately SQLite's SQL dialect and MySQL's differ enough that trying to use the former for tests is somewhat impractical, unless you're using some ORM (Django, SQLObject, SQLAlchemy, ...) that can hide the dialect differences.

like image 28
Alex Martelli Avatar answered Nov 13 '22 04:11

Alex Martelli