如何通过Python程序化指定pytest需运行的测试文件?
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

