Django,PostgreSQL,set_autocommit和测试用例

Ben*_*ueg 3 django postgresql

看起来,无论何时transaction.set_autocommit(False)在测试用例中使用,都会得到以下堆栈跟踪:

    transaction.set_autocommit(False)
  File "/Users/btoueg/src/python/python3.3.3_django1.6.1/lib/python3.3/site-packages/django/db/transaction.py", line 133, in set_autocommit
    return get_connection(using).set_autocommit(autocommit)
  File "/Users/btoueg/src/python/python3.3.3_django1.6.1/lib/python3.3/site-packages/django/db/backends/__init__.py", line 331, in set_autocommit
    self.validate_no_atomic_block()
  File "/Users/btoueg/src/python/python3.3.3_django1.6.1/lib/python3.3/site-packages/django/db/backends/__init__.py", line 360, in validate_no_atomic_block
    "This is forbidden when an 'atomic' block is active.")
django.db.transaction.TransactionManagementError: This is forbidden when an 'atomic' block is active.
Run Code Online (Sandbox Code Playgroud)

这是正常行为吗?出于性能原因,Django的TestCase类似乎将每个测试包装在事务中。

所以问题是:如果它已经使用了事务,如何在Django Testcase中测试代码?

我正在Django 1.6和PostgreSQL 9.2中使用

Ben*_*ueg 5

Django TestCase继承自TransactionTestCase

根据该文档,其功能TestCase与基本上相同TransactionTestCase,但每个测试都包含一个事务(...)。TransactionTestCase如果您需要在测试内进行事务管理,则必须使用。

我的情况有些不同,因为我的测试类是从DRF派生的APITestCase。因此,为了在我的测试案例中检查事务管理,我做了以下工作:

from rest_framework.test import APITestCase
from django.test import TestCase

class MyTestCase(APITestCase):

    def _fixture_setup(self):
        super(TestCase, self)._fixture_setup()

    def _fixture_teardown(self):
        super(TestCase, self)._fixture_teardown()

    ...
Run Code Online (Sandbox Code Playgroud)