pytest无法自动识别_test*测试文件问题求助
Hey there, let's work through why pytest isn't picking up your *_test.py files automatically, even though running them directly works. Here are the most common fixes to check step by step:
Double-check file naming and working directory
First, confirm your files match pytest's default discovery patterns: eithertest_*.py(starts withtest) or*_test.py(ends withtest). Also, make sure you're running thepytestcommand from the right folder—if your tests live in a subdirectory liketests/, you might need to runpytest tests/instead of justpytestfrom the parent directory.Check for conflicting configuration files
Look for files likepytest.ini,setup.cfg, ortox.iniin your project. These can override pytest's default discovery rules. For example, if there's a line likepython_files = test_*.py(missing the*_test.pypattern), that's why your files aren't being found. Update it to include both patterns:[pytest] python_files = test_*.py *_test.pyVerify pytest isn't ignoring your directory
Pytest automatically skips directories like__pycache__,venv,node_modules, or any folder starting with a dot. If your tests are in one of these, move them to a valid folder. Also check.gitignoreor.pytestignorefiles—custom ignore rules here might be blocking your test files.Force discovery with explicit flags
To rule out configuration issues, try forcing pytest to use your desired pattern directly from the command line:pytest --python-files "*_test.py"If this works, it means your default configuration was overriding the expected discovery pattern.
Check test function naming
Even if the file is found, pytest only runs functions that start withtest_. Make sure your test functions follow this convention (e.g.,def test_my_feature():instead ofdef my_test_function():). Usepytest --collect-onlyto see exactly which tests pytest detects—this will show you if the file is being found but the functions aren't.Update pytest to the latest version
Older pytest versions might have bugs or different default behaviors. Runpip install --upgrade pytestto get the latest release, then try again.
If none of these steps resolve the issue, sharing details like your project file structure, any existing config files, or the exact commands you're running would help dig deeper!
内容的提问来源于stack exchange,提问作者Raghav

