Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pytest: how to skip the testcases and jump right up to cleanup if something goes wrong in setup?

Tags:

I understand that in pytest, the preferred way for setup and cleanup is to utilize yield, like

class TestSomething():
    @pytest.fixture(scope="class", autouse=True)
    def setup_cleanup(self, request):
        ...
        yield
        ...

    def test_something(self):
        ...

Problem is, if there is a failure in the setup part, before yield happens, the cleanup code would not get a chance to run.

Is it possible that, when some critical failure occurs in setup, all testcases are skipped, and the control is taken over by the cleanup (after yield in the method setup_cleanup)?

like image 689
Qiang Xu Avatar asked Jan 18 '20 00:01

Qiang Xu


People also ask

How do I skip Testcases in pytest?

The simplest way to skip a test is to mark it with the skip decorator which may be passed an optional reason . It is also possible to skip imperatively during test execution or setup by calling the pytest. skip(reason) function. This is useful when it is not possible to evaluate the skip condition during import time.

Does Setup run before every test pytest?

# Setup: fill with any logic you want , this logic will be executed before every test is actually run. In your case, you can add your assert statements that will be executed before the actual test. # Teardown : fill with any logic you want , this logic will be executed after every test.

What is verbose in pytest?

Verbosity. The -v flag controls the verbosity of pytest output in various aspects: test session progress, assertion details when tests fail, fixtures details with --fixtures , etc.

Are pytest fixtures cached?

Pytest only caches one instance of a fixture at a time, which means that when using a parametrized fixture, pytest may invoke a fixture more than once in the given scope.


1 Answers

setup_cleanup triggers the test function, but it is still a function. An exception raised in any step will prevent the rest of it to be excited.

A work around will be to use try finally. It will allow the test and teardown to run without swallowing the exception

@pytest.fixture(scope="class", autouse=True)
def setup_cleanup(self, request):
    try:
        print('Setup')
        raise Exception("Setup Exception")
        yield
    finally:
        print('Teardown')

def test_example_test(self):
    print('Test')

With the exception

Setup
Teardown

test setup failed
self = <ExampleTest.TestSomething object at 0x045E6230>
request = <SubRequest 'setup_cleanup' for <Function test_something>>

    @pytest.fixture(scope="class", autouse=True)
    def setup_cleanup(self, request):
        print()
        try:
            print('Setup')
>           raise Exception("Setup Exception")
E           Exception: Setup Exception

And without

Setup
.Test
Teardown
like image 99
Guy Avatar answered Oct 11 '22 17:10

Guy