【问题标题】:how to configure Postgres to work with pytest如何配置 Postgres 以使用 pytest
【发布时间】:2021-12-29 15:19:18
【问题描述】:

我使用 django 作为后端,使用 pytest 来处理我的测试。

我将我的项目数据库从 sqlite3 切换到 postgres,除了测试之外一切正常,由于某种原因,我所有的测试都失败了。

在切换之前,我可以在测试期间使用以下行访问我的数据库:

pytestmark = pytest.mark.django_db

但现在使用 Postgres 作为我的数据库后,我在所有测试中都收到此错误

UndefinedTable

The above exception was the direct cause of the following exception:

request = <SubRequest '_django_db_marker' for <Function test_logged_user_saved_recipes_url_reverse>>

    @pytest.fixture(autouse=True)
    def _django_db_marker(request):
        """Implement the django_db marker, internal to pytest-django.

        This will dynamically request the ``db``, ``transactional_db`` or
        ``django_db_reset_sequences`` fixtures as required by the django_db marker.   
        """
        marker = request.node.get_closest_marker("django_db")
        if marker:
            transaction, reset_sequences = validate_django_db(marker)
            if reset_sequences:
                request.getfixturevalue("django_db_reset_sequences")
            elif transaction:
                request.getfixturevalue("transactional_db")
            else:
>               request.getfixturevalue("db")

有人知道在使用 pytest 时访问 Postgres db 的正确方法吗? 或者也许只有在测试时才能切换到 sqlite3 db?

提前致谢

【问题讨论】:

    标签: django postgresql django-rest-framework pytest


    【解决方案1】:

    所以将此代码添加到 conftest.py 为我解决了问题

    @pytest.fixture(scope='session')
    def django_db_setup():
        settings.DATABASES['default'] = {
            'ENGINE': 'django.db.backends.postgres',
            'HOST': 'localhost',
            'NAME': 'postgres',
    }
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-10-18
      • 1970-01-01
      • 1970-01-01
      • 2021-03-16
      • 1970-01-01
      • 2018-12-23
      • 1970-01-01
      • 2015-07-09
      相关资源
      最近更新 更多