![](/img/trans.png)
[英]pytest: parametrize class based tests with fixtures (pytest-django)
[英]Pytest-django: cannot delete db after tests
我有一個Django應用程序,正在嘗試使用pytest
和pytest-django
對其進行測試。 但是,很多時候,當測試完成運行時,我會收到以下錯誤消息:數據庫刪除失敗: DETAIL: There is 1 other session using the database.
基本上,我可以縮小范圍的最低測試代碼是:
@pytest.fixture
def make_bundle():
a = MyUser.objects.create(key_id=uuid.uuid4())
return a
class TestThings:
def test_it(self, make_bundle):
all_users = list(MyUser.objects.all())
assert_that(all_users, has_length(1))
每一次測試都會因上述錯誤而失敗。 我做錯什么了嗎? 或者我該如何解決?
我正在使用的數據庫是PostgreSQL 9.6。
我將其發布為答案,因為我需要發布大量代碼,並且這可行。 但是,對我來說,這似乎是一個骯臟的技巧,如果更好,我將非常樂意接受其他人的回答。 這是我的解決方案:基本上,將可將所有用戶從給定db中踢出的原始sql添加到銷毀db的方法中。 並通過monkeypatching做到這一點。 為了確保在測試之前進行monkeypatching,請將其作為自動使用的夾具添加到根conftest.py
文件中:
def _destroy_test_db(self, test_database_name, verbosity):
"""
Internal implementation - remove the test db tables.
"""
# Remove the test database to clean up after
# ourselves. Connect to the previous database (not the test database)
# to do so, because it's not allowed to delete a database while being
# connected to it.
with self.connection._nodb_connection.cursor() as cursor:
cursor.execute(
"SELECT pg_terminate_backend(pg_stat_activity.pid) "
"FROM pg_stat_activity "
"WHERE pg_stat_activity.datname = '{}' "
"AND pid <> pg_backend_pid();".format(test_database_name)
)
cursor.execute("DROP DATABASE %s"
% self.connection.ops.quote_name(test_database_name))
@pytest.fixture(autouse=True)
def patch_db_cleanup():
creation.BaseDatabaseCreation._destroy_test_db = _destroy_test_db
請注意,啟動代碼可能取決於您的數據庫引擎,並且在不同的Django版本中,需要進行猴子修補的方法可能有所不同。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.