django - RuntimeError : Database access not allowed, 使用 "django_db"标记,或 "db"或 "transactional_db"设备来启用它

标签 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 的 fixture 文件。
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',
        },
通过其他帖子,以下是我采取的调试步骤:
  • 添加 pytestmark = pytest.mark.django_db line - 我有这个
  • 检查数据库权限 - 我的用户具有 super 用户权限
  • 检查数据库上的迁移错误 - 我将所有迁移迁移到零并重新运行它们以检查迁移时是否有任何手动设置,一切都很好。

  • 关于尝试什么或如何获得更清晰的错误的任何想法?
    完整错误:
    ―――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――― 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):
    

    最佳答案

    我猜这个错误是由于您试图直接在测试对象上创建用户。因此,代码将在设置数据库之前执行,因此会出现错误。
    您可以尝试在测试方法中创建用户:

    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
    

    关于django - RuntimeError : Database access not allowed, 使用 "django_db"标记,或 "db"或 "transactional_db"设备来启用它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63717925/

    相关文章:

    python - 属性错误 : 'tuple' object has no attribute 'rsplit' Django

    django - 在 Django 管理中限制 ManyToMany MultipleSelect 的查询集

    python - 如何在 Python 中对需要事件 Click 上下文的函数进行单元测试

    django - 在 django 过滤器后端传递模型的所有字段

    python - 如何检查 virtualenv 是否是用 '--no-site-packages' 创建的?

    django - 如何使用 Amazon S3 和 Boto 在 Django 中仅为经过身份验证的用户提供上传的文件?

    在 Pytest 上找不到 Python 包

    python - 访问 Travis-CI 上的剪贴板

    python - 是否可以使用 pytest 测试 while True 循环(我尝试超时)?

    python - 如何在命令行中将环境变量传递给 pytest 以测试函数