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

如何通过Python程序化指定pytest需运行的测试文件?

How to Make Pytest Run Only Specific test_*.py Files (And Programmatically Control It)

Let's break down your problem into two clear solutions: configuring pytest to target exactly the test_*.py files you've identified, and doing this programmatically with Python for your GitHub CI workflow.

1. Configuring Pytest via Command Line or Persistent Settings

Quick Command Line Fix

Since you already know how to locate the test_*.py files, you can pass them directly to pytest in one go using shell command substitution:

pytest $(find . -name "test_*.py" -type f)

This bypasses pytest's default discovery (which was stuck before your PR fix) and runs only the files you've targeted. Perfect for adding directly to your GitHub CI steps.

Persistent Configuration with pyproject.toml

To avoid repeating the command every time, add these settings to your project's pyproject.toml (or pytest.ini if you prefer that format):

[tool.pytest.ini_options]
testpaths = "."  # Start searching from the project root
python_files = ["test_*.py"]  # Only recognize files starting with `test_` as test files

Now running pytest . will automatically focus on your test_*.py files—ideal for both local development and CI, now that your infinite loop issue is resolved.

2. Programmatically Specify Test Files with Python

If you want full, scripted control over which tests run (great for custom CI logic), you can use pytest's official API to pass your list of test files directly. Here's how to integrate your existing file-finding logic:

from pathlib import Path
import pytest

def find_test_files(root: Path):
    for p in root.rglob("*"):
        if (
            not p.is_file()
            or not p.name.endswith(".py")
            or not p.name.startswith("test_")
        ):
            continue
        yield str(p)  # Convert Path objects to strings for pytest compatibility

if __name__ == "__main__":
    # Gather all matching test files
    test_files = list(find_test_files(Path(".")))
    
    # Run pytest with the selected files (add `-v` for verbose output if needed)
    exit_code = pytest.main(["-v"] + test_files)
    print(f"Pytest completed with exit code: {exit_code}")

Run this script directly, and it will execute all the test_*.py files your function locates. You can easily tweak the find_test_files function if you need to add filters (like excluding specific directories).

A Quick Note on Your Original Issue

Now that you've fixed the module-level infinite loop via PR, pytest's default discovery (pytest .) should work normally. But the methods above give you explicit control over exactly which tests run—critical for maintaining consistent, reliable CI workflows.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.28 16:44:09