Pytest how to ignore the setup class in an autouse test fixture

186 views Asked by At

The below code runs after every function including the setup class. I dont create an instance before the actual tests so i don't want it to run after the setup_class method. Can you advise if i can change the signature to not run after setup class

@pytest.fixture(autouse=True)
def teardown_module(self):
    Log.test_teardown("Deleting instance")
    Utils.compute_utils().delete_instance_and_wait_for_state(
        TestAutoValidateCpuAlignment.instance_id, teardown=True)
1

There are 1 answers

2
Ilya On

This can be done more efficiently using yield. Combine the teardown_module and the create_module fixtures into one that does both and yield between the operations. This way it will create your instance, execute the tests and then tear it down.

@pytest.fixture(autouse=True)
def instance_module(self):
    try:
        Log.test_teardown("Creating instance")
        Utils.compute_utils().create_instance_and_wait_for_state(
            TestAutoValidateCpuAlignment.instance_id, teardown=True)
    
        yield
    except Exception as e:
        # do something with the exception
    finally:
        Log.test_teardown("Deleting instance")
        Utils.compute_utils().delete_instance_and_wait_for_state(
            TestAutoValidateCpuAlignment.instance_id, teardown=True)