pytest:如果设置出现问题,如何跳过测试用例并直接跳转到清理?

Qia*_* Xu 5 python pytest

我知道在 pytest 中,设置和清理的首选方法是使用yield,例如

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

    def test_something(self):
        ...
Run Code Online (Sandbox Code Playgroud)

问题是,如果设置部分出现故障,在yield发生之前,清理代码将没有机会运行。

是否有可能,当设置中发生某些严重故障时,所有测试用例都被跳过,并且控制权由清理接管(yield在方法之后setup_cleanup)?

Guy*_*Guy 4

setup_cleanup触发测试函数,但它仍然是一个函数。任何步骤中引发的异常都会阻止其余步骤的兴奋。

解决方法是使用try finally. 它将允许测试和拆卸运行而不会吞掉异常

@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')
Run Code Online (Sandbox Code Playgroud)

有这个特例

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
Run Code Online (Sandbox Code Playgroud)

并且没有

Setup
.Test
Teardown
Run Code Online (Sandbox Code Playgroud)