Flask-SQLAlchemy集成测试在每次测试后清除带有外键约束的数据库



我想知道如何使用flask-sqlalchemyunittest编写快速集成测试,而不必在每个测试上创建和删除表。我正在使用Postgres作为我的数据库。

现在,分别在setUpClasstearDownClass中创建和删除表,这从性能的角度来看是没问题的。我需要的是一种方法来删除所有的数据和"重置";每个单独测试中的数据库,而不需要重新创建所有表。

我得到的最接近的是这段代码,但由于外键约束,它引发了IntegrityError

def tearDown(self):
meta = db.metadata
for table in reversed(meta.sorted_tables):
db.session.execute(table.delete())
db.session.commit()

重要提示:因为我在做集成测试,我不可避免地在我的应用程序代码中击中db.session.commit,它使任何会话事务无效,所以我不能使用它作为解决方案。

试试这个:

for table in reversed(meta.sorted_tables):
db.session.execute(f"TRUNCATE {table.name} RESTART IDENTITY CASCADE;")

CASCADE在这里做到了这一点,来自postgres文档:

Automatically truncate all tables that have foreign-key references to any of the named tables, or to any tables added to the group due to CASCADE.

它告诉postgres删除所有指向截断表的行。

另一方面,RESTART IDENTITY:

Automatically restart sequences owned by columns of the truncated table(s).

使自增列从头开始。

最新更新