当py.test静默挂起时该怎么办?

Hex*_*nic 22 sqlite postgresql timeout hang pytest

在使用py.test时,我有一些测试可以正常运行SQLite但在我切换到Postgresql时静默挂起.我该如何调试这样的东西?是否有"详细"模式我可以运行我的测试,或设置断点?更一般地说,当pytest无声地停止时,标准的攻击计划是什么?我已经尝试使用pytest-timeout,并使用$ py.test --timeout = 300运行测试,但测试仍然挂起,屏幕上没有任何活动

kel*_*raj 16

我遇到了与Flask和SQLAlchemy相同的SQLite/Postgres问题,类似于Gordon Fierce.但是,我的解决方案有所不同.Postgres严格关于表锁和连接,因此在拆卸时明确关闭会话连接解决了我的问题.

我的工作代码:

@pytest.yield_fixture(scope='function')
def db(app):
    # app is an instance of a flask app, _db a SQLAlchemy DB
    _db.app = app
    with app.app_context():
        _db.create_all()

    yield _db

    # Explicitly close DB connection
    _db.session.close()

    _db.drop_all()
Run Code Online (Sandbox Code Playgroud)

SQLAlchemy参考:http://docs.sqlalchemy.org/en/rel_0_8/faq.html#my-program-is-hanging-when-i-say-table-drop-metadata-drop-all

  • SQLAlchemy参考的最新位置现在在这里:http://docs.sqlalchemy.org/en/latest/faq/metadata_schema.html#my-program-is-hanging-when-i-say-table-drop-metadata -drop,所有 (3认同)

小智 8

在测试使用SQLAlchemy的Flask应用程序时,我遇到了与pytest和Postgresql类似的问题.似乎pytest很难使用postgresql的request.addfinalizer方法进行拆解.

以前我曾经:

@pytest.fixture
def db(app, request):
    def teardown():
        _db.drop_all()

    _db.app = app
    _db.create_all()

    request.addfinalizer(teardown)

    return _db
Run Code Online (Sandbox Code Playgroud)

(_db是我从extensions.py导入的SQLAlchemy的一个实例)但是如果每次调用数据库fixture时都删除数据库:

@pytest.fixture
def db(app, request):
    _db.app = app
    _db.drop_all()
    _db.create_all()
    return _db
Run Code Online (Sandbox Code Playgroud)

然后pytest在第一次测试后不会挂起.


Hex*_*nic 6

不知道代码中出现了什么问题,最好的方法是隔离失败的测试并在其中设置断点来查看。注意:我使用 pudb 而不是 pdb,因为如果您不使用 IDE,它确实是调试 python 的最佳方法。

例如,您可以在测试文件中执行以下操作:

import pudb
...

def test_create_product(session):
    pudb.set_trace()
    # Create the Product instance
    # Create a  Price instance
    # Add the Product instance to the session. 
    ...
Run Code Online (Sandbox Code Playgroud)

然后运行它

py.test -s --capture=no test_my_stuff.py
Run Code Online (Sandbox Code Playgroud)

现在,您将能够准确地看到脚本锁定的位置,并在执行的这个特定时刻检查堆栈和数据库。否则就像大海捞针一样。


gao*_*the 5

回答问题“我将如何调试类似的东西?”

  1. 使用py.test -m trace --trace运行以获取python调用的跟踪。

  2. 一种选择(适用于任何卡住的unix二进制文件)是使用附加到进程strace -p <PID>。查看它可能停留在哪个系统调用中或系统调用循环中。例如卡住调用gettimeofday

  3. 有关更详细的py.test输出,请安装pytest-sugar。pip install pytest-sugar并使用https://pypi.python.org/pypi/pytest-sugar运行测试pytest.py --verbose . . .