Skip to main content
 首页 » 编程设计

python之是否可以仅在所有参数运行后才运行拆卸 fixture

2025年04月02日19unruledboy

例如,如果您有:

@pytest.mark.parametrize('lang', 
                         ["EN", 
                          "FR"]) 
def test_whats_hot_quick_links_are_displayed(self, lang): 
       # Do something here 

我在 conftest 中有这个拆解 fixture :

@pytest.fixture(scope='function', autouse=True) 
def teardown_function(request):     
    def execute_at_the_end(): 
        logging.info("Ending Test Case...")    
        database.clear() 
 
    request.addfinalizer(execute_at_the_end) 

那么如何让拆解函数仅在 EN 和 FR 测试运行都执行后才执行,而不是在每次参数运行后都运行此函数?

请您参考如下方法:

对于这种行为,我使用 scope=class 并用 class 包装我的测试:

import pytest 
 
@pytest.yield_fixture(scope='class') 
def teardown_after_all_params(): 
    yield 
    execute_at_the_end() 
 
@pytest.mark.usefixtures('teardown_after_all_params') 
class TestLinks: 
    @pytest.mark.parametrize('lang', ["EN", "FR"]) 
    def test_whats_hot_quick_links_are_displayed(self, lang): 
        # Do something here