wisenickel
wisenickel

Reputation: 394

PyTest - Specify cleanup tests in conftest.py

I am testing a service that requires starting and shutting down a gRPC server via a client's request. In my set of integration tests, I need to specify a set of pre-test and post-test actions that should happen before any given test is run within the set. Ideally, I would like to keep these pre/post-test methods in conftest.py or organize them into their own class within separate module.

I can specify the first test that should run (test that starts the server) by doing the following within conftest.py:

@pytest.fixture(scope="session", autouse=True)
def test_start_server():
    # code to start server

The problem is that when I execute another test module only the test_start_server function is executed and not the subsequent test_shutdown_request function further down in the file:

def test_shutdown_request():
    # code to shutdown server

Is there any way to specify the last test (post-test action) to be run?
If possible, I don't want to include any 3rd party dependencies or plugins, as my project already has enough.

Upvotes: 0

Views: 363

Answers (1)

Kapustin Alexander
Kapustin Alexander

Reputation: 64

I think you should use yield in your fixtures https://docs.pytest.org/en/6.2.x/fixture.html#yield-fixtures-recommended

@pytest.fixture(scope="session", autouse=True)
def server():
    # code to start server
    yield
    # code to stop server

def test_some():
    # some tests

def test_more():
    # some tests

This code create server once for session and shutdown your server after all tests.

Upvotes: 1

Related Questions