简体   繁体   中英

Database testing in python, postgresql

How do you unit test your python DAL that is using postgresql.

In sqlite you could create in-memory database for every test but this cannot be done for postgresql.

I want a library that could be used to setup a database and clean it once the test is done.

I am using Sqlalchemy as my ORM.

pg_tmp(1) is a utility intended to make this task easy. Here is how you might start up a new connection with SQLAlchemy:

from subprocess import check_output
from sqlalchemy import create_engine

url = check_output(['pg_tmp', '-t'])
engine = create_engine(url)

This will spin up a new database that is automatically destroyed in 60 seconds. If a connection is open pg_tmp will wait until all active connections are closed.

你试过testing.postgresql吗?

您可以使用nose编写测试,然后使用SQLAlchemy在setup / teardown方法中创建和清理测试数据库。

There's QuickPiggy too, which is capable of cleaning up after itself. From the docs:

A makeshift PostgresSQL instance can be obtained quite easily:

pig = quickpiggy.Piggy(volatile=True, create_db='somedb')

conn = psycopg2.connect(pig.dsnstring())

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM