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

如何在pytest.ini中配置不同测试路径实现分组执行测试

Absolutely! You can totally set this up so you don’t have to type out all those directory paths every time. Here’s a straightforward, maintainable way to make your desired commands work using a conftest.py file (pytest’s go-to for customizing behavior):

Step 1: Add/Update conftest.py in your project root

This script will intercept the xx, yy, and all keywords you pass to pytest and swap them out for the corresponding test directories. Drop this code in:

def pytest_cmdline_preparse(config, args):
    # Define your test directory groups once, easy to update later
    unit_dirs = ["unitA", "unitB", "unitC"]
    regression_dirs = ["regressionA", "regressionB", "regressionC"]
    all_dirs = unit_dirs + regression_dirs

    # Check if the first argument is one of our custom group names
    if args and args[0] in ["xx", "yy", "all"]:
        selected_group = args.pop(0)
        # Replace the keyword with the actual directories
        if selected_group == "xx":
            args[:0] = unit_dirs
        elif selected_group == "yy":
            args[:0] = regression_dirs
        elif selected_group == "all":
            args[:0] = all_dirs

Step 2: Keep your existing pytest.ini (optional)

You can leave your current pytest.ini as-is to keep the default behavior (running unitA and unitB when you just run pytest without any arguments):

[pytest]
testpaths = unitA unitB

Step 3: Run tests with your desired commands

Now you’re good to go with exactly the workflow you wanted:

  • Run unit tests: pytest xx
  • Run regression tests: pytest yy
  • Run all tests: pytest all

Quick breakdown of how this works

The pytest_cmdline_preparse hook runs right before pytest processes your command-line arguments. It checks if you passed xx, yy, or all first, removes that keyword, and inserts the list of directories you defined. Pytest then runs like you’d manually typed every directory name—no extra effort needed.

Bonus: Add help text (optional)

If you want to make it clearer what these keywords do for anyone else using your project, add this to your conftest.py to include help text in pytest --help:

def pytest_addoption(parser):
    parser.addoption(
        "test_group",
        nargs="?",
        choices=["xx", "yy", "all"],
        help="Pick a test group: xx (unit tests), yy (regression tests), all (all tests)"
    )

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 04:26:40