pytest:如何在执行所有测试后运行特定代码?

时间:2016-01-21 18:14:45

标签: pytest

我想在使用pytest

执行所有测试后运行特定代码

例如:我在执行任何测试之前打开数据库连接。我想在执行所有测试后关闭连接。

我如何用py.test实现这一目标?是否有夹具或某些东西可以做到这一点?

谢谢!

1 个答案:

答案 0 :(得分:8)

您可以使用具有会话范围的autouse fixture

@pytest.fixture(scope='session', autouse=True)
def db_conn():
    # Will be executed before the first test
    conn = db.connect()
    yield conn
    # Will be executed after the last test
    conn.disconnect()

然后,您还可以使用db_conn作为测试函数的参数:

def test_foo(db_conn):
    results = db_conn.execute(...)
相关问题