【问题标题】:Pytest-django: cannot delete db after testsPytest-django:测试后无法删除数据库
【发布时间】:2018-12-25 13:40:15
【问题描述】:

我有一个 Django 应用程序,我正在尝试使用 pytestpytest-django 对其进行测试。但是,很多时候,当测试完成运行时,我会收到数据库无法删除的错误:DETAIL: There is 1 other session using the database.

基本上,我可以缩小到的最小测试代码是:

@pytest.fixture
def make_bundle():
    a = MyUser.objects.create(key_id=uuid.uuid4())
    return a


class TestThings:
    def test_it(self, make_bundle):
        all_users = list(MyUser.objects.all())
        assert_that(all_users, has_length(1))

测试不时会因上述错误而失败。有什么我做错了吗?或者我该如何解决这个问题?

我使用的数据库是 PostgreSQL 9.6。

【问题讨论】:

  • 是的,pytest-django 在对正在使用的生产数据库运行测试时不能很好地与 PostgreSQL 配合使用。 我一直在阅读 Two Scoops of Django 并试图弄清楚用于测试的最佳 PostgreSQL“影子数据库”设置,但我还没有。只是想让你知道我在同一条船上!
  • @ScottSkiles 问题是它不是生产数据库,它是一个正在为测试运行创建和删除的数据库。

标签: python django database pytest pytest-django


【解决方案1】:

我将其发布为答案,因为我需要发布一大段代码并且因为它有效。但是,这对我来说看起来像是一个肮脏的黑客,如果它更好,我将非常乐意接受其他人的答案。 这是我的解决方案:基本上,将从给定数据库中踢出所有用户的原始 sql 添加到破坏数据库的方法中。并通过猴子补丁来做到这一点。为了确保在测试之前进行猴子补丁,请将其添加到根 conftest.py 文件中作为自动使用装置:

def _destroy_test_db(self, test_database_name, verbosity):
    """
    Internal implementation - remove the test db tables.
    """
    # Remove the test database to clean up after
    # ourselves. Connect to the previous database (not the test database)
    # to do so, because it's not allowed to delete a database while being
    # connected to it.
    with self.connection._nodb_connection.cursor() as cursor:
        cursor.execute(
            "SELECT pg_terminate_backend(pg_stat_activity.pid) "
            "FROM pg_stat_activity "
            "WHERE pg_stat_activity.datname = '{}' "
                "AND pid <> pg_backend_pid();".format(test_database_name)
        )

        cursor.execute("DROP DATABASE %s"
                       % self.connection.ops.quote_name(test_database_name))


@pytest.fixture(autouse=True)
def patch_db_cleanup():
    creation.BaseDatabaseCreation._destroy_test_db = _destroy_test_db

注意,踢出代码可能取决于你的数据库引擎,不同的Django版本需要monkeypatching的方法可能不同。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-12-24
    • 1970-01-01
    • 2016-12-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多