Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run specific code after all tests are executed?

Tags:

pytest

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?

like image 776
sridhar249 Avatar asked Jan 21 '16 18:01

sridhar249


1 Answers

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(...)
like image 182
The Compiler Avatar answered Nov 04 '22 20:11

The Compiler