[英]Flask-SQLAlchemy integration test clear database after each test with foreign key constraints
我想知道如何使用flask-sqlalchemy
和unittest
編寫快速集成測試,而不必在每個測試中創建和刪除表。 我使用 Postgres 作為我的數據庫。
現在,表分別在setUpClass
和tearDownClass
中創建和刪除,從性能的角度來看這很好。 我需要的是一種在每個單獨的測試中刪除所有數據並“重置”數據庫的方法,而無需重新創建所有表。
我得到的最接近的是這段代碼,但由於外鍵約束,它會引發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).
使您的自動增量列從頭開始。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.