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

sri*_*249 8 pytest

我想在使用pytest执行所有测试后运行特定代码

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

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

谢谢!

The*_*ler 14

您可以使用具有会话范围的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()
Run Code Online (Sandbox Code Playgroud)

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

def test_foo(db_conn):
    results = db_conn.execute(...)
Run Code Online (Sandbox Code Playgroud)

  • `yield_fixture` 已弃用:https://docs.pytest.org/en/latest/yieldfixture.html。在当前版本的 pytest 中,您已经可以在用 `@pytest.fixture(scope='session', autouse=True)` 声明的常规装置中使用 `yield`。 (2认同)

ic_*_*fl2 7

Add this to your conftest.py

def pytest_sessionfinish(session, exitstatus):
    """
    Called after whole test run finished, right before
    returning the exit status to the system.
    """
    ... # Your code goes here
Run Code Online (Sandbox Code Playgroud)

converse of def pytest_sessionstart(session)