运行测试时的TransactionManagementError,但无法找到原子块

时间:2015-10-13 11:10:14

标签: django unit-testing django-cms

我遇到运行测试的问题,我在开始运行测试后立即收到TransactionManagementError。我尝试了各种不同的测试,他们都遇到了这个错误:

.ve/lib/python2.7/site-packages/django/test/testcases.py:189: in __call__
    self._post_teardown()
.ve/lib/python2.7/site-packages/cms/test_utils/testcases.py:97: in _post_teardown
    menu_pool.clear()
.ve/lib/python2.7/site-packages/menus/menu_pool.py:156: in clear
    if to_be_deleted:
.ve/lib/python2.7/site-packages/django/db/models/query.py:145: in __nonzero__
    self._fetch_all()
.ve/lib/python2.7/site-packages/django/db/models/query.py:966: in _fetch_all
    self._result_cache = list(self.iterator())
.ve/lib/python2.7/site-packages/django/db/models/query.py:1202: in iterator
    for row in self.query.get_compiler(self.db).results_iter():
.ve/lib/python2.7/site-packages/django/db/models/sql/compiler.py:701: in results_iter
    for rows in self.execute_sql(MULTI):
.ve/lib/python2.7/site-packages/django/db/models/sql/compiler.py:787: in execute_sql
    cursor.execute(sql, params)
.ve/lib/python2.7/site-packages/django/db/backends/utils.py:59: in execute
    self.db.validate_no_broken_transaction()
.ve/lib/python2.7/site-packages/django/db/backends/__init__.py:386: in validate_no_broken_transaction
    "An error occurred in the current transaction. You can't "
E   TransactionManagementError: An error occurred in the current transaction. You can't execute queries until the end of the 'atomic' block.

你可以看到堆栈跟踪在_post_teardown方法中,所以我猜问题是在这个测试之前的某个地方。我已经查看了堆栈跟踪的每一行上的代码,并且无法在代码的这些位中看到正在启动的事务,所以它必须在此之前发生,但我如何找到哪里?< / p>

考虑到我是单独测试应用A还是单独测试应用B,我不确定如何跟踪相关代码。欢迎任何建议。

我正在使用Django 1.7,Django CMS 3.1(其中包含上面堆栈跟踪中的菜单应用程序)和pytest作为测试运行程序。我使用--create-db参数进行此测试,以确保数据库干净地重新创建。

1 个答案:

答案 0 :(得分:2)

我通过回滚提交来跟踪更改,直到测试通过并比较更改的内容。事实证明,它正在添加一个post保存信号处理程序来自动创建一个链接模型,该模型是停止测试传递的更改。我有一个User模型,以及一个指向User模型的OneToOneField的UserProfile模型。

问题是测试通常是手动创建UserProfile。一旦添加了post_save处理程序,这将导致手动创建的UserProfile的重复ID错误,因为自动创建的UserProfile已经使用了该id。我猜这导致单元测试周围的事务严重失败,导致所有其他错误。

但是原始错误隐藏在关于交易的许多错误的噪音中。

相关问题