You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用pytest-rerunfailures识别测试重跑模式及判断当前测试是否为首次运行?

Hey there! Let's tackle your two questions about pytest-rerunfailures one by one:

1. How to identify if pytest-rerunfailures' rerun mode is enabled

There are a couple of straightforward ways to check if rerun mode is active:

  • Check command line arguments: Look for the --reruns flag (e.g., pytest --reruns 3) or --reruns-delay (to add a wait between retries) in your test execution command. If either is present, rerun mode is enabled.
  • Check pytest configuration files: If you've set up reruns in a config file like pytest.ini, tox.ini, or setup.cfg (e.g., addopts = --reruns 2), that means rerun mode is enabled by default for all test runs.
  • Programmatically check via pytest hooks: You can use the pytest_configure hook to inspect the pytest config object and confirm if reruns are enabled:
    def pytest_configure(config):
        rerun_limit = config.getoption("--reruns")
        if rerun_limit and int(rerun_limit) > 0:
            print(f"Rerun mode is active: up to {rerun_limit} retries allowed")
    
2. How to determine if a test is running for the first time or in rerun mode

pytest-rerunfailures adds a rerun_count attribute to each test item (the node representing your test) that tracks how many times the test has been retried. Here's how to use it:

  • Inside a test function using the request fixture:
    def test_flaky_feature(request):
        # Get the rerun count, default to 0 if the attribute doesn't exist
        current_rerun = getattr(request.node, "rerun_count", 0)
        
        if current_rerun == 0:
            print("This is the first execution of the test")
        else:
            print(f"This is the {current_rerun}th rerun of the test")
        
        # Your test logic here
        assert some_flaky_function() == expected_result
    
  • In pytest hooks (like pytest_runtest_setup or pytest_runtest_teardown):
    def pytest_runtest_setup(item):
        rerun_count = getattr(item, "rerun_count", 0)
        if rerun_count > 0:
            print(f"Preparing to rerun test {item.name} (attempt {rerun_count + 1})")
    

A quick note: The rerun_count starts at 0 for the first run, increments by 1 each time the test is retried. Using getattr with a default value is safe in case the plugin isn't enabled (so you won't get an AttributeError).

内容的提问来源于stack exchange,提问作者Aviv Monika

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.28 14:52:29