我本人也遇到了同样的问题。这是由于在新版本的Django中如何处理事务的古怪之处,加上故意触发异常的单元测试。
我有一个单元测试,通过有意触发IntegrityError异常来检查以确保实施了唯一的列约束:
def test_constraint(self): try: # Duplicates should be prevented. models.Question.objects.create(domain=self.domain, slug='barks') self.fail('Duplicate question allowed.') except IntegrityError: pass do_more_model_stuff()在Django 1.4中,这可以正常工作。但是,在Django 1.5 / 1.6中,每个测试都包装在一个事务中,因此,如果发生异常,它将破坏该事务,直到你明确地将其回滚为止。因此,该事务中任何进一步的ORM操作(例如
my do_more_model_stuff())都将因该
django.db.transaction.TransactionManagementError异常而失败。
就像注释中提到的caio一样,解决方案是使用以下方式捕获你的异常
transaction.atomic:
from django.db import transactiondef test_constraint(self): try: # Duplicates should be prevented. with transaction.atomic(): models.Question.objects.create(domain=self.domain, slug='barks') self.fail('Duplicate question allowed.') except IntegrityError: pass这样可以防止故意抛出的异常破坏整个单元测试的事务。



