簡體   English   中英

如何清理在django-nose測試功能中所做的數據庫更改?

[英]How can I clean up database changes made in django-nose test functions?

出於多種原因,我們使用鼻子功能測試編寫測試套件。

當為我們的Django應用程序運行測試套件時,我們希望避免泄漏這些測試中的任何數據(與django.test.TestCase ),因為這會導致耦合並且難以診斷故障。

解決此問題的最明顯方法是裝飾器,我們可以將需要清理的測試包起來,但是如果其他解決方案可以為我們提供所需的解決方案,則我對此並不滿意。

我們在PostgreSQL上運行,因此特定於Postgres的解決方案就可以了。

我今天花了一些時間研究這個問題,並提出了以下裝飾器:

from functools import wraps

from django.db import transaction
from mock import patch

def rollback_db_changes(func):
    """Decorate a function so that it will be rolled back once completed."""
    @wraps(func)
    @transaction.commit_manually
    def new_f(*args, **kwargs):
        def fake_commit(using=None):
            # Don't properly commit the transaction, so we can roll it back
            transaction.set_clean(using)
        patcher = patch('django.db.transaction.commit', fake_commit)
        patcher.start()
        try:
            return func(*args, **kwargs)
        finally:
            patcher.stop()
            transaction.rollback()
    return new_f

我們執行補丁操作,以便Django測試客戶端在無法回滾之前不會關閉事務。 這允許以下測試通過:

from django.contrib.auth.models import User

@rollback_db_changes
def test_allowed_access():
    user = User.objects.create(username='test_user')
    eq_(1, User.objects.count())


@rollback_db_changes
def test_allowed_access_2():
    user = User.objects.create(username='test_user')
    eq_(1, User.objects.count())

以前,要運行的第二項測試無法創建具有重復用戶名的用戶。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM