python runtime_error ai_generated true

RuntimeError: 不允许访问数据库,请使用 "django_db" 标记或 "db" 或 "transactional_db" fixtures 来启用它。

RuntimeError: Database access not allowed, use the "django_db" mark or the "db" or "transactional_db" fixtures to enable it.

ID: python/pytest-django-fixture-db-access

其他格式: JSON · Markdown 中文 · English
80%修复率
89%置信度
0证据数
2024-04-18首次发现

版本兼容性

版本状态引入弃用备注
3.x active — — —

根因分析

pytest-django 默认阻止数据库访问。测试尝试查询数据库但没有使用 django_db 标记或 db fixture。

English

pytest-django blocks database access by default. The test tries to query the database without the django_db mark or db fixture.

generic

解决方案

  1. 98% 成功率
    @pytest.mark.django_db
    def test_create_user():
        User.objects.create(username='test')
  2. 95% 成功率
    def test_create_user(db):
        User.objects.create(username='test')
  3. 90% 成功率
    @pytest.mark.django_db(transaction=True)
    def test_transaction():
        ...

无效尝试

常见但无效的做法:

  1. 90% 失败

    The block is enforced by pytest-django, not Django settings.

  2. 95% 失败

    Breaks Django test integration and may cause other failures.

  3. 80% 失败

    pytest-django still applies the block unless marked.