测试使用testing.postgresql和testing.mysqld库的备忘录
总结
testing.postgresql 及び testing.mysqld は、テストを実行する際に MySQL / PostgreSQL を自動的に起動し、テストが終了したあとに MySQL / PostgreSQL も終了するという動きをしてくれるライブラリ。
テストする際に本物の MySQL や PostgreSQL が必要な場合に使える。
DB系のテストでsqlalchemy + インメモリデータベース や mock ライブラリを使ってテストを実行しようとしていたが、あるプログラムをマルチプロセスで動かす可能性が出てきたため今回このライブラリを試してみることにした。
请参考
环境
(Note: This is the native Chinese translation of the word “environment”)
# Pythonのバージョンを確認
python --version
> Python 3.7.3
# testing.mysqldのインストール
> pip install testing.mysqld
# testing.postgresqlのインストール
> pip install testing.postgresql
# SQLAlchemyのインストール
> pip install SQLAlchemy
# psycopg2のインストール
> pip install psycopg2
# pymysqlのインストール
> pip install pymysql
预备
用Python写成如下。
如果是PostgreSQL的话
import testing.postgresql
from sqlalchemy import create_engine
import psycopg2
# Lanuch new PostgreSQL server
with testing.postgresql.Postgresql() as postgresql:
# connect to PostgreSQL
engine = create_engine(postgresql.url())
with psycopg2.connect(**postgresql.dsn()) as conn:
with conn.cursor() as cursor:
cursor.execute("CREATE TABLE hello(id int, value varchar(256))")
cursor.execute("INSERT INTO hello values(1, 'hello'), (2, 'ciao')")
conn.commit()
cursor.execute("SELECT * from hello")
rows = cursor.fetchall()
print(rows)
对于MySQL的情况来说
import testing.mysqld
from sqlalchemy import create_engine
import pymysql
# Lanuch new MySQL server
with testing.mysqld.Mysqld() as mysqld:
# connect to MySQL
engine = create_engine(mysqld.url())
with pymysql.connect(**mysqld.dsn()) as conn:
with conn.cursor() as cursor:
cursor.execute("CREATE TABLE hello(id int, value varchar(256))")
cursor.execute("INSERT INTO hello values(1, 'hello'), (2, 'ciao')")
conn.commit()
cursor.execute("SELECT * from hello")
rows = cursor.fetchall()
print(rows)
Outcome
[(1, 'hello'), (2, 'ciao')]
我之前在Docker上建立了数据库,并以类似的方式进行了测试,但是执行速度相当慢。相比之下,这个项目的执行速度很快,感觉很好。
补全
获取并安装与本地已安装的MySQL / PostgreSQL数据库版本相同的数据库版本。