【问题标题】:Flask unit tests with SQLAlchemy and PostgreSQL exhausts db connections使用 SQLAlchemy 和 PostgreSQL 进行烧瓶单元测试会耗尽数据库连接
【发布时间】:2013-08-22 03:22:11
【问题描述】:

我正在使用 Flask、SQLAlchemy 和 PostgreSQL 运行一套相当简单的测试用例。使用应用程序工厂,我定义了一个基本单元测试类,如下所示:

class BaseTestCase(unittest.TestCase):
    def setUp(self):
        self.app = create_app()
        self.app.config.from_object('app.config.test')
        self.api_base = '/api/v1'

        self.ctx = self.app.test_request_context()
        self.ctx.push()

        self.client = self.app.test_client()
        db.create_all()

    def tearDown(self):
        db.session.remove()
        db.drop_all(app=self.app)
        print db.engine.pool.status()
        if self.ctx is not None:
            self.ctx.pop()

几个单元测试一切顺利,直到:

OperationalError: (OperationalError) FATAL:  remaining connection slots are reserved for non-replication superuser connections

池中似乎只有 1 个连接(每个测试的 db.engine.pool.status() 显示:池大小:5 池中的连接:1 当前溢出:-4 当前已签出连接:0) ,但不知何故,该应用程序永远不会断开连接。显然,为每个测试用例创建了一个新的应用程序实例,根据文档,这似乎很好。如果我将应用程序创建移动到模块级别,它可以正常工作。

有人知道为什么会这样吗?

谢谢

【问题讨论】:

  • 听起来 create_app() 正在点击 create_engine() 并对其进行操作。
  • 我看到了同样的错误,但只是间歇性/不确定性。虽然 PostgreSQL 是本地的,但我的测试依赖于网络上的资源,而且这个错误似乎只在我们的网络不稳定时发生。所以可能是其他网络请求导致测试等待,同时 SQLAlchemy 连接超时。

标签: python unit-testing sqlalchemy flask flask-sqlalchemy


【解决方案1】:

在 db.drop_all() 之后添加db.get_engine(self.app).dispose()

【讨论】:

    猜你喜欢
    • 2013-08-19
    • 1970-01-01
    • 2014-03-12
    • 1970-01-01
    • 2011-12-16
    • 2018-12-16
    • 2015-03-15
    • 2019-10-28
    • 2020-11-30
    相关资源
    最近更新 更多