1
Django的TestCase類將每個測試包裝在一個事務中,並在每次測試後將該事務處理回滾爲 ,以提供測試 隔離。Django中多個數據庫的測試隔離被破壞。如何解決它?
但是,顯然只有在default
數據庫中的操作纔在事務範圍內。我有一個多路數據庫安裝程序,它將一些模型上的ORM調用引導到第二個數據庫。這意味着,在下面的例子中,test2
失敗:
class MyTestCase(TestCase):
def test1(self):
# Let's say Foo model ORM calls are routed to a different DB
foo = Foo.objects.create(...)
assert foo.is_ok()
def test2(self):
assert not Foo.objects.exists()
的最直接解決這個問題將是覆蓋MyTestCase
的tearDown
方法和人工務必刪除所有Foo
對象。但是這有點令人討厭,因爲它只是一種破解和數據庫序列(例如自動增量列),例如只有在測試套件完成並且數據庫被銷燬之後纔會被重置。
有沒有一種方法可以正確地解決這個問題,確保所有數據庫操作默認在事務內部進行,並在每次測試結束時回退?
[更新]
這裏是我的路由器:
class FooRouter(object):
def db_for_read(self, model, **hints):
if model._meta.app_label == 'foo':
return 'foo_db'
return None
def db_for_write(self, model, **hints):
if model._meta.app_label == 'foo':
return 'foo_db'
return None
def allow_migrate(self, db, app_label, model_name=None, **hints):
if app_label == 'foo':
return db == 'foo_db'
return None
哼,我不知道,我不會這麼認爲。這是一個非常基本的路由器。但無論如何,我添加了代碼,希望它有幫助。 – Ariel
'test2'失敗。對不起,我不是很明確。剛剛更新的問題更清楚。 – Ariel