I would like to run specific code after all the tests are executed using pytest
for eg: I open up a database connection before any tests are executed. And I would like to close the connection after all the tests are executed.
How can i achieve this with py.test? Is there a fixture or some thing that can do this?
You can use a autouse fixture with session scope:
@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()
You can then also use db_conn
as an argument to a test function:
def test_foo(db_conn):
results = db_conn.execute(...)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With