最好的解决方案是使用testing.postgresql
模块。这将在用户空间中启动一个数据库,然后在运行结束时再次将其删除。您可以根据需要的持久性setUp
,将以下内容放入unittest套件中-setUpClass
或中setUpModule
-:
import testing.postgresql
def setUp(self):
self.postgresql = testing.postgresql.Postgresql(port=7654)
# Get the url to connect to with psycopg2 or equivalent
print(self.postgresql.url())
def tearDown(self):
self.postgresql.stop()
如果您希望数据库在测试之间/之后保持不变,则可以使用base_dir
设置目录的选项运行该数据库-这样可以防止数据库在关机后被删除:
name = "testdb"
port = "5678"
path = "/tmp/my_test_db"
testing.postgresql.Postgresql(name=name, port=port, base_dir=path)
在测试之外,它还可以用作上下文管理器,在其中,当退出with块时,它将自动清理和关闭:
with testing.postgresql.Postgresql(port=7654) as psql:
# do something here