python - Django PyTest - 不允许数据库访问即使使用 django_db 和装置也会出错?

标签 python django pytest pytest-django

我正在 django 中学习 PyTest,遇到了无法解决的问题。

我收到此错误:

____________________________________________________________________________________________________________ ERROR collecting prices_tool/tests/test_views.py ____________________________________________________________________________________________________________
prices_tool/tests/test_views.py:9: in <module>
    from prices_tool.views import results
prices_tool/views.py:14: in <module>
    from prices_tool.forms import SearchForm, FreeSearchForm
prices_tool/forms.py:7: in <module>
    class FreeSearchForm(forms.Form):
prices_tool/forms.py:11: in FreeSearchForm
    for make in makes:
../prices_tool-env/lib/python3.8/site-packages/django/db/models/query.py:287: in __iter__
    self._fetch_all()
../prices_tool-env/lib/python3.8/site-packages/django/db/models/query.py:1308: in _fetch_all
    self._result_cache = list(self._iterable_class(self))
../prices_tool-env/lib/python3.8/site-packages/django/db/models/query.py:111: in __iter__
    for row in compiler.results_iter(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size):
../prices_tool-env/lib/python3.8/site-packages/django/db/models/sql/compiler.py:1108: in results_iter
    results = self.execute_sql(MULTI, chunked_fetch=chunked_fetch, chunk_size=chunk_size)
../prices_tool-env/lib/python3.8/site-packages/django/db/models/sql/compiler.py:1154: in execute_sql
    cursor = self.connection.cursor()
../prices_tool-env/lib/python3.8/site-packages/django/utils/asyncio.py:26: in inner
    return func(*args, **kwargs)
../prices_tool-env/lib/python3.8/site-packages/django/db/backends/base/base.py:259: in cursor
    return self._cursor()
../prices_tool-env/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 ===========================================================================================================================
ERROR prices_tool/tests/test_views.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 !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
============================================================================================================================== 1 error in 0.47s ==============================================================================================================================

我似乎无法从views.py 导入任何方法。当然,我尝试添加 @pytest.mark.django_db 但没有成功。我用谷歌搜索了一下,发现了一些帖子,并在我的 conftest.py 中添加了以下内容:

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

当这不起作用时,我什至尝试过这个:

@pytest.fixture(scope='session')
def django_db_setup():
    settings.DATABASES['default'] = {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': 'path/to/dbfile.sqlite3',
    }

但是这些都没有修复或更改错误消息。我该如何解决这个问题?

谢谢并干杯!

最佳答案

我已经找到了解决问题的方法。我不确定这是否是明智之举,但现在这是显而易见的解决方案。

只需将有问题的 View 的导入移至@pytest.mark.django_db下方即可。

例如:

@pytest.mark.django_db
class TestViews:
    def test_view(self, client):
        path = reverse('results')
        request = RequestFactory().get(path)
        request.user = mixer.blend(User)

        context = {
            'info': info
        }

        from prices_tool.views import results
        response = results(request, context)
        assert response.status_code == 200

通过这种方式,您将避免由于某些 View 正在导入数据库内容而发生的错误。

关于python - Django PyTest - 不允许数据库访问即使使用 django_db 和装置也会出错?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66295344/

相关文章:

python - 错误 : (-215) ssize. width > 0 && ssize.height > 0 in function resize

python - Django -- User.DoesNotExist 不存在?

python - PickledObjectField (django-picklefield) 的使用示例?

django - Django REST Framework 中的嵌套 URL 模式

python - 为什么有专门的patch.dict

python - 以编程方式加载现有数据目录

python - 解析和排序 Python 字典中的键

python pylibmc 没有安装

python - 如何使用上下文变量在 djangoviews.py 文件中指定页面标题?

python-3.x - pytest argparse 测试用例不起作用