python - 带有回滚仿真的 Django TransactionTestCase

标签 python django postgresql testcase django-testing

我将 Django 1.7.7 与 python 2.7.6 和 Postgres 一起用作数据库,并且我遇到了 TransactionTestCase 问题。在我的迁移中,我有两个 datamigrations,我希望它们在测试期间可用,所以我将 serialized_rollback = True 添加到我的测试用例 ( https://docs.djangoproject.com/en/1.7/topics/testing/overview/#test-case-serialized-rollback )。

测试用例的第一个测试没问题,但随后 django 提示 IntegrityError:

IntegrityError: duplicate key value violates unique constraint "django_content_type_app_label_6032a1f08b99c274_uniq"
DETAIL:  Key (app_label, model)=(admin, logentry) already exists.

我设法运行测试并通过将以下内容添加到我的设置 ( https://docs.djangoproject.com/en/1.7/ref/settings/#std:setting-TEST_NON_SERIALIZED_APPS ) 来避免此错误:

TEST_NON_SERIALIZED_APPS = ['django.contrib.contenttypes',
                            'django.contrib.auth']

但我想知道为什么需要这个?这是回滚中的错误还是我这边的问题?

最佳答案

这个问题在django related ticket中有很好的解释:https://code.djangoproject.com/ticket/23727

从那里引用:

When using a TransactionTestCase with serialized_rollback=True, after creating the database and running its migrations (along with emitting the post_migrate signal), the contents of the database are serialized to _test_serialized_contents.

After the first test case, _fixture_teardown() would flush the tables but then the post_migrate signal would be emitted and new rows (with new PKs) would be created in the django_content_type table.

Then in any subsequent test cases in a suite, _fixture_setup() attempts to deserialize the content of _test_serialized_contents, but these rows are identical to the rows already in the database except for their PKs.

This causes an IntegrityError due to the unique constraint in the django_content_type table.

补丁已创建/发布,但仅适用于 Django 1.9.x。

对于以前的版本,我猜你应该继续使用 TEST_NON_SERIALIZED_APPS...

关于python - 带有回滚仿真的 Django TransactionTestCase,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29226869/

相关文章:

django - 连接到 PostgreSQL 时 Django 中的 "psycopg2"有什么用

google-app-engine - 连接 GWT 和 PostgreSQL

python - 长文本作为 Python 中的字符串

Django根据不工作的类别计算类似的帖子

python - 按相关对象的第一个实例对对象进行排序,Django

javascript - 如何在django网站中将D3图保存为图像?

arrays - 将 PostgreSQL 数组数据类型解析为数组到 perl

python - 将 Unicode 流重新编码为 Ascii 忽略错误

python - write()之后文件大小未更新?

python - Gunicorn 未在 AWS EC2 上创建 .sock 文件