Pytest - Fixture(3) - yield遇到异常

发布时间 2023-05-26 17:11:12作者: 粥雨

Pytest - yield遇到异常

  • 如果yield前面的代码,即setup部分已经抛出异常了,则不会执行yield后面的teardown内容;

  • 如果测试用例抛出异常,yield后面的teardown内容还是会正常执行;

    test_py.py

    import pytest
    
    # 配置自动运行的fixture
    @pytest.fixture(scope="function", autouse=True)
    def open():
        # 会话前置操作 setup
        print("\n====打开浏览器====")
    
        yield
    
        # yield后面,会话后置操作 teardown
        print("****关闭浏览器****")
        
    def test_s1():
        print("\n用例test_s1:用例失败则也会执行yield后面的代码")
        assert False
        
    def test_s2():
        print("\n用例test_s2:删除")
    
    if __name__ == '__main__':
        pytest.main(['-q', 'test_py.py'])