求助:使用@pytest.mark.run排序测试用例无效,求解决或替代方案
@pytest.mark.run(order=...) Not Working Hey there! I’ve run into this exact issue before, so let me break down what’s going wrong and how to fix it quickly.
Why the @pytest.mark.run(order=...) isn’t working
The run(order=...) mark isn’t built into core pytest—you’re missing the plugin that adds this functionality! A basic pip install pytest only gets you the core framework, not extra features like test ordering.
Step-by-Step Solution
Install the right plugin
The modern, maintained plugin for test ordering ispytest-order(the olderpytest-orderingis no longer updated). Install it with:pip install pytest-orderUpdate your test decorator
The plugin uses a slightly different syntax than what you tried. Replace@pytest.mark.run(order=2)with@pytest.mark.order(2)(norunwrapper needed). Here’s a working example:import pytest @pytest.mark.order(1) def test_setup(): print("Running first test") assert True @pytest.mark.order(2) def test_main_logic(): print("Running second test") assert TrueVerify it works
Run your tests with verbose mode to confirm the order:pytest -vYou’ll see your tests execute in the exact order specified by the
ordernumbers.
Alternative Options (No Plugin Needed)
If you don’t want to add an extra plugin, you have two simple workarounds:
- Name your tests sequentially: Pytest runs tests in alphanumeric order by default. Name your tests like
test_01_login,test_02_create_user,test_03_logoutto enforce order. - Use pytest’s dependency features: If you need tests to run only after another passes, use
@pytest.mark.dependency(built into pytest since version 4.0) to define dependencies instead of strict ordering.
内容的提问来源于stack exchange,提问作者Shibu

