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

求助:使用@pytest.mark.run排序测试用例无效,求解决或替代方案

Fixing Pytest Test Ordering with @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

  1. Install the right plugin
    The modern, maintained plugin for test ordering is pytest-order (the older pytest-ordering is no longer updated). Install it with:

    pip install pytest-order
    
  2. Update 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) (no run wrapper 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 True
    
  3. Verify it works
    Run your tests with verbose mode to confirm the order:

    pytest -v
    

    You’ll see your tests execute in the exact order specified by the order numbers.

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_logout to 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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 03:45:16