如何使用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
--rerunsflag (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, orsetup.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_configurehook 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
requestfixture: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_setuporpytest_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
相关产品推荐
相关产品推荐

