RuntimeError:不允许数据库访问,请使用“ django_db”标记或“ db”或“ transactional_db”固定装置将其启用

时间:2020-09-03 06:20:45

标签: django pytest

我正在尝试运行pytest并收到此错误: RuntimeError: Database access not allowed, use the "django_db" mark, or the "db" or "transactional_db" fixtures to enable it.

我在test_models.py中进行以下测试,以检查uuid是否已添加到用户(它是自动添加的):

import pytest

from backendapps.core.models import User

pytestmark = pytest.mark.django_db

class TestUserModel():
    user = User.objects.create()

    assert user.uuid is not None

我在根目录下也有一个名为conftest.py的固件文件。

import pytest

from backendapps.core.models import Org, User

@pytest.fixture(autouse=True)
def enable_db_access(db):
    pass

然后在根目录下也有这个pytest.ini:

[pytest]
testpaths = backendapps
addopts = --ds=config.settings.local --reuse-db --create-db
python_files = tests.py test_*.py *_tests.py```

我的测试数据库设置为:

        'TEST': {
            'NAME': 'project_test_db',
        },

浏览其他文章,这是我已执行的调试步骤:

  1. 添加pytestmark = pytest.mark.django_db行-我有这个
  2. 检查数据库权限-我的用户具有超级用户权限
  3. 检查数据库上的迁移错误-我将所有迁移都迁移到了零,然后重新运行以检查迁移时是否有任何手动设置,一切都很好。

是否有任何尝试或如何清除错误的想法?

完整错误:

―――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――― ERROR collecting backendapps/core/tests/test_models.py ――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――
backendapps/core/tests/test_models.py:18: in <module>
    class TestUserModel():
backendapps/core/tests/test_models.py:27: in TestUserModel
    user = User.objects.create()
../../.local/share/virtualenvs/projectAPI-NVQT3lgx/lib/python3.8/site-packages/django/db/models/manager.py:85: in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
../../.local/share/virtualenvs/projectAPI-NVQT3lgx/lib/python3.8/site-packages/django/db/models/query.py:447: in create
    obj.save(force_insert=True, using=self.db)
../../.local/share/virtualenvs/projectAPI-NVQT3lgx/lib/python3.8/site-packages/django/db/models/base.py:753: in save
    self.save_base(using=using, force_insert=force_insert,
../../.local/share/virtualenvs/projectAPI-NVQT3lgx/lib/python3.8/site-packages/django/db/models/base.py:790: in save_base
    updated = self._save_table(
../../.local/share/virtualenvs/projectAPI-NVQT3lgx/lib/python3.8/site-packages/django/db/models/base.py:895: in _save_table
    results = self._do_insert(cls._base_manager, using, fields, returning_fields, raw)
../../.local/share/virtualenvs/projectAPI-NVQT3lgx/lib/python3.8/site-packages/django/db/models/base.py:933: in _do_insert
    return manager._insert(
../../.local/share/virtualenvs/projectAPI-NVQT3lgx/lib/python3.8/site-packages/django/db/models/manager.py:85: in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
../../.local/share/virtualenvs/projectAPI-NVQT3lgx/lib/python3.8/site-packages/django/db/models/query.py:1249: in _insert
    return query.get_compiler(using=using).execute_sql(returning_fields)
../../.local/share/virtualenvs/projectAPI-NVQT3lgx/lib/python3.8/site-packages/django/db/models/sql/compiler.py:1395: in execute_sql
    with self.connection.cursor() as cursor:
../../.local/share/virtualenvs/projectAPI-NVQT3lgx/lib/python3.8/site-packages/django/utils/asyncio.py:26: in inner
    return func(*args, **kwargs)
../../.local/share/virtualenvs/projectAPI-NVQT3lgx/lib/python3.8/site-packages/django/db/backends/base/base.py:259: in cursor
    return self._cursor()
../../.local/share/virtualenvs/projectAPI-NVQT3lgx/lib/python3.8/site-packages/django/db/backends/base/base.py:235: in _cursor
    self.ensure_connection()
E   RuntimeError: Database access not allowed, use the "django_db" mark, or the "db" or "transactional_db" fixtures to enable it.

================================================================================= short test summary info ==================================================================================
FAILED backendapps/core/tests/test_models.py - RuntimeError: Database access not allowed, use the "django_db" mark, or the "db" or "transactional_db" fixtures to enable it.
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! Interrupted: 1 error during collection !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

Results (0.49s):

2 个答案:

答案 0 :(得分:0)

来自pytest文档:

默认情况下,如果测试尝试访问数据库,则测试将失败。仅当您明确要求数据库访问时,才允许这样做。这鼓励您将需要数据库的测试保持在最低水平,这是最佳做法,因为几乎没有业务逻辑都需要数据库。此外,它可以很清楚地知道哪些代码使用数据库并捕获任何错误。

最简单的解决方案是将灯具添加为装饰器:

@pytest.mark.django_db(True)
class TestUserModel():

答案 1 :(得分:0)

我猜这个错误是由于您试图直接在测试对象上创建User而引起的。因此,代码将在数据库安装之前执行,因此会出现错误。
您可以尝试通过测试方法创建用户:

class TestUserModel:
    def test_user_uuid_is_not_none(self):
        user = User.objects.create()
        assert user.uuid is not None

或者您可以只运行一个测试功能

def test_user_uuid_is_not_none(self):
        user = User.objects.create()
        assert user.uuid is not None

如果您需要在测试中多次访问用户,请创建一个固定装置并在测试中使用它:

[conftest.py]
@pytest.fixture
def user() -> settings.AUTH_USER_MODEL:
    # return the UserFactory (factoryboy)
    return UserFactory()

[test_models.py]
import pytest
from django.contrib.auth import get_user_model

pytestmark = pytest.mark.django_db

User = get_user_model()


class TestUserModel:
    def test_user_uuid_is_not_none(self, user: User):
        assert user.uuid is not None