나는이 오늘보고 약간의 시간을 보냈어요, 다음과 같은 장식과 함께 올라와있다 : 장고 테스트 클라이언트없이 트랜잭션을 종료하지 않도록
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
우리는 패치를 수행 우리는 그것을 되돌릴 수 있습니다. 중복 된 사용자 이름을 가진 사용자를 만들 수 없습니다 실행
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())
이전에 두 번째 테스트를이 다음과 같은 테스트를 통과 할 수 있습니다.
django가 각 테스트 실행을 위해 데이터베이스를 자동으로 떼어 내면 분리 된 테스트 환경이 생성됩니다. – dm03514
@ dm03514 잠시 파고 들기 직전에 장고비 테스트 기능이 더 일반적인 경우가 아니라는 것을 알았습니다. 원래 질문을 초안으로 작성했습니다. –