Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pytest - how to link a specific setup and teardown functions to a specific test function?

Tags:

python

pytest

Similar questions have been asked but none of the answers solved my problem:

I have the following 3 functions:

def specific_setup_function():
    print("\n\nsetup_function\n\n")


def specific_teardown_function():
    print("\n\nteardown_function\n\n")


def specific_test():
    print('\n\nTEST\n\n')

How do i make pytest execute specific_test() right after specific_setup_function and right before specific_teardown_function(), regardless of how many other functions there are in my test module ?

In this example it will execute in the specified order because these are the only functions but in the more general case i want the previous code to be equivalent to the following, ALWAYS:

def test():
    specific_setup_function()
    print('\n\nTEST\n\n')
    specific_teardown_function()

So specific_test will be linked to specific_setup_function and specific_teardown_function.

Is there a way ?

like image 951
Caffeine Avatar asked Nov 26 '25 11:11

Caffeine


1 Answers

You'll want to use fixtures with a finalizer.

@pytest.fixture
def specific_fixture(request):
    print("\n\nsetup_function\n\n")
    def fin():
        print("\n\nteardown_function\n\n")
    request.addfinalizer(fin)
    return 6  # You can return a value from a fixture


def specific_test(specific_fixture):
    print('\n\nTEST: %s\n\n' % specific_fixture)
like image 143
AKX Avatar answered Nov 29 '25 01:11

AKX



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!