使用SQLAlchemy和PostgreSQL进行瓶测试会耗尽数据库连接 [英] Flask unit tests with SQLAlchemy and PostgreSQL exhausts db connections

查看:434
本文介绍了使用SQLAlchemy和PostgreSQL进行瓶测试会耗尽数据库连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用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()
$ b $ def tearDown(self):
db.session.remove()
db.drop_all(app = self.app )
print db.engine.pool.status()
如果self.ctx不是None:
self.ctx.pop()

一些单元测试一切正常,直到:

  OperationalError:(OperationalError)致命:其余的连接槽保留给非复制超级用户连接

似乎有池中只有一个连接(db.engine.pool.status()为每个测试显示:池大小:5池中的连接:1当前溢出:-4当前检出连接:0),但不知何故应用程序永远不会断开连接。显然,每个测试用例都会创建一个新的应用程序实例,根据文档,这看起来很好。



有人知道为什么发生这种情况吗?

感谢

解决方案

添加 db.get_engine(self.app).dispose()

I'm running a suite of fairly straightforward test cases using Flask, SQLAlchemy, and PostgreSQL. Using an application factory, I've defined a base unit test class like so:

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()

All goes well for a few unit tests, up until:

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

It seems that there is only 1 connection in the pool (db.engine.pool.status() for each test shows: Pool size: 5 Connections in pool: 1 Current Overflow: -4 Current Checked out connections: 0), but somehow the app never disconnects. Clearly a new app instance is created for each test case, which seems fine according to the documentation. If I move the app creation to the module level it works fine.

Does anyone know why this is happening?

Thanks

解决方案

Add db.get_engine(self.app).dispose() after db.drop_all()

这篇关于使用SQLAlchemy和PostgreSQL进行瓶测试会耗尽数据库连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆