How to run a method before all tests in all classes?

pytest, python, selenium

Solution

You might want to use a session-scoped "autouse" fixture:

# content of conftest.py or a tests file (e.g. in your tests or root directory)

@pytest.fixture(scope="session", autouse=True)
def do_something(request):
    # prepare something ahead of all tests
    request.addfinalizer(finalizer_function)

This will run ahead of all tests. The finalizer will be called after the last test finished.

Problem

I'm writing selenium tests, with a set of classes, each class containing several tests. Each class currently opens and then closes Firefox, which has two consequences: - super slow, opening firefox takes longer than running the test in a class... - crashes, because after firefox has been closed, trying to reopen it really quickly, from selenium, results in an 'Error 54' I could solve the error 54, probably, by adding a sleep, but it would still be super slow. So, what I'd like to do is reuse the same Firefox instances across all test classes. Which means I need to run a method before all test classes, and another method after all test classes. So, 'setup_class' and 'teardown_class' are not sufficient.

Original source

Related problems